CppEditor: Make a few CppModelManager functions static

... to simplify code using it.

Change-Id: Ib2bfbb5a17a1d48088a9cf4973d4c3f006cd34e4
Reviewed-by: Christian Kandeler <christian.kandeler@qt.io>
This commit is contained in:
hjk
2023-07-12 09:47:29 +02:00
parent 8f82e76ba1
commit 0b83f110f4
80 changed files with 505 additions and 619 deletions

View File

@@ -392,7 +392,7 @@ void AutotestPluginPrivate::onRunUnderCursorTriggered(TestRunMode mode)
const int line = currentEditor->currentLine(); const int line = currentEditor->currentLine();
const FilePath filePath = currentEditor->textDocument()->filePath(); const FilePath filePath = currentEditor->textDocument()->filePath();
const CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::snapshot();
const CPlusPlus::Document::Ptr doc = snapshot.document(filePath); const CPlusPlus::Document::Ptr doc = snapshot.document(filePath);
if (doc.isNull()) // not part of C++ snapshot if (doc.isNull()) // not part of C++ snapshot
return; return;

View File

@@ -104,9 +104,8 @@ bool BoostTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
if (doc.isNull() || !includesBoostTest(doc, m_cppSnapshot) || !hasBoostTestMacros(doc)) if (doc.isNull() || !includesBoostTest(doc, m_cppSnapshot) || !hasBoostTestMacros(doc))
return false; return false;
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance();
const QList<CppEditor::ProjectPart::ConstPtr> projectParts const QList<CppEditor::ProjectPart::ConstPtr> projectParts
= modelManager->projectPart(fileName); = CppEditor::CppModelManager::projectPart(fileName);
if (projectParts.isEmpty()) // happens if shutting down while parsing if (projectParts.isEmpty()) // happens if shutting down while parsing
return false; return false;
const CppEditor::ProjectPart::ConstPtr projectPart = projectParts.first(); const CppEditor::ProjectPart::ConstPtr projectPart = projectParts.first();

View File

@@ -178,10 +178,9 @@ QList<ITestConfiguration *> BoostTestTreeItem::getAllTestConfigurations() const
++funcChildren; ++funcChildren;
}); });
if (funcChildren) { if (funcChildren) {
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
testsPerProjectfile[item->proFile()].testCases += funcChildren; testsPerProjectfile[item->proFile()].testCases += funcChildren;
testsPerProjectfile[item->proFile()].internalTargets.unite(cppMM->internalTargets(item->filePath())); testsPerProjectfile[item->proFile()].internalTargets.unite(
CppEditor::CppModelManager::internalTargets(item->filePath()));
} }
}); });
@@ -219,8 +218,6 @@ QList<ITestConfiguration *> BoostTestTreeItem::getTestConfigurations(
if (!item->enabled()) // ignore child tests known to be disabled when using run selected if (!item->enabled()) // ignore child tests known to be disabled when using run selected
return; return;
if (predicate(item)) { if (predicate(item)) {
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
QString tcName = item->name(); QString tcName = item->name();
if (item->state().testFlag(BoostTestTreeItem::Templated)) if (item->state().testFlag(BoostTestTreeItem::Templated))
tcName.append("<*"); tcName.append("<*");
@@ -229,7 +226,8 @@ QList<ITestConfiguration *> BoostTestTreeItem::getTestConfigurations(
tcName = handleSpecialFunctionNames(tcName); tcName = handleSpecialFunctionNames(tcName);
testCasesForProjectFile[item->proFile()].testCases.append( testCasesForProjectFile[item->proFile()].testCases.append(
item->prependWithParentsSuitePaths(tcName)); item->prependWithParentsSuitePaths(tcName));
testCasesForProjectFile[item->proFile()].internalTargets.unite(cppMM->internalTargets(item->filePath())); testCasesForProjectFile[item->proFile()].internalTargets.unite(
CppEditor::CppModelManager::internalTargets(item->filePath()));
} }
}); });
@@ -265,8 +263,6 @@ ITestConfiguration *BoostTestTreeItem::testConfiguration() const
{ {
ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject(); ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject();
QTC_ASSERT(project, return nullptr); QTC_ASSERT(project, return nullptr);
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return nullptr);
const Type itemType = type(); const Type itemType = type();
if (itemType == TestSuite || itemType == TestCase) { if (itemType == TestSuite || itemType == TestCase) {
@@ -300,7 +296,7 @@ ITestConfiguration *BoostTestTreeItem::testConfiguration() const
config->setProjectFile(proFile()); config->setProjectFile(proFile());
config->setProject(project); config->setProject(project);
config->setTestCases(testCases); config->setTestCases(testCases);
config->setInternalTargets(cppMM->internalTargets(filePath())); config->setInternalTargets(CppEditor::CppModelManager::internalTargets(filePath()));
return config; return config;
} }
return nullptr; return nullptr;

View File

@@ -99,7 +99,6 @@ bool CatchTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
if (doc.isNull() || !includesCatchHeader(doc, m_cppSnapshot)) if (doc.isNull() || !includesCatchHeader(doc, m_cppSnapshot))
return false; return false;
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance();
const QString &filePath = doc->filePath().toString(); const QString &filePath = doc->filePath().toString();
const QByteArray &fileContent = getFileContent(fileName); const QByteArray &fileContent = getFileContent(fileName);
@@ -115,7 +114,8 @@ bool CatchTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
} }
const QList<CppEditor::ProjectPart::ConstPtr> projectParts = modelManager->projectPart(fileName); const QList<CppEditor::ProjectPart::ConstPtr> projectParts
= CppEditor::CppModelManager::projectPart(fileName);
if (projectParts.isEmpty()) // happens if shutting down while parsing if (projectParts.isEmpty()) // happens if shutting down while parsing
return false; return false;
FilePath proFile; FilePath proFile;

View File

@@ -145,8 +145,6 @@ ITestConfiguration *CatchTreeItem::testConfiguration() const
{ {
ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject(); ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject();
QTC_ASSERT(project, return nullptr); QTC_ASSERT(project, return nullptr);
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return nullptr);
if (type() != TestCase) if (type() != TestCase)
return nullptr; return nullptr;
@@ -157,7 +155,7 @@ ITestConfiguration *CatchTreeItem::testConfiguration() const
config->setProjectFile(proFile()); config->setProjectFile(proFile());
config->setProject(project); config->setProject(project);
config->setTestCases(QStringList(testCasesString())); config->setTestCases(QStringList(testCasesString()));
config->setInternalTargets(cppMM->internalTargets(filePath())); config->setInternalTargets(CppEditor::CppModelManager::internalTargets(filePath()));
return config; return config;
} }
@@ -180,8 +178,6 @@ static void collectTestInfo(const TestTreeItem *item,
bool ignoreCheckState) bool ignoreCheckState)
{ {
QTC_ASSERT(item, return); QTC_ASSERT(item, return);
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
const int childCount = item->childCount(); const int childCount = item->childCount();
if (item->type() == TestTreeItem::GroupNode) { if (item->type() == TestTreeItem::GroupNode) {
item->forFirstLevelChildItems([&testCasesForProfile, ignoreCheckState](TestTreeItem *it) { item->forFirstLevelChildItems([&testCasesForProfile, ignoreCheckState](TestTreeItem *it) {
@@ -198,15 +194,16 @@ static void collectTestInfo(const TestTreeItem *item,
CatchTreeItem *current = static_cast<CatchTreeItem *>(it); CatchTreeItem *current = static_cast<CatchTreeItem *>(it);
testCasesForProfile[projectFile].names.append(current->testCasesString()); testCasesForProfile[projectFile].names.append(current->testCasesString());
}); });
testCasesForProfile[projectFile].internalTargets.unite(cppMM->internalTargets(item->filePath())); testCasesForProfile[projectFile].internalTargets.unite(
CppEditor::CppModelManager::internalTargets(item->filePath()));
} else if (item->checked() == Qt::PartiallyChecked) { } else if (item->checked() == Qt::PartiallyChecked) {
item->forFirstLevelChildItems([&testCasesForProfile, cppMM](TestTreeItem *child) { item->forFirstLevelChildItems([&testCasesForProfile](TestTreeItem *child) {
QTC_ASSERT(child->type() == TestTreeItem::TestCase, return); QTC_ASSERT(child->type() == TestTreeItem::TestCase, return);
if (child->checked() == Qt::Checked) { if (child->checked() == Qt::Checked) {
CatchTreeItem *current = static_cast<CatchTreeItem *>(child); CatchTreeItem *current = static_cast<CatchTreeItem *>(child);
testCasesForProfile[child->proFile()].names.append(current->testCasesString()); testCasesForProfile[child->proFile()].names.append(current->testCasesString());
testCasesForProfile[child->proFile()].internalTargets.unite( testCasesForProfile[child->proFile()].internalTargets.unite(
cppMM->internalTargets(child->filePath())); CppEditor::CppModelManager::internalTargets(child->filePath()));
} }
}); });
@@ -222,13 +219,11 @@ static void collectFailedTestInfo(const CatchTreeItem *item,
item->forAllChildItems([&testCasesForProfile](TestTreeItem *it) { item->forAllChildItems([&testCasesForProfile](TestTreeItem *it) {
QTC_ASSERT(it, return); QTC_ASSERT(it, return);
QTC_ASSERT(it->parentItem(), return); QTC_ASSERT(it->parentItem(), return);
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
if (it->type() == TestTreeItem::TestCase && it->data(0, FailedRole).toBool()) { if (it->type() == TestTreeItem::TestCase && it->data(0, FailedRole).toBool()) {
CatchTreeItem *current = static_cast<CatchTreeItem *>(it); CatchTreeItem *current = static_cast<CatchTreeItem *>(it);
testCasesForProfile[it->proFile()].names.append(current->testCasesString()); testCasesForProfile[it->proFile()].names.append(current->testCasesString());
testCasesForProfile[it->proFile()].internalTargets.unite( testCasesForProfile[it->proFile()].internalTargets.unite(
cppMM->internalTargets(it->filePath())); CppEditor::CppModelManager::internalTargets(it->filePath()));
} }
}); });
} }
@@ -270,8 +265,6 @@ QList<ITestConfiguration *> CatchTreeItem::getFailedTestConfigurations() const
QList<ITestConfiguration *> CatchTreeItem::getTestConfigurationsForFile(const FilePath &fileName) const QList<ITestConfiguration *> CatchTreeItem::getTestConfigurationsForFile(const FilePath &fileName) const
{ {
QList<ITestConfiguration *> result; QList<ITestConfiguration *> result;
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return result);
ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject(); ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject();
if (!project || type() != Root) if (!project || type() != Root)
@@ -296,7 +289,8 @@ QList<ITestConfiguration *> CatchTreeItem::getTestConfigurationsForFile(const Fi
testConfig->setTestCases(testCases); testConfig->setTestCases(testCases);
testConfig->setProjectFile(item->proFile()); testConfig->setProjectFile(item->proFile());
testConfig->setProject(ProjectExplorer::ProjectManager::startupProject()); testConfig->setProject(ProjectExplorer::ProjectManager::startupProject());
testConfig->setInternalTargets(cppMM->internalTargets(item->filePath())); testConfig->setInternalTargets(
CppEditor::CppModelManager::internalTargets(item->filePath()));
result << testConfig; result << testConfig;
} }

View File

@@ -86,7 +86,6 @@ bool GTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
} }
const FilePath filePath = doc->filePath(); const FilePath filePath = doc->filePath();
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance();
CPlusPlus::Document::Ptr document = m_cppSnapshot.preprocessedDocument(fileContent, fileName); CPlusPlus::Document::Ptr document = m_cppSnapshot.preprocessedDocument(fileContent, fileName);
document->check(); document->check();
CPlusPlus::AST *ast = document->translationUnit()->ast(); CPlusPlus::AST *ast = document->translationUnit()->ast();
@@ -95,7 +94,8 @@ bool GTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
const QMap<GTestCaseSpec, GTestCodeLocationList> result = visitor.gtestFunctions(); const QMap<GTestCaseSpec, GTestCodeLocationList> result = visitor.gtestFunctions();
FilePath proFile; FilePath proFile;
const QList<CppEditor::ProjectPart::ConstPtr> &ppList = modelManager->projectPart(filePath); const QList<CppEditor::ProjectPart::ConstPtr> &ppList =
CppEditor::CppModelManager::projectPart(filePath);
if (!ppList.isEmpty()) if (!ppList.isEmpty())
proFile = FilePath::fromString(ppList.first()->projectFile); proFile = FilePath::fromString(ppList.first()->projectFile);
else else

View File

@@ -504,14 +504,14 @@ QString GTestTreeItem::nameSuffix() const
QSet<QString> internalTargets(const TestTreeItem &item) QSet<QString> internalTargets(const TestTreeItem &item)
{ {
QSet<QString> result; QSet<QString> result;
const auto cppMM = CppEditor::CppModelManager::instance(); const auto projectInfo = CppEditor::CppModelManager::projectInfo(
const auto projectInfo = cppMM->projectInfo(ProjectExplorer::ProjectManager::startupProject()); ProjectExplorer::ProjectManager::startupProject());
if (!projectInfo) if (!projectInfo)
return {}; return {};
const FilePath filePath = item.filePath(); const FilePath filePath = item.filePath();
const QVector<CppEditor::ProjectPart::ConstPtr> projectParts = projectInfo->projectParts(); const QVector<CppEditor::ProjectPart::ConstPtr> projectParts = projectInfo->projectParts();
if (projectParts.isEmpty()) if (projectParts.isEmpty())
return cppMM->dependingInternalTargets(item.filePath()); return CppEditor::CppModelManager::dependingInternalTargets(item.filePath());
for (const CppEditor::ProjectPart::ConstPtr &projectPart : projectParts) { for (const CppEditor::ProjectPart::ConstPtr &projectPart : projectParts) {
if (FilePath::fromString(projectPart->projectFile) == item.proFile() if (FilePath::fromString(projectPart->projectFile) == item.proFile()
&& Utils::anyOf(projectPart->files, [&filePath](const CppEditor::ProjectFile &pf) { && Utils::anyOf(projectPart->files, [&filePath](const CppEditor::ProjectFile &pf) {
@@ -519,7 +519,7 @@ QSet<QString> internalTargets(const TestTreeItem &item)
})) { })) {
result.insert(projectPart->buildSystemTarget); result.insert(projectPart->buildSystemTarget);
if (projectPart->buildTargetType != ProjectExplorer::BuildTargetType::Executable) if (projectPart->buildTargetType != ProjectExplorer::BuildTargetType::Executable)
result.unite(cppMM->dependingInternalTargets(filePath)); result.unite(CppEditor::CppModelManager::dependingInternalTargets(filePath));
} }
} }
return result; return result;

View File

@@ -28,14 +28,14 @@ void CppParser::init(const QSet<FilePath> &filesToParse, bool fullParse)
{ {
Q_UNUSED(filesToParse) Q_UNUSED(filesToParse)
Q_UNUSED(fullParse) Q_UNUSED(fullParse)
m_cppSnapshot = CppEditor::CppModelManager::instance()->snapshot(); m_cppSnapshot = CppEditor::CppModelManager::snapshot();
m_workingCopy = CppEditor::CppModelManager::instance()->workingCopy(); m_workingCopy = CppEditor::CppModelManager::workingCopy();
} }
bool CppParser::selectedForBuilding(const FilePath &fileName) bool CppParser::selectedForBuilding(const FilePath &fileName)
{ {
QList<CppEditor::ProjectPart::ConstPtr> projParts = QList<CppEditor::ProjectPart::ConstPtr> projParts =
CppEditor::CppModelManager::instance()->projectPart(fileName); CppEditor::CppModelManager::projectPart(fileName);
return !projParts.isEmpty() && projParts.at(0)->selectedForBuilding; return !projParts.isEmpty() && projParts.at(0)->selectedForBuilding;
} }
@@ -62,8 +62,8 @@ bool precompiledHeaderContains(const CPlusPlus::Snapshot &snapshot,
const QString &cacheString, const QString &cacheString,
const std::function<bool(const FilePath &)> &checker) const std::function<bool(const FilePath &)> &checker)
{ {
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance(); const QList<CppEditor::ProjectPart::ConstPtr> projectParts
const QList<CppEditor::ProjectPart::ConstPtr> projectParts = modelManager->projectPart(filePath); = CppEditor::CppModelManager::projectPart(filePath);
if (projectParts.isEmpty()) if (projectParts.isEmpty())
return false; return false;
const QStringList precompiledHeaders = projectParts.first()->precompiledHeaders; const QStringList precompiledHeaders = projectParts.first()->precompiledHeaders;

View File

@@ -74,7 +74,7 @@ static bool includesQtTest(const CPlusPlus::Document::Ptr &doc, const CPlusPlus:
static bool qtTestLibDefined(const FilePath &fileName) static bool qtTestLibDefined(const FilePath &fileName)
{ {
const QList<CppEditor::ProjectPart::ConstPtr> parts = const QList<CppEditor::ProjectPart::ConstPtr> parts =
CppEditor::CppModelManager::instance()->projectPart(fileName); CppEditor::CppModelManager::projectPart(fileName);
if (parts.size() > 0) { if (parts.size() > 0) {
return Utils::anyOf(parts.at(0)->projectMacros, [](const ProjectExplorer::Macro &macro) { return Utils::anyOf(parts.at(0)->projectMacros, [](const ProjectExplorer::Macro &macro) {
return macro.key == "QT_TESTLIB_LIB"; return macro.key == "QT_TESTLIB_LIB";
@@ -83,11 +83,10 @@ static bool qtTestLibDefined(const FilePath &fileName)
return false; return false;
} }
TestCases QtTestParser::testCases(const CppEditor::CppModelManager *modelManager, TestCases QtTestParser::testCases(const FilePath &filePath) const
const FilePath &filePath) const
{ {
const QByteArray &fileContent = getFileContent(filePath); const QByteArray &fileContent = getFileContent(filePath);
CPlusPlus::Document::Ptr document = modelManager->document(filePath); CPlusPlus::Document::Ptr document = CppEditor::CppModelManager::document(filePath);
if (document.isNull()) if (document.isNull())
return {}; return {};
@@ -305,8 +304,7 @@ bool QtTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
return false; return false;
} }
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance(); TestCases testCaseList(testCases(fileName));
TestCases testCaseList(testCases(modelManager, fileName));
bool reported = false; bool reported = false;
// we might be in a reparse without the original entry point with the QTest::qExec() // we might be in a reparse without the original entry point with the QTest::qExec()
if (testCaseList.isEmpty() && !oldTestCases.empty()) if (testCaseList.isEmpty() && !oldTestCases.empty())
@@ -319,7 +317,7 @@ bool QtTestParser::processDocument(QPromise<TestParseResultPtr> &promise,
continue; continue;
QList<CppEditor::ProjectPart::ConstPtr> projectParts QList<CppEditor::ProjectPart::ConstPtr> projectParts
= modelManager->projectPart(fileName); = CppEditor::CppModelManager::projectPart(fileName);
if (projectParts.isEmpty()) // happens if shutting down while parsing if (projectParts.isEmpty()) // happens if shutting down while parsing
return false; return false;

View File

@@ -10,8 +10,6 @@
#include <optional> #include <optional>
namespace CppEditor { class CppModelManager; }
namespace Autotest { namespace Autotest {
namespace Internal { namespace Internal {
@@ -40,8 +38,7 @@ public:
const Utils::FilePath &fileName) override; const Utils::FilePath &fileName) override;
private: private:
TestCases testCases(const CppEditor::CppModelManager *modelManager, TestCases testCases(const Utils::FilePath &fileName) const;
const Utils::FilePath &fileName) const;
QHash<QString, QtTestCodeLocationList> checkForDataTags(const Utils::FilePath &fileName) const; QHash<QString, QtTestCodeLocationList> checkForDataTags(const Utils::FilePath &fileName) const;
struct TestCaseData { struct TestCaseData {
Utils::FilePath fileName; Utils::FilePath fileName;

View File

@@ -120,8 +120,6 @@ ITestConfiguration *QtTestTreeItem::testConfiguration() const
{ {
ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject(); ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::startupProject();
QTC_ASSERT(project, return nullptr); QTC_ASSERT(project, return nullptr);
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return nullptr);
QtTestConfiguration *config = nullptr; QtTestConfiguration *config = nullptr;
switch (type()) { switch (type()) {
@@ -155,15 +153,13 @@ ITestConfiguration *QtTestTreeItem::testConfiguration() const
return nullptr; return nullptr;
} }
if (config) if (config)
config->setInternalTargets(cppMM->internalTargets(filePath())); config->setInternalTargets(CppEditor::CppModelManager::internalTargets(filePath()));
return config; return config;
} }
static void fillTestConfigurationsFromCheckState(const TestTreeItem *item, static void fillTestConfigurationsFromCheckState(const TestTreeItem *item,
QList<ITestConfiguration *> &testConfigurations) QList<ITestConfiguration *> &testConfigurations)
{ {
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
QTC_ASSERT(item, return); QTC_ASSERT(item, return);
if (item->type() == TestTreeItem::GroupNode) { if (item->type() == TestTreeItem::GroupNode) {
for (int row = 0, count = item->childCount(); row < count; ++row) for (int row = 0, count = item->childCount(); row < count; ++row)
@@ -198,15 +194,14 @@ static void fillTestConfigurationsFromCheckState(const TestTreeItem *item,
testConfig->setTestCases(testCases); testConfig->setTestCases(testCases);
testConfig->setProjectFile(item->proFile()); testConfig->setProjectFile(item->proFile());
testConfig->setProject(ProjectExplorer::ProjectManager::startupProject()); testConfig->setProject(ProjectExplorer::ProjectManager::startupProject());
testConfig->setInternalTargets(cppMM->internalTargets(item->filePath())); testConfig->setInternalTargets(
CppEditor::CppModelManager::internalTargets(item->filePath()));
testConfigurations << testConfig; testConfigurations << testConfig;
} }
} }
static void collectFailedTestInfo(TestTreeItem *item, QList<ITestConfiguration *> &testConfigs) static void collectFailedTestInfo(TestTreeItem *item, QList<ITestConfiguration *> &testConfigs)
{ {
const auto cppMM = CppEditor::CppModelManager::instance();
QTC_ASSERT(cppMM, return);
QTC_ASSERT(item, return); QTC_ASSERT(item, return);
if (item->type() == TestTreeItem::GroupNode) { if (item->type() == TestTreeItem::GroupNode) {
for (int row = 0, count = item->childCount(); row < count; ++row) for (int row = 0, count = item->childCount(); row < count; ++row)
@@ -232,7 +227,8 @@ static void collectFailedTestInfo(TestTreeItem *item, QList<ITestConfiguration *
testConfig->setTestCases(testCases); testConfig->setTestCases(testCases);
testConfig->setProjectFile(item->proFile()); testConfig->setProjectFile(item->proFile());
testConfig->setProject(ProjectExplorer::ProjectManager::startupProject()); testConfig->setProject(ProjectExplorer::ProjectManager::startupProject());
testConfig->setInternalTargets(cppMM->internalTargets(item->filePath())); testConfig->setInternalTargets(
CppEditor::CppModelManager::internalTargets(item->filePath()));
testConfigs << testConfig; testConfigs << testConfig;
} }

View File

@@ -82,9 +82,10 @@ static bool includesQtQuickTest(const CPlusPlus::Document::Ptr &doc,
return false; return false;
} }
static QString quickTestSrcDir(const CppEditor::CppModelManager *cppMM, const FilePath &fileName) static QString quickTestSrcDir(const FilePath &fileName)
{ {
const QList<CppEditor::ProjectPart::ConstPtr> parts = cppMM->projectPart(fileName); const QList<CppEditor::ProjectPart::ConstPtr> parts =
CppEditor::CppModelManager::projectPart(fileName);
if (parts.size() > 0) { if (parts.size() > 0) {
const ProjectExplorer::Macros &macros = parts.at(0)->projectMacros; const ProjectExplorer::Macros &macros = parts.at(0)->projectMacros;
auto found = std::find_if(macros.cbegin(), macros.cend(), auto found = std::find_if(macros.cbegin(), macros.cend(),
@@ -252,17 +253,17 @@ bool QuickTestParser::handleQtQuickTest(QPromise<TestParseResultPtr> &promise,
CPlusPlus::Document::Ptr document, CPlusPlus::Document::Ptr document,
ITestFramework *framework) ITestFramework *framework)
{ {
const CppEditor::CppModelManager *modelManager = CppEditor::CppModelManager::instance();
if (quickTestName(document).isEmpty()) if (quickTestName(document).isEmpty())
return false; return false;
QList<CppEditor::ProjectPart::ConstPtr> ppList = modelManager->projectPart(document->filePath()); QList<CppEditor::ProjectPart::ConstPtr> ppList =
CppEditor::CppModelManager::projectPart(document->filePath());
if (ppList.isEmpty()) // happens if shutting down while parsing if (ppList.isEmpty()) // happens if shutting down while parsing
return false; return false;
const FilePath cppFileName = document->filePath(); const FilePath cppFileName = document->filePath();
const FilePath proFile = FilePath::fromString(ppList.at(0)->projectFile); const FilePath proFile = FilePath::fromString(ppList.at(0)->projectFile);
m_mainCppFiles.insert(cppFileName, proFile); m_mainCppFiles.insert(cppFileName, proFile);
const FilePath srcDir = FilePath::fromString(quickTestSrcDir(modelManager, cppFileName)); const FilePath srcDir = FilePath::fromString(quickTestSrcDir(cppFileName));
if (srcDir.isEmpty()) if (srcDir.isEmpty())
return false; return false;

View File

@@ -370,8 +370,8 @@ bool QuickTestTreeItem::isGroupable() const
QSet<QString> internalTargets(const FilePath &proFile) QSet<QString> internalTargets(const FilePath &proFile)
{ {
QSet<QString> result; QSet<QString> result;
const auto cppMM = CppEditor::CppModelManager::instance(); const auto projectInfo =
const auto projectInfo = cppMM->projectInfo(ProjectExplorer::ProjectManager::startupProject()); CppEditor::CppModelManager::projectInfo(ProjectExplorer::ProjectManager::startupProject());
if (!projectInfo) if (!projectInfo)
return {}; return {};
for (const CppEditor::ProjectPart::ConstPtr &projectPart : projectInfo->projectParts()) { for (const CppEditor::ProjectPart::ConstPtr &projectPart : projectInfo->projectParts()) {

View File

@@ -337,7 +337,7 @@ void TestCodeParser::scanForTests(const QSet<FilePath> &filePaths,
qCDebug(LOG) << QDateTime::currentDateTime().toString("hh:mm:ss.zzz") << "StartParsing"; qCDebug(LOG) << QDateTime::currentDateTime().toString("hh:mm:ss.zzz") << "StartParsing";
m_parsingTimer.restart(); m_parsingTimer.restart();
QSet<QString> extensions; QSet<QString> extensions;
const auto cppSnapshot = CppEditor::CppModelManager::instance()->snapshot(); const auto cppSnapshot = CppEditor::CppModelManager::snapshot();
for (ITestParser *parser : codeParsers) { for (ITestParser *parser : codeParsers) {
parser->init(files, isFullParse); parser->init(files, isFullParse);

View File

@@ -65,7 +65,7 @@ static void extractAllFiles(const DebuggerRunTool *runTool, QStringList &include
FilePaths &headers, FilePaths &sources, FilePaths &assemblers) FilePaths &headers, FilePaths &sources, FilePaths &assemblers)
{ {
const auto project = runTool->runControl()->project(); const auto project = runTool->runControl()->project();
const CppEditor::ProjectInfo::ConstPtr info = CppModelManager::instance()->projectInfo(project); const CppEditor::ProjectInfo::ConstPtr info = CppModelManager::projectInfo(project);
if (!info) if (!info)
return; return;
const QVector<ProjectPart::ConstPtr> parts = info->projectParts(); const QVector<ProjectPart::ConstPtr> parts = info->projectParts();

View File

@@ -53,7 +53,7 @@ void ClangCodeModelPlugin::generateCompilationDB()
if (!target) if (!target)
return; return;
const auto projectInfo = CppModelManager::instance()->projectInfo(target->project()); const auto projectInfo = CppModelManager::projectInfo(target->project());
if (!projectInfo) if (!projectInfo)
return; return;
FilePath baseDir = projectInfo->buildRoot(); FilePath baseDir = projectInfo->buildRoot();
@@ -78,7 +78,7 @@ ClangCodeModelPlugin::~ClangCodeModelPlugin()
void ClangCodeModelPlugin::initialize() void ClangCodeModelPlugin::initialize()
{ {
TaskHub::addCategory({Constants::TASK_CATEGORY_DIAGNOSTICS, Tr::tr("Clang Code Model")}); TaskHub::addCategory({Constants::TASK_CATEGORY_DIAGNOSTICS, Tr::tr("Clang Code Model")});
CppEditor::CppModelManager::instance()->activateClangCodeModel( CppEditor::CppModelManager::activateClangCodeModel(
std::make_unique<ClangModelManagerSupport>()); std::make_unique<ClangModelManagerSupport>());
createCompilationDBAction(); createCompilationDBAction();
@@ -135,8 +135,8 @@ void ClangCodeModelPlugin::createCompilationDBAction()
"No active project."); "No active project.");
return; return;
} }
const CppEditor::ProjectInfo::ConstPtr projectInfo = CppEditor::CppModelManager::instance() const CppEditor::ProjectInfo::ConstPtr projectInfo =
->projectInfo(project); CppEditor::CppModelManager::projectInfo(project);
if (!projectInfo || projectInfo->projectParts().isEmpty()) { if (!projectInfo || projectInfo->projectParts().isEmpty()) {
MessageManager::writeDisrupting("Cannot generate compilation database: " MessageManager::writeDisrupting("Cannot generate compilation database: "
"Project has no C/C++ project parts."); "Project has no C/C++ project parts.");

View File

@@ -407,7 +407,7 @@ ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir, c
const Utils::FilePath includeDir const Utils::FilePath includeDir
= CppEditor::ClangdSettings(d->settings).clangdIncludePath(); = CppEditor::ClangdSettings(d->settings).clangdIncludePath();
CppEditor::CompilerOptionsBuilder optionsBuilder = clangOptionsBuilder( CppEditor::CompilerOptionsBuilder optionsBuilder = clangOptionsBuilder(
*CppEditor::CppModelManager::instance()->fallbackProjectPart(), *CppEditor::CppModelManager::fallbackProjectPart(),
warningsConfigForProject(nullptr), includeDir, {}); warningsConfigForProject(nullptr), includeDir, {});
const CppEditor::UsePrecompiledHeaders usePch = CppEditor::getPchUsage(); const CppEditor::UsePrecompiledHeaders usePch = CppEditor::getPchUsage();
const QJsonArray projectPartOptions = fullProjectPartOptions( const QJsonArray projectPartOptions = fullProjectPartOptions(
@@ -755,7 +755,7 @@ bool ClangdClient::fileBelongsToProject(const Utils::FilePath &filePath) const
RefactoringChangesData *ClangdClient::createRefactoringChangesBackend() const RefactoringChangesData *ClangdClient::createRefactoringChangesBackend() const
{ {
return new CppEditor::CppRefactoringChangesData( return new CppEditor::CppRefactoringChangesData(
CppEditor::CppModelManager::instance()->snapshot()); CppEditor::CppModelManager::snapshot());
} }
QVersionNumber ClangdClient::versionNumber() const QVersionNumber ClangdClient::versionNumber() const
@@ -875,8 +875,7 @@ void ClangdClient::updateParserConfig(const Utils::FilePath &filePath,
// TODO: Should we write the editor defines into the json file? It seems strange // TODO: Should we write the editor defines into the json file? It seems strange
// that they should affect the index only while the file is open in the editor. // that they should affect the index only while the file is open in the editor.
const auto projectPart = !config.preferredProjectPartId.isEmpty() const auto projectPart = !config.preferredProjectPartId.isEmpty()
? CppEditor::CppModelManager::instance()->projectPartForId( ? CppEditor::CppModelManager::projectPartForId(config.preferredProjectPartId)
config.preferredProjectPartId)
: projectPartForFile(filePath); : projectPartForFile(filePath);
if (!projectPart) if (!projectPart)
return; return;

View File

@@ -609,7 +609,7 @@ QList<AssistProposalItemInterface *> ClangdCompletionAssistProcessor::generateCo
if (!doc || pos < 0 || !Utils::anyOf(items, criterion)) if (!doc || pos < 0 || !Utils::anyOf(items, criterion))
return itemGenerator(items); return itemGenerator(items);
const QString content = doc->toPlainText(); const QString content = doc->toPlainText();
const bool requiresSignal = CppModelManager::instance()->getSignalSlotType( const bool requiresSignal = CppModelManager::getSignalSlotType(
filePath(), content.toUtf8(), pos) filePath(), content.toUtf8(), pos)
== SignalSlotType::NewStyleSignal; == SignalSlotType::NewStyleSignal;
if (requiresSignal) if (requiresSignal)

View File

@@ -62,11 +62,6 @@ using namespace Utils;
namespace ClangCodeModel::Internal { namespace ClangCodeModel::Internal {
static CppModelManager *cppModelManager()
{
return CppModelManager::instance();
}
static Project *fallbackProject() static Project *fallbackProject()
{ {
if (Project * const p = ProjectTree::currentProject()) if (Project * const p = ProjectTree::currentProject())
@@ -202,10 +197,10 @@ ClangModelManagerSupport::ClangModelManagerSupport()
watchForInternalChanges(); watchForInternalChanges();
setupClangdConfigFile(); setupClangdConfigFile();
checkSystemForClangdSuitability(); checkSystemForClangdSuitability();
cppModelManager()->setCurrentDocumentFilter(std::make_unique<ClangdCurrentDocumentFilter>()); CppModelManager::setCurrentDocumentFilter(std::make_unique<ClangdCurrentDocumentFilter>());
cppModelManager()->setLocatorFilter(std::make_unique<ClangdAllSymbolsFilter>()); CppModelManager::setLocatorFilter(std::make_unique<ClangdAllSymbolsFilter>());
cppModelManager()->setClassesFilter(std::make_unique<ClangdClassesFilter>()); CppModelManager::setClassesFilter(std::make_unique<ClangdClassesFilter>());
cppModelManager()->setFunctionsFilter(std::make_unique<ClangdFunctionsFilter>()); CppModelManager::setFunctionsFilter(std::make_unique<ClangdFunctionsFilter>());
// Setup matchers // Setup matchers
LocatorMatcher::addMatcherCreator(MatcherType::AllSymbols, [] { LocatorMatcher::addMatcherCreator(MatcherType::AllSymbols, [] {
return LanguageClient::languageClientMatchers( return LanguageClient::languageClientMatchers(
@@ -226,7 +221,7 @@ ClangModelManagerSupport::ClangModelManagerSupport()
connect(editorManager, &EditorManager::currentEditorChanged, connect(editorManager, &EditorManager::currentEditorChanged,
this, &ClangModelManagerSupport::onCurrentEditorChanged); this, &ClangModelManagerSupport::onCurrentEditorChanged);
CppModelManager *modelManager = cppModelManager(); CppModelManager *modelManager = CppModelManager::instance();
connect(modelManager, &CppModelManager::abstractEditorSupportContentsUpdated, connect(modelManager, &CppModelManager::abstractEditorSupportContentsUpdated,
this, &ClangModelManagerSupport::onAbstractEditorSupportContentsUpdated); this, &ClangModelManagerSupport::onAbstractEditorSupportContentsUpdated);
connect(modelManager, &CppModelManager::abstractEditorSupportRemoved, connect(modelManager, &CppModelManager::abstractEditorSupportRemoved,
@@ -382,7 +377,7 @@ void ClangModelManagerSupport::checkUnused(const Link &link, SearchResult *searc
} }
} }
CppModelManager::instance()->modelManagerSupport( CppModelManager::modelManagerSupport(
CppModelManager::Backend::Builtin)->checkUnused(link, search, callback); CppModelManager::Backend::Builtin)->checkUnused(link, search, callback);
} }
@@ -409,7 +404,7 @@ void ClangModelManagerSupport::onCurrentEditorChanged(IEditor *editor)
{ {
// Update task hub issues for current CppEditorDocument // Update task hub issues for current CppEditorDocument
TaskHub::clearTasks(Constants::TASK_CATEGORY_DIAGNOSTICS); TaskHub::clearTasks(Constants::TASK_CATEGORY_DIAGNOSTICS);
if (!editor || !editor->document() || !cppModelManager()->isCppEditor(editor)) if (!editor || !editor->document() || !CppModelManager::isCppEditor(editor))
return; return;
const FilePath filePath = editor->document()->filePath(); const FilePath filePath = editor->document()->filePath();
@@ -460,12 +455,12 @@ static bool isProjectDataUpToDate(Project *project, ProjectInfoList projectInfo,
return false; return false;
ProjectInfoList newProjectInfo; ProjectInfoList newProjectInfo;
if (project) { if (project) {
if (const ProjectInfo::ConstPtr pi = CppModelManager::instance()->projectInfo(project)) if (const ProjectInfo::ConstPtr pi = CppModelManager::projectInfo(project))
newProjectInfo.append(pi); newProjectInfo.append(pi);
else else
return false; return false;
} else { } else {
newProjectInfo = CppModelManager::instance()->projectInfos(); newProjectInfo = CppModelManager::projectInfos();
} }
if (newProjectInfo.size() != projectInfo.size()) if (newProjectInfo.size() != projectInfo.size())
return false; return false;
@@ -486,8 +481,8 @@ void ClangModelManagerSupport::updateLanguageClient(Project *project)
ProjectInfoList projectInfo; ProjectInfoList projectInfo;
if (sessionModeEnabled()) { if (sessionModeEnabled()) {
project = nullptr; project = nullptr;
projectInfo = CppModelManager::instance()->projectInfos(); projectInfo = CppModelManager::projectInfos();
} else if (const ProjectInfo::ConstPtr pi = CppModelManager::instance()->projectInfo(project)) { } else if (const ProjectInfo::ConstPtr pi = CppModelManager::projectInfo(project)) {
projectInfo.append(pi); projectInfo.append(pi);
} else { } else {
return; return;
@@ -771,7 +766,7 @@ void ClangModelManagerSupport::onEditorOpened(IEditor *editor)
QTC_ASSERT(document, return); QTC_ASSERT(document, return);
auto textDocument = qobject_cast<TextEditor::TextDocument *>(document); auto textDocument = qobject_cast<TextEditor::TextDocument *>(document);
if (textDocument && cppModelManager()->isCppEditor(editor)) { if (textDocument && CppModelManager::isCppEditor(editor)) {
connectToWidgetsMarkContextMenuRequested(editor->widget()); connectToWidgetsMarkContextMenuRequested(editor->widget());
Project * project = ProjectManager::projectForFile(document->filePath()); Project * project = ProjectManager::projectForFile(document->filePath());

View File

@@ -695,7 +695,7 @@ Tasking::Group ClangTool::runRecipe(const RunSettings &runSettings,
} }
const ProjectInfo::ConstPtr projectInfoBeforeBuild const ProjectInfo::ConstPtr projectInfoBeforeBuild
= CppModelManager::instance()->projectInfo(target->project()); = CppModelManager::projectInfo(target->project());
const auto onTreeSetup = [this, storage, runSettings, diagnosticConfig, fileInfos, tempDir, const auto onTreeSetup = [this, storage, runSettings, diagnosticConfig, fileInfos, tempDir,
environment, projectInfoBeforeBuild](TaskTree &taskTree) { environment, projectInfoBeforeBuild](TaskTree &taskTree) {
@@ -710,7 +710,7 @@ Tasking::Group ClangTool::runRecipe(const RunSettings &runSettings,
ProjectExplorerPlugin::saveModifiedFiles(); ProjectExplorerPlugin::saveModifiedFiles();
Project *project = m_runControl->project(); Project *project = m_runControl->project();
const ProjectInfo::ConstPtr projectInfo = CppModelManager::instance()->projectInfo(project); const ProjectInfo::ConstPtr projectInfo = CppModelManager::projectInfo(project);
if (!projectInfo) { if (!projectInfo) {
m_infoBarWidget->setError(InfoBarWidget::Error, failedMessage, m_infoBarWidget->setError(InfoBarWidget::Error, failedMessage,
[this] { showOutputPane(); }); [this] { showOutputPane(); });
@@ -892,7 +892,7 @@ FileInfos ClangTool::collectFileInfos(Project *project, FileSelection fileSelect
return {}; return {};
} }
const auto projectInfo = CppModelManager::instance()->projectInfo(project); const auto projectInfo = CppModelManager::projectInfo(project);
QTC_ASSERT(projectInfo, return FileInfos()); QTC_ASSERT(projectInfo, return FileInfos());
const FileInfos allFileInfos = sortedFileInfos(projectInfo->projectParts()); const FileInfos allFileInfos = sortedFileInfos(projectInfo->projectParts());
@@ -1024,7 +1024,7 @@ static bool canAnalyzeProject(Project *project)
const bool projectSupportsLanguage = project->projectLanguages().contains(c) const bool projectSupportsLanguage = project->projectLanguages().contains(c)
|| project->projectLanguages().contains(cxx); || project->projectLanguages().contains(cxx);
return projectSupportsLanguage return projectSupportsLanguage
&& CppModelManager::instance()->projectInfo(project) && CppModelManager::projectInfo(project)
&& ToolChainKitAspect::cxxToolChain(target->kit()); && ToolChainKitAspect::cxxToolChain(target->kit());
} }
return false; return false;

View File

@@ -109,7 +109,7 @@ static VirtualFileSystemOverlay &vfso()
static FileInfo getFileInfo(const FilePath &file, Project *project) static FileInfo getFileInfo(const FilePath &file, Project *project)
{ {
const ProjectInfo::ConstPtr projectInfo = CppModelManager::instance()->projectInfo(project); const ProjectInfo::ConstPtr projectInfo = CppModelManager::projectInfo(project);
if (!projectInfo) if (!projectInfo)
return {}; return {};

View File

@@ -250,7 +250,7 @@ ParserTreeItem::ConstPtr Parser::getCachedOrParseDocumentTree(const CPlusPlus::D
void Parser::updateDocuments(const QSet<FilePath> &documentPaths) void Parser::updateDocuments(const QSet<FilePath> &documentPaths)
{ {
updateDocumentsFromSnapshot(documentPaths, CppEditor::CppModelManager::instance()->snapshot()); updateDocumentsFromSnapshot(documentPaths, CppEditor::CppModelManager::snapshot());
} }
void Parser::updateDocumentsFromSnapshot(const QSet<FilePath> &documentPaths, void Parser::updateDocumentsFromSnapshot(const QSet<FilePath> &documentPaths,
@@ -293,7 +293,7 @@ void Parser::resetData(const QHash<FilePath, QPair<QString, FilePaths>> &project
d->m_projectCache.clear(); d->m_projectCache.clear();
d->m_documentCache.clear(); d->m_documentCache.clear();
const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::snapshot();
for (auto it = projects.cbegin(); it != projects.cend(); ++it) { for (auto it = projects.cbegin(); it != projects.cend(); ++it) {
const auto projectData = it.value(); const auto projectData = it.value();
QSet<FilePath> commonFiles; QSet<FilePath> commonFiles;
@@ -313,7 +313,7 @@ void Parser::resetData(const QHash<FilePath, QPair<QString, FilePaths>> &project
void Parser::addProject(const FilePath &projectPath, const QString &projectName, void Parser::addProject(const FilePath &projectPath, const QString &projectName,
const FilePaths &filesInProject) const FilePaths &filesInProject)
{ {
const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::snapshot();
QSet<FilePath> commonFiles; QSet<FilePath> commonFiles;
for (const auto &fileInProject : filesInProject) { for (const auto &fileInProject : filesInProject) {
CPlusPlus::Document::Ptr doc = snapshot.document(fileInProject); CPlusPlus::Document::Ptr doc = snapshot.document(fileInProject);

View File

@@ -180,7 +180,7 @@ void CppcheckTool::check(const Utils::FilePaths &files)
return; return;
const CppEditor::ProjectInfo::ConstPtr info const CppEditor::ProjectInfo::ConstPtr info
= CppEditor::CppModelManager::instance()->projectInfo(m_project); = CppEditor::CppModelManager::projectInfo(m_project);
if (!info) if (!info)
return; return;
const QVector<CppEditor::ProjectPart::ConstPtr> parts = info->projectParts(); const QVector<CppEditor::ProjectPart::ConstPtr> parts = info->projectParts();

View File

@@ -56,7 +56,7 @@ void CppcheckTrigger::checkEditors(const QList<IEditor *> &editors)
using CppModelManager = CppEditor::CppModelManager; using CppModelManager = CppEditor::CppModelManager;
const CppEditor::ProjectInfo::ConstPtr info const CppEditor::ProjectInfo::ConstPtr info
= CppModelManager::instance()->projectInfo(m_currentProject); = CppModelManager::projectInfo(m_currentProject);
if (!info) if (!info)
return; return;

View File

@@ -16,26 +16,26 @@ using namespace Utils;
namespace CppEditor { namespace CppEditor {
AbstractEditorSupport::AbstractEditorSupport(CppModelManager *modelmanager, QObject *parent) : AbstractEditorSupport::AbstractEditorSupport(QObject *parent) :
QObject(parent), m_modelmanager(modelmanager), m_revision(1) QObject(parent), m_revision(1)
{ {
modelmanager->addExtraEditorSupport(this); CppModelManager::addExtraEditorSupport(this);
} }
AbstractEditorSupport::~AbstractEditorSupport() AbstractEditorSupport::~AbstractEditorSupport()
{ {
m_modelmanager->removeExtraEditorSupport(this); CppModelManager::removeExtraEditorSupport(this);
} }
void AbstractEditorSupport::updateDocument() void AbstractEditorSupport::updateDocument()
{ {
++m_revision; ++m_revision;
m_modelmanager->updateSourceFiles({filePath()}); CppModelManager::updateSourceFiles({filePath()});
} }
void AbstractEditorSupport::notifyAboutUpdatedContents() const void AbstractEditorSupport::notifyAboutUpdatedContents() const
{ {
m_modelmanager->emitAbstractEditorSupportContentsUpdated( CppModelManager::emitAbstractEditorSupportContentsUpdated(
filePath().toString(), sourceFilePath().toString(), contents()); filePath().toString(), sourceFilePath().toString(), contents());
} }

View File

@@ -13,14 +13,12 @@ namespace ProjectExplorer { class Project; }
namespace CppEditor { namespace CppEditor {
class CppModelManager;
class CPPEDITOR_EXPORT AbstractEditorSupport : public QObject class CPPEDITOR_EXPORT AbstractEditorSupport : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit AbstractEditorSupport(CppModelManager *modelmanager, QObject *parent = nullptr); explicit AbstractEditorSupport(QObject *parent = nullptr);
~AbstractEditorSupport() override; ~AbstractEditorSupport() override;
/// \returns the contents, encoded as UTF-8 /// \returns the contents, encoded as UTF-8
@@ -38,7 +36,6 @@ public:
static bool usePragmaOnce(ProjectExplorer::Project *project); static bool usePragmaOnce(ProjectExplorer::Project *project);
private: private:
CppModelManager *m_modelmanager;
unsigned m_revision; unsigned m_revision;
}; };

View File

@@ -92,8 +92,7 @@ ProjectPartInfo BaseEditorDocumentParser::projectPartInfo() const
BaseEditorDocumentParser::Ptr BaseEditorDocumentParser::get(const FilePath &filePath) BaseEditorDocumentParser::Ptr BaseEditorDocumentParser::get(const FilePath &filePath)
{ {
CppModelManager *cmmi = CppModelManager::instance(); if (CppEditorDocumentHandle *cppEditorDocument = CppModelManager::cppEditorDocument(filePath)) {
if (CppEditorDocumentHandle *cppEditorDocument = cmmi->cppEditorDocument(filePath)) {
if (BaseEditorDocumentProcessor *processor = cppEditorDocument->processor()) if (BaseEditorDocumentProcessor *processor = cppEditorDocument->processor())
return processor->parser(); return processor->parser();
} }
@@ -109,14 +108,14 @@ ProjectPartInfo BaseEditorDocumentParser::determineProjectPart(const QString &fi
{ {
Internal::ProjectPartChooser chooser; Internal::ProjectPartChooser chooser;
chooser.setFallbackProjectPart([](){ chooser.setFallbackProjectPart([](){
return CppModelManager::instance()->fallbackProjectPart(); return CppModelManager::fallbackProjectPart();
}); });
chooser.setProjectPartsForFile([](const QString &filePath) { chooser.setProjectPartsForFile([](const QString &filePath) {
return CppModelManager::instance()->projectPart(filePath); return CppModelManager::projectPart(filePath);
}); });
chooser.setProjectPartsFromDependenciesForFile([&](const QString &filePath) { chooser.setProjectPartsFromDependenciesForFile([&](const QString &filePath) {
const auto fileName = Utils::FilePath::fromString(filePath); const auto fileName = Utils::FilePath::fromString(filePath);
return CppModelManager::instance()->projectPartFromDependencies(fileName); return CppModelManager::projectPartFromDependencies(fileName);
}); });
const ProjectPartInfo chooserResult const ProjectPartInfo chooserResult

View File

@@ -39,7 +39,7 @@ void BaseEditorDocumentProcessor::run(bool projectsUpdated)
? Utils::Language::C ? Utils::Language::C
: Utils::Language::Cxx; : Utils::Language::Cxx;
runImpl({CppModelManager::instance()->workingCopy(), runImpl({CppModelManager::workingCopy(),
ProjectExplorer::ProjectManager::startupProject(), ProjectExplorer::ProjectManager::startupProject(),
languagePreference, languagePreference,
projectsUpdated}); projectsUpdated});
@@ -72,7 +72,7 @@ void BaseEditorDocumentProcessor::runParser(QPromise<void> &promise,
} }
parser->update(promise, updateParams); parser->update(promise, updateParams);
CppModelManager::instance()->finishedRefreshingSourceFiles({parser->filePath().toString()}); CppModelManager::finishedRefreshingSourceFiles({parser->filePath().toString()});
promise.setProgressValue(1); promise.setProgressValue(1);
} }

View File

@@ -218,8 +218,8 @@ private:
if (Symbol *s = Internal::CanonicalSymbol::canonicalSymbol( if (Symbol *s = Internal::CanonicalSymbol::canonicalSymbol(
m_scope, m_expression, typeOfExpression)) { m_scope, m_expression, typeOfExpression)) {
const QList<int> tokenIndices = CppModelManager::instance() const QList<int> tokenIndices =
->references(s, typeOfExpression.context()); CppModelManager::references(s, typeOfExpression.context());
result = toRanges(tokenIndices, m_document->translationUnit()); result = toRanges(tokenIndices, m_document->translationUnit());
} }

View File

@@ -59,8 +59,7 @@ void BuiltinEditorDocumentParser::updateImpl(const QPromise<void> &promise,
bool invalidateSnapshot = false, invalidateConfig = false; bool invalidateSnapshot = false, invalidateConfig = false;
CppModelManager *modelManager = CppModelManager::instance(); QByteArray configFile = CppModelManager::codeModelConfiguration();
QByteArray configFile = modelManager->codeModelConfiguration();
ProjectExplorer::HeaderPaths headerPaths; ProjectExplorer::HeaderPaths headerPaths;
FilePaths includedFiles; FilePaths includedFiles;
FilePaths precompiledHeaders; FilePaths precompiledHeaders;
@@ -131,7 +130,7 @@ void BuiltinEditorDocumentParser::updateImpl(const QPromise<void> &promise,
else else
invalidateSnapshot = true; invalidateSnapshot = true;
Snapshot globalSnapshot = modelManager->snapshot(); Snapshot globalSnapshot = CppModelManager::snapshot();
if (invalidateSnapshot) { if (invalidateSnapshot) {
state.snapshot = Snapshot(); state.snapshot = Snapshot();
@@ -172,19 +171,19 @@ void BuiltinEditorDocumentParser::updateImpl(const QPromise<void> &promise,
Internal::CppSourceProcessor sourceProcessor(state.snapshot, [&](const Document::Ptr &doc) { Internal::CppSourceProcessor sourceProcessor(state.snapshot, [&](const Document::Ptr &doc) {
const bool isInEditor = doc->filePath() == filePath(); const bool isInEditor = doc->filePath() == filePath();
Document::Ptr otherDoc = modelManager->document(doc->filePath()); Document::Ptr otherDoc = CppModelManager::document(doc->filePath());
unsigned newRev = otherDoc.isNull() ? 1U : otherDoc->revision() + 1; unsigned newRev = otherDoc.isNull() ? 1U : otherDoc->revision() + 1;
if (isInEditor) if (isInEditor)
newRev = qMax(rev + 1, newRev); newRev = qMax(rev + 1, newRev);
doc->setRevision(newRev); doc->setRevision(newRev);
modelManager->emitDocumentUpdated(doc); CppModelManager::emitDocumentUpdated(doc);
if (releaseSourceAndAST_) if (releaseSourceAndAST_)
doc->releaseSourceAndAST(); doc->releaseSourceAndAST();
}); });
sourceProcessor.setFileSizeLimitInMb(m_fileSizeLimitInMb); sourceProcessor.setFileSizeLimitInMb(m_fileSizeLimitInMb);
sourceProcessor.setCancelChecker([&promise] { return promise.isCanceled(); }); sourceProcessor.setCancelChecker([&promise] { return promise.isCanceled(); });
Snapshot globalSnapshot = modelManager->snapshot(); Snapshot globalSnapshot = CppModelManager::snapshot();
globalSnapshot.remove(filePath()); globalSnapshot.remove(filePath());
sourceProcessor.setGlobalSnapshot(globalSnapshot); sourceProcessor.setGlobalSnapshot(globalSnapshot);
sourceProcessor.setWorkingCopy(workingCopy); sourceProcessor.setWorkingCopy(workingCopy);

View File

@@ -183,7 +183,7 @@ BuiltinEditorDocumentProcessor::~BuiltinEditorDocumentProcessor()
void BuiltinEditorDocumentProcessor::runImpl( void BuiltinEditorDocumentProcessor::runImpl(
const BaseEditorDocumentParser::UpdateParams &updateParams) const BaseEditorDocumentParser::UpdateParams &updateParams)
{ {
m_parserFuture = Utils::asyncRun(CppModelManager::instance()->sharedThreadPool(), m_parserFuture = Utils::asyncRun(CppModelManager::sharedThreadPool(),
runParser, parser(), updateParams); runParser, parser(), updateParams);
} }
@@ -277,8 +277,7 @@ void BuiltinEditorDocumentProcessor::onParserFinished(CPlusPlus::Document::Ptr d
continue; continue;
if (cppEditorDoc->filePath() == document->filePath()) if (cppEditorDoc->filePath() == document->filePath())
continue; continue;
CPlusPlus::Document::Ptr cppDoc = CppModelManager::instance()->document( CPlusPlus::Document::Ptr cppDoc = CppModelManager::document(cppEditorDoc->filePath());
cppEditorDoc->filePath());
if (!cppDoc) if (!cppDoc)
continue; continue;
if (!cppDoc->includedFiles().contains(document->filePath())) if (!cppDoc->includedFiles().contains(document->filePath()))
@@ -325,7 +324,7 @@ SemanticInfo::Source BuiltinEditorDocumentProcessor::createSemanticInfoSource(bo
{ {
QByteArray source; QByteArray source;
int revision = 0; int revision = 0;
if (const auto entry = CppModelManager::instance()->workingCopy().get(filePath())) { if (const auto entry = CppModelManager::workingCopy().get(filePath())) {
source = entry->first; source = entry->first;
revision = entry->second; revision = entry->second;
} }

View File

@@ -105,7 +105,7 @@ void BuiltinModelManagerSupport::followSymbol(const CursorInEditor &data,
{ {
SymbolFinder finder; SymbolFinder finder;
m_followSymbol->findLink(data, processLinkCallback, m_followSymbol->findLink(data, processLinkCallback,
resolveTarget, CppModelManager::instance()->snapshot(), resolveTarget, CppModelManager::snapshot(),
data.editorWidget()->semanticInfo().doc, &finder, inNextSplit); data.editorWidget()->semanticInfo().doc, &finder, inNextSplit);
} }
@@ -125,7 +125,7 @@ void BuiltinModelManagerSupport::switchDeclDef(const CursorInEditor &data,
{ {
SymbolFinder finder; SymbolFinder finder;
m_followSymbol->switchDeclDef(data, processLinkCallback, m_followSymbol->switchDeclDef(data, processLinkCallback,
CppModelManager::instance()->snapshot(), data.editorWidget()->semanticInfo().doc, CppModelManager::snapshot(), data.editorWidget()->semanticInfo().doc,
&finder); &finder);
} }
@@ -144,47 +144,39 @@ void BuiltinModelManagerSupport::globalRename(const CursorInEditor &data,
const QString &replacement, const QString &replacement,
const std::function<void()> &callback) const std::function<void()> &callback)
{ {
CppModelManager *modelManager = CppModelManager::instance();
if (!modelManager)
return;
CppEditorWidget *editorWidget = data.editorWidget(); CppEditorWidget *editorWidget = data.editorWidget();
QTC_ASSERT(editorWidget, return;); QTC_ASSERT(editorWidget, return;);
SemanticInfo info = editorWidget->semanticInfo(); SemanticInfo info = editorWidget->semanticInfo();
info.snapshot = modelManager->snapshot(); info.snapshot = CppModelManager::snapshot();
info.snapshot.insert(info.doc); info.snapshot.insert(info.doc);
const QTextCursor &cursor = data.cursor(); const QTextCursor &cursor = data.cursor();
if (const CPlusPlus::Macro *macro = findCanonicalMacro(cursor, info.doc)) { if (const CPlusPlus::Macro *macro = findCanonicalMacro(cursor, info.doc)) {
modelManager->renameMacroUsages(*macro, replacement); CppModelManager::renameMacroUsages(*macro, replacement);
} else { } else {
Internal::CanonicalSymbol cs(info.doc, info.snapshot); Internal::CanonicalSymbol cs(info.doc, info.snapshot);
CPlusPlus::Symbol *canonicalSymbol = cs(cursor); CPlusPlus::Symbol *canonicalSymbol = cs(cursor);
if (canonicalSymbol) if (canonicalSymbol)
modelManager->renameUsages(canonicalSymbol, cs.context(), replacement, callback); CppModelManager::renameUsages(canonicalSymbol, cs.context(), replacement, callback);
} }
} }
void BuiltinModelManagerSupport::findUsages(const CursorInEditor &data) const void BuiltinModelManagerSupport::findUsages(const CursorInEditor &data) const
{ {
CppModelManager *modelManager = CppModelManager::instance();
if (!modelManager)
return;
CppEditorWidget *editorWidget = data.editorWidget(); CppEditorWidget *editorWidget = data.editorWidget();
QTC_ASSERT(editorWidget, return;); QTC_ASSERT(editorWidget, return;);
SemanticInfo info = editorWidget->semanticInfo(); SemanticInfo info = editorWidget->semanticInfo();
info.snapshot = modelManager->snapshot(); info.snapshot = CppModelManager::snapshot();
info.snapshot.insert(info.doc); info.snapshot.insert(info.doc);
const QTextCursor &cursor = data.cursor(); const QTextCursor &cursor = data.cursor();
if (const CPlusPlus::Macro *macro = findCanonicalMacro(cursor, info.doc)) { if (const CPlusPlus::Macro *macro = findCanonicalMacro(cursor, info.doc)) {
modelManager->findMacroUsages(*macro); CppModelManager::findMacroUsages(*macro);
} else { } else {
Internal::CanonicalSymbol cs(info.doc, info.snapshot); Internal::CanonicalSymbol cs(info.doc, info.snapshot);
CPlusPlus::Symbol *canonicalSymbol = cs(cursor); CPlusPlus::Symbol *canonicalSymbol = cs(cursor);
if (canonicalSymbol) if (canonicalSymbol)
modelManager->findUsages(canonicalSymbol, cs.context()); CppModelManager::findUsages(canonicalSymbol, cs.context());
} }
} }
@@ -199,7 +191,7 @@ void BuiltinModelManagerSupport::switchHeaderSource(const FilePath &filePath,
void BuiltinModelManagerSupport::checkUnused(const Utils::Link &link, SearchResult *search, void BuiltinModelManagerSupport::checkUnused(const Utils::Link &link, SearchResult *search,
const Utils::LinkHandler &callback) const Utils::LinkHandler &callback)
{ {
CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot(); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
QFile file(link.targetFilePath.toString()); QFile file(link.targetFilePath.toString());
if (!file.open(QIODevice::ReadOnly)) if (!file.open(QIODevice::ReadOnly))
return callback(link); return callback(link);

View File

@@ -1642,8 +1642,6 @@ void CppCodeModelInspectorDialog::onWorkingCopyDocumentSelected(const QModelInde
void CppCodeModelInspectorDialog::refresh() void CppCodeModelInspectorDialog::refresh()
{ {
CppModelManager *cmmi = CppModelManager::instance();
const int oldSnapshotIndex = m_snapshotSelector->currentIndex(); const int oldSnapshotIndex = m_snapshotSelector->currentIndex();
const bool selectEditorRelevant const bool selectEditorRelevant
= m_selectEditorRelevantEntriesAfterRefreshCheckBox->isChecked(); = m_selectEditorRelevantEntriesAfterRefreshCheckBox->isChecked();
@@ -1652,7 +1650,7 @@ void CppCodeModelInspectorDialog::refresh()
m_snapshotInfos->clear(); m_snapshotInfos->clear();
m_snapshotSelector->clear(); m_snapshotSelector->clear();
const Snapshot globalSnapshot = cmmi->snapshot(); const Snapshot globalSnapshot = CppModelManager::snapshot();
CppCodeModelInspector::Dumper dumper(globalSnapshot); CppCodeModelInspector::Dumper dumper(globalSnapshot);
m_snapshotModel->setGlobalSnapshot(globalSnapshot); m_snapshotModel->setGlobalSnapshot(globalSnapshot);
@@ -1666,7 +1664,7 @@ void CppCodeModelInspectorDialog::refresh()
CppEditorDocumentHandle *cppEditorDocument = nullptr; CppEditorDocumentHandle *cppEditorDocument = nullptr;
if (editor) { if (editor) {
const FilePath editorFilePath = editor->document()->filePath(); const FilePath editorFilePath = editor->document()->filePath();
cppEditorDocument = cmmi->cppEditorDocument(editorFilePath); cppEditorDocument = CppModelManager::cppEditorDocument(editorFilePath);
if (auto documentProcessor = CppModelManager::cppEditorDocumentProcessor(editorFilePath)) { if (auto documentProcessor = CppModelManager::cppEditorDocumentProcessor(editorFilePath)) {
const Snapshot editorSnapshot = documentProcessor->snapshot(); const Snapshot editorSnapshot = documentProcessor->snapshot();
m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot)); m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot));
@@ -1721,7 +1719,7 @@ void CppCodeModelInspectorDialog::refresh()
? cppEditorDocument->processor()->parser()->projectPartInfo().projectPart ? cppEditorDocument->processor()->parser()->projectPartInfo().projectPart
: ProjectPart::ConstPtr(); : ProjectPart::ConstPtr();
const QList<ProjectInfo::ConstPtr> projectInfos = cmmi->projectInfos(); const QList<ProjectInfo::ConstPtr> projectInfos = CppModelManager::projectInfos();
dumper.dumpProjectInfos(projectInfos); dumper.dumpProjectInfos(projectInfos);
m_projectPartsModel->configure(projectInfos, editorsProjectPart); m_projectPartsModel->configure(projectInfos, editorsProjectPart);
m_projectPartsView->resizeColumns(ProjectPartsModel::ColumnCount); m_projectPartsView->resizeColumns(ProjectPartsModel::ColumnCount);
@@ -1737,7 +1735,7 @@ void CppCodeModelInspectorDialog::refresh()
} }
// Working Copy // Working Copy
const WorkingCopy workingCopy = cmmi->workingCopy(); const WorkingCopy workingCopy = CppModelManager::workingCopy();
dumper.dumpWorkingCopy(workingCopy); dumper.dumpWorkingCopy(workingCopy);
m_workingCopyModel->configure(workingCopy); m_workingCopyModel->configure(workingCopy);
m_workingCopyView->resizeColumns(WorkingCopyModel::ColumnCount); m_workingCopyView->resizeColumns(WorkingCopyModel::ColumnCount);
@@ -1752,8 +1750,8 @@ void CppCodeModelInspectorDialog::refresh()
} }
// Merged entities // Merged entities
dumper.dumpMergedEntities(cmmi->headerPaths(), dumper.dumpMergedEntities(CppModelManager::headerPaths(),
ProjectExplorer::Macro::toByteArray(cmmi->definedMacros())); ProjectExplorer::Macro::toByteArray(CppModelManager::definedMacros()));
} }
enum DocumentTabs { enum DocumentTabs {

View File

@@ -395,7 +395,7 @@ QString Utils::toString(const ProjectExplorer::Abi &abi)
QString Utils::partsForFile(const ::Utils::FilePath &filePath) QString Utils::partsForFile(const ::Utils::FilePath &filePath)
{ {
const QList<ProjectPart::ConstPtr> parts const QList<ProjectPart::ConstPtr> parts
= CppModelManager::instance()->projectPart(filePath); = CppModelManager::projectPart(filePath);
QString result; QString result;
for (const ProjectPart::ConstPtr &part : parts) for (const ProjectPart::ConstPtr &part : parts)
result += part->displayName + QLatin1Char(','); result += part->displayName + QLatin1Char(',');

View File

@@ -417,7 +417,7 @@ std::unique_ptr<AssistInterface> InternalCompletionAssistProvider::createAssistI
BuiltinEditorDocumentParser::get(filePath), BuiltinEditorDocumentParser::get(filePath),
languageFeatures, languageFeatures,
reason, reason,
CppModelManager::instance()->workingCopy()); CppModelManager::workingCopy());
} }
// ----------------- // -----------------
@@ -2076,7 +2076,7 @@ void CppCompletionAssistInterface::getCppSpecifics() const
m_gotCppSpecifics = true; m_gotCppSpecifics = true;
if (m_parser) { if (m_parser) {
m_parser->update({CppModelManager::instance()->workingCopy(), m_parser->update({CppModelManager::workingCopy(),
nullptr, nullptr,
Utils::Language::Cxx, Utils::Language::Cxx,
false}); false});

View File

@@ -41,11 +41,6 @@ using namespace Utils;
namespace CppEditor { namespace CppEditor {
namespace Internal { namespace Internal {
static CppEditor::CppModelManager *mm()
{
return CppEditor::CppModelManager::instance();
}
enum { processDocumentIntervalInMs = 150 }; enum { processDocumentIntervalInMs = 150 };
class CppEditorDocumentHandleImpl : public CppEditorDocumentHandle class CppEditorDocumentHandleImpl : public CppEditorDocumentHandle
@@ -55,12 +50,12 @@ public:
: m_cppEditorDocument(cppEditorDocument) : m_cppEditorDocument(cppEditorDocument)
, m_registrationFilePath(cppEditorDocument->filePath().toString()) , m_registrationFilePath(cppEditorDocument->filePath().toString())
{ {
mm()->registerCppEditorDocument(this); CppModelManager::registerCppEditorDocument(this);
} }
~CppEditorDocumentHandleImpl() override ~CppEditorDocumentHandleImpl() override
{ {
mm()->unregisterCppEditorDocument(m_registrationFilePath); CppModelManager::unregisterCppEditorDocument(m_registrationFilePath);
} }
FilePath filePath() const override { return m_cppEditorDocument->filePath(); } FilePath filePath() const override { return m_cppEditorDocument->filePath(); }
@@ -101,7 +96,7 @@ CppEditorDocument::CppEditorDocument()
connect(this, &IDocument::filePathChanged, connect(this, &IDocument::filePathChanged,
this, &CppEditorDocument::onFilePathChanged); this, &CppEditorDocument::onFilePathChanged);
connect(mm(), &CppModelManager::diagnosticsChanged, connect(CppModelManager::instance(), &CppModelManager::diagnosticsChanged,
this, &CppEditorDocument::onDiagnosticsChanged); this, &CppEditorDocument::onDiagnosticsChanged);
connect(&m_parseContextModel, &ParseContextModel::preferredParseContextChanged, connect(&m_parseContextModel, &ParseContextModel::preferredParseContextChanged,
@@ -187,7 +182,7 @@ void CppEditorDocument::onMimeTypeChanged()
const QString &mt = mimeType(); const QString &mt = mimeType();
m_isObjCEnabled = (mt == QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE) m_isObjCEnabled = (mt == QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE)
|| mt == QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)); || mt == QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
m_completionAssistProvider = mm()->completionAssistProvider(); m_completionAssistProvider = CppModelManager::completionAssistProvider();
initializeTimer(); initializeTimer();
} }
@@ -380,7 +375,7 @@ void CppEditorDocument::updateOutline()
{ {
CPlusPlus::Document::Ptr document; CPlusPlus::Document::Ptr document;
if (!usesClangd()) if (!usesClangd())
document = CppModelManager::instance()->snapshot().document(filePath()); document = CppModelManager::snapshot().document(filePath());
m_overviewModel.update(document); m_overviewModel.update(document);
} }
@@ -392,7 +387,7 @@ QFuture<CursorInfo> CppEditorDocument::cursorInfo(const CursorInfoParams &params
BaseEditorDocumentProcessor *CppEditorDocument::processor() BaseEditorDocumentProcessor *CppEditorDocument::processor()
{ {
if (!m_processor) { if (!m_processor) {
m_processor.reset(mm()->createEditorDocumentProcessor(this)); m_processor.reset(CppModelManager::createEditorDocumentProcessor(this));
connect(m_processor.data(), connect(m_processor.data(),
&BaseEditorDocumentProcessor::projectPartInfoUpdated, &BaseEditorDocumentProcessor::projectPartInfoUpdated,
[this](const ProjectPartInfo &info) { [this](const ProjectPartInfo &info) {
@@ -493,7 +488,7 @@ void CppEditorDocument::onDiagnosticsChanged(const QString &fileName, const QStr
const Utils::Id category = Utils::Id::fromString(kind); const Utils::Id category = Utils::Id::fromString(kind);
for (const auto &diagnostic : mm()->diagnosticMessages()) { for (const auto &diagnostic : CppModelManager::diagnosticMessages()) {
if (diagnostic.filePath() == filePath()) { if (diagnostic.filePath() == filePath()) {
auto it = std::find_if(std::begin(removedMarks), auto it = std::find_if(std::begin(removedMarks),
std::end(removedMarks), std::end(removedMarks),

View File

@@ -125,7 +125,7 @@ QWidget *CppEditorOutline::widget() const
QSharedPointer<CPlusPlus::Document> getDocument(const Utils::FilePath &filePath) QSharedPointer<CPlusPlus::Document> getDocument(const Utils::FilePath &filePath)
{ {
const CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
return snapshot.document(filePath); return snapshot.document(filePath);
} }

View File

@@ -231,7 +231,7 @@ void CppEditorPlugin::initialize()
d = new CppEditorPluginPrivate; d = new CppEditorPluginPrivate;
d->initialize(); d->initialize();
CppModelManager::instance()->registerJsExtension(); CppModelManager::registerJsExtension();
ExtensionSystem::PluginManager::addObject(&d->m_cppProjectUpdaterFactory); ExtensionSystem::PluginManager::addObject(&d->m_cppProjectUpdaterFactory);
// Menus // Menus
@@ -446,9 +446,8 @@ void CppEditorPlugin::initialize()
cppToolsMenu->addSeparator(Core::Constants::G_DEFAULT_THREE); cppToolsMenu->addSeparator(Core::Constants::G_DEFAULT_THREE);
d->m_reparseExternallyChangedFiles = new QAction(Tr::tr("Reparse Externally Changed Files"), this); d->m_reparseExternallyChangedFiles = new QAction(Tr::tr("Reparse Externally Changed Files"), this);
cmd = ActionManager::registerAction(d->m_reparseExternallyChangedFiles, Constants::UPDATE_CODEMODEL); cmd = ActionManager::registerAction(d->m_reparseExternallyChangedFiles, Constants::UPDATE_CODEMODEL);
CppModelManager *cppModelManager = CppModelManager::instance();
connect(d->m_reparseExternallyChangedFiles, &QAction::triggered, connect(d->m_reparseExternallyChangedFiles, &QAction::triggered,
cppModelManager, &CppModelManager::updateModifiedSourceFiles); CppModelManager::instance(), &CppModelManager::updateModifiedSourceFiles);
cppToolsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE); cppToolsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
ActionContainer *toolsDebug = ActionManager::actionContainer(Core::Constants::M_TOOLS_DEBUG); ActionContainer *toolsDebug = ActionManager::actionContainer(Core::Constants::M_TOOLS_DEBUG);
@@ -515,7 +514,7 @@ void CppEditorPlugin::extensionsInitialized()
}); });
ProjectPanelFactory::registerFactory(fileNamesPanelFactory); ProjectPanelFactory::registerFactory(fileNamesPanelFactory);
if (CppModelManager::instance()->isClangCodeModelActive()) { if (CppModelManager::isClangCodeModelActive()) {
d->m_clangdSettingsPage = new ClangdSettingsPage; d->m_clangdSettingsPage = new ClangdSettingsPage;
const auto clangdPanelFactory = new ProjectPanelFactory; const auto clangdPanelFactory = new ProjectPanelFactory;
clangdPanelFactory->setPriority(100); clangdPanelFactory->setPriority(100);
@@ -528,7 +527,7 @@ void CppEditorPlugin::extensionsInitialized()
// Add the hover handler factories here instead of in initialize() // Add the hover handler factories here instead of in initialize()
// so that the Clang Code Model has a chance to hook in. // so that the Clang Code Model has a chance to hook in.
d->m_cppEditorFactory.addHoverHandler(CppModelManager::instance()->createHoverHandler()); d->m_cppEditorFactory.addHoverHandler(CppModelManager::createHoverHandler());
d->m_cppEditorFactory.addHoverHandler(new ColorPreviewHoverHandler); d->m_cppEditorFactory.addHoverHandler(new ColorPreviewHoverHandler);
d->m_cppEditorFactory.addHoverHandler(new ResourcePreviewHoverHandler); d->m_cppEditorFactory.addHoverHandler(new ResourcePreviewHoverHandler);
@@ -876,8 +875,7 @@ FilePath correspondingHeaderOrSource(const FilePath &filePath, bool *wasHeader,
// Find files in other projects // Find files in other projects
} else { } else {
CppModelManager *modelManager = CppModelManager::instance(); const QList<ProjectInfo::ConstPtr> projectInfos = CppModelManager::projectInfos();
const QList<ProjectInfo::ConstPtr> projectInfos = modelManager->projectInfos();
for (const ProjectInfo::ConstPtr &projectInfo : projectInfos) { for (const ProjectInfo::ConstPtr &projectInfo : projectInfos) {
const Project *project = projectForProjectInfo(*projectInfo); const Project *project = projectForProjectInfo(*projectInfo);
if (project == currentProject) if (project == currentProject)

View File

@@ -383,8 +383,6 @@ public:
bool shouldOfferOutline() const { return !CppModelManager::usesClangd(m_cppEditorDocument); } bool shouldOfferOutline() const { return !CppModelManager::usesClangd(m_cppEditorDocument); }
public: public:
QPointer<CppModelManager> m_modelManager;
CppEditorDocument *m_cppEditorDocument; CppEditorDocument *m_cppEditorDocument;
CppEditorOutline *m_cppEditorOutline = nullptr; CppEditorOutline *m_cppEditorOutline = nullptr;
@@ -405,8 +403,7 @@ public:
}; };
CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q) CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q)
: m_modelManager(CppModelManager::instance()) : m_cppEditorDocument(qobject_cast<CppEditorDocument *>(q->textDocument()))
, m_cppEditorDocument(qobject_cast<CppEditorDocument *>(q->textDocument()))
, m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q)) , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
, m_localRenaming(q) , m_localRenaming(q)
, m_useSelectionsUpdater(q) , m_useSelectionsUpdater(q)
@@ -611,7 +608,7 @@ void CppEditorWidget::findUsages(QTextCursor cursor)
// 'this' in cursorInEditor is never used (and must never be used) asynchronously. // 'this' in cursorInEditor is never used (and must never be used) asynchronously.
const CursorInEditor cursorInEditor{cursor, textDocument()->filePath(), this, textDocument()}; const CursorInEditor cursorInEditor{cursor, textDocument()->filePath(), this, textDocument()};
QPointer<CppEditorWidget> cppEditorWidget = this; QPointer<CppEditorWidget> cppEditorWidget = this;
d->m_modelManager->findUsages(cursorInEditor); CppModelManager::findUsages(cursorInEditor);
} }
void CppEditorWidget::renameUsages(const QString &replacement, QTextCursor cursor) void CppEditorWidget::renameUsages(const QString &replacement, QTextCursor cursor)
@@ -626,7 +623,7 @@ void CppEditorWidget::renameUsages(const QString &replacement, QTextCursor curso
showRenameWarningIfFileIsGenerated(link.targetFilePath); showRenameWarningIfFileIsGenerated(link.targetFilePath);
CursorInEditor cursorInEditor{cursor, textDocument()->filePath(), this, textDocument()}; CursorInEditor cursorInEditor{cursor, textDocument()->filePath(), this, textDocument()};
QPointer<CppEditorWidget> cppEditorWidget = this; QPointer<CppEditorWidget> cppEditorWidget = this;
d->m_modelManager->globalRename(cursorInEditor, replacement); CppModelManager::globalRename(cursorInEditor, replacement);
}; };
CppModelManager::followSymbol( CppModelManager::followSymbol(
CursorInEditor{cursor, textDocument()->filePath(), this, textDocument()}, CursorInEditor{cursor, textDocument()->filePath(), this, textDocument()},
@@ -640,7 +637,7 @@ void CppEditorWidget::renameUsages(const Utils::FilePath &filePath, const QStrin
cursor = textCursor(); cursor = textCursor();
CursorInEditor cursorInEditor{cursor, filePath, this, textDocument()}; CursorInEditor cursorInEditor{cursor, filePath, this, textDocument()};
QPointer<CppEditorWidget> cppEditorWidget = this; QPointer<CppEditorWidget> cppEditorWidget = this;
d->m_modelManager->globalRename(cursorInEditor, replacement, callback); CppModelManager::globalRename(cursorInEditor, replacement, callback);
} }
bool CppEditorWidget::selectBlockUp() bool CppEditorWidget::selectBlockUp()
@@ -695,15 +692,14 @@ bool CppEditorWidget::isWidgetHighlighted(QWidget *widget)
namespace { namespace {
QList<ProjectPart::ConstPtr> fetchProjectParts(CppModelManager *modelManager, QList<ProjectPart::ConstPtr> fetchProjectParts(const Utils::FilePath &filePath)
const Utils::FilePath &filePath)
{ {
QList<ProjectPart::ConstPtr> projectParts = modelManager->projectPart(filePath); QList<ProjectPart::ConstPtr> projectParts = CppModelManager::projectPart(filePath);
if (projectParts.isEmpty()) if (projectParts.isEmpty())
projectParts = modelManager->projectPartFromDependencies(filePath); projectParts = CppModelManager::projectPartFromDependencies(filePath);
if (projectParts.isEmpty()) if (projectParts.isEmpty())
projectParts.append(modelManager->fallbackProjectPart()); projectParts.append(CppModelManager::fallbackProjectPart());
return projectParts; return projectParts;
} }
@@ -728,10 +724,10 @@ const ProjectPart *findProjectPartForCurrentProject(
const ProjectPart *CppEditorWidget::projectPart() const const ProjectPart *CppEditorWidget::projectPart() const
{ {
if (!d->m_modelManager) if (!CppModelManager::instance())
return nullptr; return nullptr;
auto projectParts = fetchProjectParts(d->m_modelManager, textDocument()->filePath()); auto projectParts = fetchProjectParts(textDocument()->filePath());
return findProjectPartForCurrentProject(projectParts, return findProjectPartForCurrentProject(projectParts,
ProjectExplorer::ProjectTree::currentProject()); ProjectExplorer::ProjectTree::currentProject());
@@ -868,11 +864,11 @@ void CppEditorWidget::renameSymbolUnderCursor()
}; };
viewport()->setCursor(Qt::BusyCursor); viewport()->setCursor(Qt::BusyCursor);
d->m_modelManager->startLocalRenaming(CursorInEditor{textCursor(), CppModelManager::startLocalRenaming(CursorInEditor{textCursor(),
textDocument()->filePath(), textDocument()->filePath(),
this, textDocument()}, this, textDocument()},
projPart, projPart,
std::move(renameSymbols)); std::move(renameSymbols));
} }
void CppEditorWidget::updatePreprocessorButtonTooltip() void CppEditorWidget::updatePreprocessorButtonTooltip()
@@ -887,7 +883,7 @@ void CppEditorWidget::updatePreprocessorButtonTooltip()
void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit) void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
{ {
if (!d->m_modelManager) if (!CppModelManager::instance())
return; return;
const CursorInEditor cursor(textCursor(), textDocument()->filePath(), this, textDocument()); const CursorInEditor cursor(textCursor(), textDocument()->filePath(), this, textDocument());
@@ -901,7 +897,7 @@ void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
void CppEditorWidget::followSymbolToType(bool inNextSplit) void CppEditorWidget::followSymbolToType(bool inNextSplit)
{ {
if (!d->m_modelManager) if (!CppModelManager::instance())
return; return;
const CursorInEditor cursor(textCursor(), textDocument()->filePath(), this, textDocument()); const CursorInEditor cursor(textCursor(), textDocument()->filePath(), this, textDocument());
@@ -968,7 +964,7 @@ void CppEditorWidget::findLinkAt(const QTextCursor &cursor,
bool resolveTarget, bool resolveTarget,
bool inNextSplit) bool inNextSplit)
{ {
if (!d->m_modelManager) if (!CppModelManager::instance())
return processLinkCallback(Utils::Link()); return processLinkCallback(Utils::Link());
if (followUrl(cursor, processLinkCallback)) if (followUrl(cursor, processLinkCallback))
@@ -1269,8 +1265,7 @@ std::unique_ptr<AssistInterface> CppEditorWidget::createAssistInterface(AssistKi
return cap->createAssistInterface(textDocument()->filePath(), this, getFeatures(), reason); return cap->createAssistInterface(textDocument()->filePath(), this, getFeatures(), reason);
if (isOldStyleSignalOrSlot()) { if (isOldStyleSignalOrSlot()) {
return CppModelManager::instance() return CppModelManager::completionAssistProvider()
->completionAssistProvider()
->createAssistInterface(textDocument()->filePath(), this, getFeatures(), reason); ->createAssistInterface(textDocument()->filePath(), this, getFeatures(), reason);
} }
} }
@@ -1331,7 +1326,7 @@ void CppEditorWidget::updateFunctionDeclDefLinkNow()
if (!isSemanticInfoValidExceptLocalUses()) if (!isSemanticInfoValidExceptLocalUses())
return; return;
Snapshot snapshot = d->m_modelManager->snapshot(); Snapshot snapshot = CppModelManager::snapshot();
snapshot.insert(semanticDoc); snapshot.insert(semanticDoc);
d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot); d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot);

View File

@@ -475,7 +475,7 @@ static QFuture<QSharedPointer<CppElement>> exec(SourceFunction &&sourceFunction,
ExecFunction &&execFunction, ExecFunction &&execFunction,
bool followTypedef = true) bool followTypedef = true)
{ {
const Snapshot &snapshot = CppModelManager::instance()->snapshot(); const Snapshot &snapshot = CppModelManager::snapshot();
Document::Ptr doc; Document::Ptr doc;
QString expression; QString expression;
@@ -497,7 +497,7 @@ static QFuture<QSharedPointer<CppElement>> asyncExec(
const CPlusPlus::LookupContext &lookupContext) const CPlusPlus::LookupContext &lookupContext)
{ {
return Utils::asyncRun(&createTypeHierarchy, snapshot, lookupItem, lookupContext, return Utils::asyncRun(&createTypeHierarchy, snapshot, lookupItem, lookupContext,
*CppModelManager::instance()->symbolFinder()); *CppModelManager::symbolFinder());
} }
class FromExpressionFunctor class FromExpressionFunctor
@@ -589,7 +589,7 @@ QFuture<QSharedPointer<CppElement>> FromGuiFunctor::syncExec(
QFutureInterface<QSharedPointer<CppElement>> futureInterface; QFutureInterface<QSharedPointer<CppElement>> futureInterface;
futureInterface.reportStarted(); futureInterface.reportStarted();
m_element = handleLookupItemMatch(snapshot, lookupItem, lookupContext, m_element = handleLookupItemMatch(snapshot, lookupItem, lookupContext,
*CppModelManager::instance()->symbolFinder()); *CppModelManager::symbolFinder());
futureInterface.reportResult(m_element); futureInterface.reportResult(m_element);
futureInterface.reportFinished(); futureInterface.reportFinished();
return futureInterface.future(); return futureInterface.future();
@@ -694,7 +694,7 @@ const QString &CppElementEvaluator::diagnosis() const
Utils::Link CppElementEvaluator::linkFromExpression(const QString &expression, const FilePath &filePath) Utils::Link CppElementEvaluator::linkFromExpression(const QString &expression, const FilePath &filePath)
{ {
const Snapshot &snapshot = CppModelManager::instance()->snapshot(); const Snapshot &snapshot = CppModelManager::snapshot();
Document::Ptr doc = snapshot.document(filePath); Document::Ptr doc = snapshot.document(filePath);
if (doc.isNull()) if (doc.isNull())
return Utils::Link(); return Utils::Link();

View File

@@ -437,9 +437,9 @@ void CppFindReferences::findAll_helper(SearchResult *search, CPlusPlus::Symbol *
if (search->isInteractive()) if (search->isInteractive())
SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus); SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
const WorkingCopy workingCopy = m_modelManager->workingCopy(); const WorkingCopy workingCopy = CppModelManager::workingCopy();
QFuture<CPlusPlus::Usage> result; QFuture<CPlusPlus::Usage> result;
result = Utils::asyncRun(m_modelManager->sharedThreadPool(), find_helper, result = Utils::asyncRun(CppModelManager::sharedThreadPool(), find_helper,
workingCopy, context, symbol, categorize); workingCopy, context, symbol, categorize);
createWatcher(result, search); createWatcher(result, search);
@@ -484,7 +484,7 @@ void CppFindReferences::searchAgain(SearchResult *search)
{ {
CppFindReferencesParameters parameters = search->userData().value<CppFindReferencesParameters>(); CppFindReferencesParameters parameters = search->userData().value<CppFindReferencesParameters>();
parameters.filesToRename.clear(); parameters.filesToRename.clear();
CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot(); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
search->restart(); search->restart();
CPlusPlus::LookupContext context; CPlusPlus::LookupContext context;
CPlusPlus::Symbol *symbol = findSymbol(parameters, snapshot, &context); CPlusPlus::Symbol *symbol = findSymbol(parameters, snapshot, &context);
@@ -544,7 +544,7 @@ CPlusPlus::Symbol *CppFindReferences::findSymbol(const CppFindReferencesParamete
CPlusPlus::Document::Ptr newSymbolDocument = snapshot.document(parameters.symbolFilePath); CPlusPlus::Document::Ptr newSymbolDocument = snapshot.document(parameters.symbolFilePath);
// document is not parsed and has no bindings yet, do it // document is not parsed and has no bindings yet, do it
QByteArray source = getSource(newSymbolDocument->filePath(), m_modelManager->workingCopy()); QByteArray source = getSource(newSymbolDocument->filePath(), CppModelManager::workingCopy());
CPlusPlus::Document::Ptr doc = CPlusPlus::Document::Ptr doc =
snapshot.preprocessedDocument(source, newSymbolDocument->filePath()); snapshot.preprocessedDocument(source, newSymbolDocument->filePath());
doc->check(); doc->check();
@@ -747,8 +747,8 @@ void CppFindReferences::findMacroUses(const CPlusPlus::Macro &macro, const QStri
Core::EditorManager::openEditorAtSearchResult(item); Core::EditorManager::openEditorAtSearchResult(item);
}); });
const CPlusPlus::Snapshot snapshot = m_modelManager->snapshot(); const CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
const WorkingCopy workingCopy = m_modelManager->workingCopy(); const WorkingCopy workingCopy = CppModelManager::workingCopy();
// add the macro definition itself // add the macro definition itself
{ {
@@ -768,7 +768,7 @@ void CppFindReferences::findMacroUses(const CPlusPlus::Macro &macro, const QStri
} }
QFuture<CPlusPlus::Usage> result; QFuture<CPlusPlus::Usage> result;
result = Utils::asyncRun(m_modelManager->sharedThreadPool(), findMacroUses_helper, result = Utils::asyncRun(CppModelManager::sharedThreadPool(), findMacroUses_helper,
workingCopy, snapshot, macro); workingCopy, snapshot, macro);
createWatcher(result, search); createWatcher(result, search);
@@ -829,8 +829,8 @@ void CppFindReferences::checkUnused(Core::SearchResult *search, const Link &link
}); });
connect(search, &SearchResult::canceled, watcher, [watcher] { watcher->cancel(); }); connect(search, &SearchResult::canceled, watcher, [watcher] { watcher->cancel(); });
connect(search, &SearchResult::destroyed, watcher, [watcher] { watcher->cancel(); }); connect(search, &SearchResult::destroyed, watcher, [watcher] { watcher->cancel(); });
watcher->setFuture(Utils::asyncRun(m_modelManager->sharedThreadPool(), find_helper, watcher->setFuture(Utils::asyncRun(CppModelManager::sharedThreadPool(), find_helper,
m_modelManager->workingCopy(), context, symbol, true)); CppModelManager::workingCopy(), context, symbol, true));
} }
void CppFindReferences::createWatcher(const QFuture<CPlusPlus::Usage> &future, SearchResult *search) void CppFindReferences::createWatcher(const QFuture<CPlusPlus::Usage> &future, SearchResult *search)

View File

@@ -209,7 +209,7 @@ Link findMacroLink(const QByteArray &name, const Document::Ptr &doc)
{ {
if (!name.isEmpty()) { if (!name.isEmpty()) {
if (doc) { if (doc) {
const Snapshot snapshot = CppModelManager::instance()->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
QSet<QString> processed; QSet<QString> processed;
return findMacroLink_helper(name, doc, snapshot, &processed); return findMacroLink_helper(name, doc, snapshot, &processed);
} }

View File

@@ -54,7 +54,7 @@ enum {
static Snapshot globalSnapshot() static Snapshot globalSnapshot()
{ {
return CppModelManager::instance()->snapshot(); return CppModelManager::snapshot();
} }
struct FileAndLine struct FileAndLine

View File

@@ -90,7 +90,7 @@ CppIncludesFilter::CppIncludesFilter()
if (entry) if (entry)
inputFilePaths.insert(entry->filePath()); inputFilePaths.insert(entry->filePath());
} }
const CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
return [snapshot, inputFilePaths](const QFuture<void> &future) { return [snapshot, inputFilePaths](const QFuture<void> &future) {
// This body runs in non-main thread // This body runs in non-main thread
return generateFilePaths(future, snapshot, inputFilePaths); return generateFilePaths(future, snapshot, inputFilePaths);

View File

@@ -31,7 +31,7 @@ static Q_LOGGING_CATEGORY(indexerLog, "qtc.cppeditor.indexer", QtWarningMsg)
SymbolSearcher::SymbolSearcher(const SymbolSearcher::Parameters &parameters, SymbolSearcher::SymbolSearcher(const SymbolSearcher::Parameters &parameters,
const QSet<QString> &fileNames) const QSet<QString> &fileNames)
: m_snapshot(CppModelManager::instance()->snapshot()) : m_snapshot(CppModelManager::snapshot())
, m_parameters(parameters) , m_parameters(parameters)
, m_fileNames(fileNames) , m_fileNames(fileNames)
{} {}
@@ -138,8 +138,7 @@ void indexFindErrors(QPromise<void> &promise, const ParseParams params)
// Parse the file as precisely as possible // Parse the file as precisely as possible
BuiltinEditorDocumentParser parser(FilePath::fromString(file)); BuiltinEditorDocumentParser parser(FilePath::fromString(file));
parser.setReleaseSourceAndAST(false); parser.setReleaseSourceAndAST(false);
parser.update({CppModelManager::instance()->workingCopy(), nullptr, parser.update({CppModelManager::workingCopy(), nullptr, Language::Cxx, false});
Language::Cxx, false});
CPlusPlus::Document::Ptr document = parser.document(); CPlusPlus::Document::Ptr document = parser.document();
QTC_ASSERT(document, return); QTC_ASSERT(document, return);
@@ -181,8 +180,7 @@ void index(QPromise<void> &promise, const ParseParams params)
const FilePath &conf = CppModelManager::configurationFileName(); const FilePath &conf = CppModelManager::configurationFileName();
bool processingHeaders = false; bool processingHeaders = false;
CppModelManager *cmm = CppModelManager::instance(); const ProjectExplorer::HeaderPaths fallbackHeaderPaths = CppModelManager::headerPaths();
const ProjectExplorer::HeaderPaths fallbackHeaderPaths = cmm->headerPaths();
const CPlusPlus::LanguageFeatures defaultFeatures = const CPlusPlus::LanguageFeatures defaultFeatures =
CPlusPlus::LanguageFeatures::defaultFeatures(); CPlusPlus::LanguageFeatures::defaultFeatures();
@@ -192,7 +190,7 @@ void index(QPromise<void> &promise, const ParseParams params)
break; break;
const QString fileName = files.at(i); const QString fileName = files.at(i);
const QList<ProjectPart::ConstPtr> parts = cmm->projectPart(fileName); const QList<ProjectPart::ConstPtr> parts = CppModelManager::projectPart(fileName);
const CPlusPlus::LanguageFeatures languageFeatures = parts.isEmpty() const CPlusPlus::LanguageFeatures languageFeatures = parts.isEmpty()
? defaultFeatures ? defaultFeatures
: parts.first()->languageFeatures; : parts.first()->languageFeatures;
@@ -236,7 +234,7 @@ void parse(QPromise<void> &promise, const ParseParams params)
index(promise, params); index(promise, params);
promise.setProgressValue(files.size()); promise.setProgressValue(files.size());
CppModelManager::instance()->finishedRefreshingSourceFiles(files); CppModelManager::finishedRefreshingSourceFiles(files);
} }
} // anonymous namespace } // anonymous namespace
@@ -306,15 +304,13 @@ bool CppIndexingSupport::isFindErrorsIndexingActive()
QFuture<void> CppIndexingSupport::refreshSourceFiles(const QSet<QString> &sourceFiles, QFuture<void> CppIndexingSupport::refreshSourceFiles(const QSet<QString> &sourceFiles,
CppModelManager::ProgressNotificationMode mode) CppModelManager::ProgressNotificationMode mode)
{ {
CppModelManager *mgr = CppModelManager::instance();
ParseParams params; ParseParams params;
params.indexerFileSizeLimitInMb = indexerFileSizeLimitInMb(); params.indexerFileSizeLimitInMb = indexerFileSizeLimitInMb();
params.headerPaths = mgr->headerPaths(); params.headerPaths = CppModelManager::headerPaths();
params.workingCopy = mgr->workingCopy(); params.workingCopy = CppModelManager::workingCopy();
params.sourceFiles = sourceFiles; params.sourceFiles = sourceFiles;
QFuture<void> result = Utils::asyncRun(mgr->sharedThreadPool(), parse, params); QFuture<void> result = Utils::asyncRun(CppModelManager::sharedThreadPool(), parse, params);
m_synchronizer.addFuture(result); m_synchronizer.addFuture(result);
if (mode == CppModelManager::ForcedProgressNotification || sourceFiles.count() > 1) { if (mode == CppModelManager::ForcedProgressNotification || sourceFiles.count() > 1) {

View File

@@ -41,7 +41,7 @@ void matchesFor(QPromise<void> &promise, const LocatorStorage &storage,
const bool hasColonColon = input.contains("::"); const bool hasColonColon = input.contains("::");
const QRegularExpression shortRegexp = hasColonColon const QRegularExpression shortRegexp = hasColonColon
? ILocatorFilter::createRegExp(input.mid(input.lastIndexOf("::") + 2)) : regexp; ? ILocatorFilter::createRegExp(input.mid(input.lastIndexOf("::") + 2)) : regexp;
CppLocatorData *locatorData = CppModelManager::instance()->locatorData(); CppLocatorData *locatorData = CppModelManager::locatorData();
locatorData->filterAllFiles([&](const IndexItem::Ptr &info) { locatorData->filterAllFiles([&](const IndexItem::Ptr &info) {
if (promise.isCanceled()) if (promise.isCanceled())
return IndexItem::Break; return IndexItem::Break;
@@ -174,7 +174,7 @@ QList<IndexItem::Ptr> itemsOfCurrentDocument(const FilePath &currentFileName)
return {}; return {};
QList<IndexItem::Ptr> results; QList<IndexItem::Ptr> results;
const Snapshot snapshot = CppModelManager::instance()->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
if (const Document::Ptr thisDocument = snapshot.document(currentFileName)) { if (const Document::Ptr thisDocument = snapshot.document(currentFileName)) {
SearchSymbols search; SearchSymbols search;
search.setSymbolsToSearchFor(SymbolSearcher::Declarations | search.setSymbolsToSearchFor(SymbolSearcher::Declarations |

View File

@@ -215,6 +215,8 @@ public:
QList<Document::DiagnosticMessage> m_diagnosticMessages; QList<Document::DiagnosticMessage> m_diagnosticMessages;
}; };
static CppModelManagerPrivate *d;
} // namespace Internal } // namespace Internal
using namespace Internal; using namespace Internal;
@@ -296,14 +298,13 @@ QSet<FilePath> CppModelManager::timeStampModifiedFiles(const QList<Document::Ptr
*/ */
CppSourceProcessor *CppModelManager::createSourceProcessor() CppSourceProcessor *CppModelManager::createSourceProcessor()
{ {
CppModelManager *that = instance(); return new CppSourceProcessor(snapshot(), [](const Document::Ptr &doc) {
return new CppSourceProcessor(that->snapshot(), [that](const Document::Ptr &doc) { const Document::Ptr previousDocument = document(doc->filePath());
const Document::Ptr previousDocument = that->document(doc->filePath());
const unsigned newRevision = previousDocument.isNull() const unsigned newRevision = previousDocument.isNull()
? 1U ? 1U
: previousDocument->revision() + 1; : previousDocument->revision() + 1;
doc->setRevision(newRevision); doc->setRevision(newRevision);
that->emitDocumentUpdated(doc); emitDocumentUpdated(doc);
doc->releaseSourceAndAST(); doc->releaseSourceAndAST();
}); });
} }
@@ -314,7 +315,7 @@ const FilePath &CppModelManager::editorConfigurationFileName()
return config; return config;
} }
ModelManagerSupport *CppModelManager::modelManagerSupport(Backend backend) const ModelManagerSupport *CppModelManager::modelManagerSupport(Backend backend)
{ {
return backend == Backend::Builtin return backend == Backend::Builtin
? &d->m_builtinModelManagerSupport : d->m_activeModelManagerSupport; ? &d->m_builtinModelManagerSupport : d->m_activeModelManagerSupport;
@@ -325,27 +326,26 @@ void CppModelManager::startLocalRenaming(const CursorInEditor &data,
RenameCallback &&renameSymbolsCallback, RenameCallback &&renameSymbolsCallback,
Backend backend) Backend backend)
{ {
instance()->modelManagerSupport(backend) modelManagerSupport(backend)
->startLocalRenaming(data, projectPart, std::move(renameSymbolsCallback)); ->startLocalRenaming(data, projectPart, std::move(renameSymbolsCallback));
} }
void CppModelManager::globalRename(const CursorInEditor &data, const QString &replacement, void CppModelManager::globalRename(const CursorInEditor &data, const QString &replacement,
const std::function<void()> &callback, Backend backend) const std::function<void()> &callback, Backend backend)
{ {
instance()->modelManagerSupport(backend)->globalRename(data, replacement, callback); modelManagerSupport(backend)->globalRename(data, replacement, callback);
} }
void CppModelManager::findUsages(const CursorInEditor &data, Backend backend) void CppModelManager::findUsages(const CursorInEditor &data, Backend backend)
{ {
instance()->modelManagerSupport(backend)->findUsages(data); modelManagerSupport(backend)->findUsages(data);
} }
void CppModelManager::switchHeaderSource(bool inNextSplit, Backend backend) void CppModelManager::switchHeaderSource(bool inNextSplit, Backend backend)
{ {
const IDocument *currentDocument = EditorManager::currentDocument(); const IDocument *currentDocument = EditorManager::currentDocument();
QTC_ASSERT(currentDocument, return); QTC_ASSERT(currentDocument, return);
instance()->modelManagerSupport(backend)->switchHeaderSource(currentDocument->filePath(), modelManagerSupport(backend)->switchHeaderSource(currentDocument->filePath(), inNextSplit);
inNextSplit);
} }
void CppModelManager::showPreprocessedFile(bool inNextSplit) void CppModelManager::showPreprocessedFile(bool inNextSplit)
@@ -383,7 +383,7 @@ void CppModelManager::showPreprocessedFile(bool inNextSplit)
TemporaryDirectory::masterTemporaryDirectory()->filePath(outFileName)); TemporaryDirectory::masterTemporaryDirectory()->filePath(outFileName));
const auto useBuiltinPreprocessor = [filePath, outFilePath, inNextSplit, const auto useBuiltinPreprocessor = [filePath, outFilePath, inNextSplit,
contents = doc->contents()] { contents = doc->contents()] {
const Document::Ptr preprocessedDoc = instance()->snapshot() const Document::Ptr preprocessedDoc = snapshot()
.preprocessedDocument(contents, filePath); .preprocessedDocument(contents, filePath);
QByteArray content = R"(/* Created using Qt Creator's built-in preprocessor. */ QByteArray content = R"(/* Created using Qt Creator's built-in preprocessor. */
/* See Tools -> Debug Qt Creator -> Inspect C++ Code Model for the parameters used. /* See Tools -> Debug Qt Creator -> Inspect C++ Code Model for the parameters used.
@@ -430,7 +430,7 @@ void CppModelManager::showPreprocessedFile(bool inNextSplit)
} }
const ProjectPart::ConstPtr projectPart = Utils::findOrDefault( const ProjectPart::ConstPtr projectPart = Utils::findOrDefault(
instance()->projectPart(filePath), [](const ProjectPart::ConstPtr &pp) { CppModelManager::projectPart(filePath), [](const ProjectPart::ConstPtr &pp) {
return pp->belongsToProject(ProjectTree::currentProject()); return pp->belongsToProject(ProjectTree::currentProject());
}); });
if (!projectPart) { if (!projectPart) {
@@ -513,7 +513,7 @@ static void checkNextFunctionForUnused(
remainingLinks = remainingLinksList; remainingLinks = remainingLinksList;
activeLinks = activeLinksList; activeLinks = activeLinksList;
search->setUserData(data); search->setUserData(data);
CppModelManager::instance()->modelManagerSupport(CppModelManager::Backend::Best) CppModelManager::modelManagerSupport(CppModelManager::Backend::Best)
->checkUnused(link, search, [search, link, findRefsFuture, actionsSwitcher](const Link &) { ->checkUnused(link, search, [search, link, findRefsFuture, actionsSwitcher](const Link &) {
if (!search || findRefsFuture->isCanceled()) if (!search || findRefsFuture->isCanceled())
return; return;
@@ -620,7 +620,7 @@ void CppModelManager::checkForUnusedSymbol(SearchResult *search,
const CPlusPlus::LookupContext &context, const CPlusPlus::LookupContext &context,
const LinkHandler &callback) const LinkHandler &callback)
{ {
instance()->d->m_findReferences->checkUnused(search, link, symbol, context, callback); d->m_findReferences->checkUnused(search, link, symbol, context, callback);
} }
int argumentPositionOf(const AST *last, const CallAST *callAst) int argumentPositionOf(const AST *last, const CallAST *callAst)
@@ -642,7 +642,7 @@ int argumentPositionOf(const AST *last, const CallAST *callAst)
SignalSlotType CppModelManager::getSignalSlotType(const FilePath &filePath, SignalSlotType CppModelManager::getSignalSlotType(const FilePath &filePath,
const QByteArray &content, const QByteArray &content,
int position) const int position)
{ {
if (content.isEmpty()) if (content.isEmpty())
return SignalSlotType::None; return SignalSlotType::None;
@@ -653,7 +653,7 @@ SignalSlotType CppModelManager::getSignalSlotType(const FilePath &filePath,
if (position > 2 && content.mid(position - 2, 2) == "::") if (position > 2 && content.mid(position - 2, 2) == "::")
fixedContent.insert(position, 'x'); fixedContent.insert(position, 'x');
const Snapshot snapshot = this->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
const Document::Ptr document = snapshot.preprocessedDocument(fixedContent, filePath); const Document::Ptr document = snapshot.preprocessedDocument(fixedContent, filePath);
document->check(); document->check();
QTextDocument textDocument(QString::fromUtf8(fixedContent)); QTextDocument textDocument(QString::fromUtf8(fixedContent));
@@ -763,7 +763,7 @@ SignalSlotType CppModelManager::getSignalSlotType(const FilePath &filePath,
FollowSymbolUnderCursor &CppModelManager::builtinFollowSymbol() FollowSymbolUnderCursor &CppModelManager::builtinFollowSymbol()
{ {
return instance()->d->m_builtinModelManagerSupport.followSymbolInterface(); return d->m_builtinModelManagerSupport.followSymbolInterface();
} }
template<class FilterClass> template<class FilterClass>
@@ -804,32 +804,32 @@ void CppModelManager::setCurrentDocumentFilter(std::unique_ptr<ILocatorFilter> &
setFilter(d->m_currentDocumentFilter, std::move(filter)); setFilter(d->m_currentDocumentFilter, std::move(filter));
} }
ILocatorFilter *CppModelManager::locatorFilter() const ILocatorFilter *CppModelManager::locatorFilter()
{ {
return d->m_locatorFilter.get(); return d->m_locatorFilter.get();
} }
ILocatorFilter *CppModelManager::classesFilter() const ILocatorFilter *CppModelManager::classesFilter()
{ {
return d->m_classesFilter.get(); return d->m_classesFilter.get();
} }
ILocatorFilter *CppModelManager::includesFilter() const ILocatorFilter *CppModelManager::includesFilter()
{ {
return d->m_includesFilter.get(); return d->m_includesFilter.get();
} }
ILocatorFilter *CppModelManager::functionsFilter() const ILocatorFilter *CppModelManager::functionsFilter()
{ {
return d->m_functionsFilter.get(); return d->m_functionsFilter.get();
} }
IFindFilter *CppModelManager::symbolsFindFilter() const IFindFilter *CppModelManager::symbolsFindFilter()
{ {
return d->m_symbolsFindFilter.get(); return d->m_symbolsFindFilter.get();
} }
ILocatorFilter *CppModelManager::currentDocumentFilter() const ILocatorFilter *CppModelManager::currentDocumentFilter()
{ {
return d->m_currentDocumentFilter.get(); return d->m_currentDocumentFilter.get();
} }
@@ -841,7 +841,7 @@ const FilePath &CppModelManager::configurationFileName()
void CppModelManager::updateModifiedSourceFiles() void CppModelManager::updateModifiedSourceFiles()
{ {
const Snapshot snapshot = this->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
QList<Document::Ptr> documentsToCheck; QList<Document::Ptr> documentsToCheck;
for (const Document::Ptr &document : snapshot) for (const Document::Ptr &document : snapshot)
documentsToCheck << document; documentsToCheck << document;
@@ -869,7 +869,7 @@ CppModelManager *CppModelManager::instance()
void CppModelManager::registerJsExtension() void CppModelManager::registerJsExtension()
{ {
JsExpander::registerGlobalObject("Cpp", [this] { JsExpander::registerGlobalObject("Cpp", [] {
return new CppToolsJsExtension(&d->m_locatorData); return new CppToolsJsExtension(&d->m_locatorData);
}); });
} }
@@ -878,16 +878,16 @@ void CppModelManager::initCppTools()
{ {
// Objects // Objects
connect(VcsManager::instance(), &VcsManager::repositoryChanged, connect(VcsManager::instance(), &VcsManager::repositoryChanged,
this, &CppModelManager::updateModifiedSourceFiles); m_instance, &CppModelManager::updateModifiedSourceFiles);
connect(DocumentManager::instance(), &DocumentManager::filesChangedInternally, connect(DocumentManager::instance(), &DocumentManager::filesChangedInternally,
this, [this](const FilePaths &filePaths) { m_instance, [](const FilePaths &filePaths) {
updateSourceFiles(toSet(filePaths)); updateSourceFiles(toSet(filePaths));
}); });
connect(this, &CppModelManager::documentUpdated, connect(m_instance, &CppModelManager::documentUpdated,
&d->m_locatorData, &CppLocatorData::onDocumentUpdated); &d->m_locatorData, &CppLocatorData::onDocumentUpdated);
connect(this, &CppModelManager::aboutToRemoveFiles, connect(m_instance, &CppModelManager::aboutToRemoveFiles,
&d->m_locatorData, &CppLocatorData::onAboutToRemoveFiles); &d->m_locatorData, &CppLocatorData::onAboutToRemoveFiles);
// Set up builtin filters // Set up builtin filters
@@ -895,7 +895,7 @@ void CppModelManager::initCppTools()
setClassesFilter(std::make_unique<CppClassesFilter>()); setClassesFilter(std::make_unique<CppClassesFilter>());
setIncludesFilter(std::make_unique<CppIncludesFilter>()); setIncludesFilter(std::make_unique<CppIncludesFilter>());
setFunctionsFilter(std::make_unique<CppFunctionsFilter>()); setFunctionsFilter(std::make_unique<CppFunctionsFilter>());
setSymbolsFindFilter(std::make_unique<SymbolsFindFilter>(this)); setSymbolsFindFilter(std::make_unique<SymbolsFindFilter>());
setCurrentDocumentFilter(std::make_unique<CppCurrentDocumentFilter>()); setCurrentDocumentFilter(std::make_unique<CppCurrentDocumentFilter>());
// Setup matchers // Setup matchers
LocatorMatcher::addMatcherCreator(MatcherType::AllSymbols, [] { LocatorMatcher::addMatcherCreator(MatcherType::AllSymbols, [] {
@@ -912,24 +912,13 @@ void CppModelManager::initCppTools()
}); });
} }
static bool setExtraDiagnosticsCallback(const QString &fileName, const QString &kind,
const QList<Document::DiagnosticMessage> &diagnostics)
{
return m_instance->setExtraDiagnostics(fileName, kind, diagnostics);
}
static Snapshot snapshotCallback()
{
return m_instance->snapshot();
}
CppModelManager::CppModelManager() CppModelManager::CppModelManager()
: d(new CppModelManagerPrivate)
{ {
d = new CppModelManagerPrivate;
m_instance = this; m_instance = this;
CppModelManagerBase::registerSetExtraDiagnosticsCallback(&setExtraDiagnosticsCallback); CppModelManagerBase::registerSetExtraDiagnosticsCallback(&CppModelManager::setExtraDiagnostics);
CppModelManagerBase::registerSnapshotCallback(&snapshotCallback); CppModelManagerBase::registerSnapshotCallback(&CppModelManager::snapshot);
// Used for weak dependency in VcsBaseSubmitEditor // Used for weak dependency in VcsBaseSubmitEditor
setObjectName("CppModelManager"); setObjectName("CppModelManager");
@@ -1002,13 +991,13 @@ CppModelManager::~CppModelManager()
delete d; delete d;
} }
Snapshot CppModelManager::snapshot() const Snapshot CppModelManager::snapshot()
{ {
QMutexLocker locker(&d->m_snapshotMutex); QMutexLocker locker(&d->m_snapshotMutex);
return d->m_snapshot; return d->m_snapshot;
} }
Document::Ptr CppModelManager::document(const FilePath &filePath) const Document::Ptr CppModelManager::document(const FilePath &filePath)
{ {
QMutexLocker locker(&d->m_snapshotMutex); QMutexLocker locker(&d->m_snapshotMutex);
return d->m_snapshot.document(filePath); return d->m_snapshot.document(filePath);
@@ -1042,7 +1031,7 @@ void CppModelManager::ensureUpdated()
d->m_dirty = false; d->m_dirty = false;
} }
FilePaths CppModelManager::internalProjectFiles() const FilePaths CppModelManager::internalProjectFiles()
{ {
FilePaths files; FilePaths files;
for (const ProjectData &projectData : std::as_const(d->m_projectData)) { for (const ProjectData &projectData : std::as_const(d->m_projectData)) {
@@ -1055,7 +1044,7 @@ FilePaths CppModelManager::internalProjectFiles() const
return files; return files;
} }
HeaderPaths CppModelManager::internalHeaderPaths() const HeaderPaths CppModelManager::internalHeaderPaths()
{ {
HeaderPaths headerPaths; HeaderPaths headerPaths;
for (const ProjectData &projectData: std::as_const(d->m_projectData)) { for (const ProjectData &projectData: std::as_const(d->m_projectData)) {
@@ -1079,7 +1068,7 @@ static void addUnique(const Macros &newMacros, Macros &macros,
} }
} }
Macros CppModelManager::internalDefinedMacros() const Macros CppModelManager::internalDefinedMacros()
{ {
Macros macros; Macros macros;
QSet<ProjectExplorer::Macro> alreadyIn; QSet<ProjectExplorer::Macro> alreadyIn;
@@ -1107,7 +1096,7 @@ void CppModelManager::dumpModelManagerConfiguration(const QString &logFileId)
ProjectExplorer::Macro::toByteArray(definedMacros())); ProjectExplorer::Macro::toByteArray(definedMacros()));
} }
QSet<AbstractEditorSupport *> CppModelManager::abstractEditorSupports() const QSet<AbstractEditorSupport *> CppModelManager::abstractEditorSupports()
{ {
return d->m_extraEditorSupports; return d->m_extraEditorSupports;
} }
@@ -1122,7 +1111,7 @@ void CppModelManager::removeExtraEditorSupport(AbstractEditorSupport *editorSupp
d->m_extraEditorSupports.remove(editorSupport); d->m_extraEditorSupports.remove(editorSupport);
} }
CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const FilePath &filePath) const CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const FilePath &filePath)
{ {
if (filePath.isEmpty()) if (filePath.isEmpty())
return nullptr; return nullptr;
@@ -1133,7 +1122,7 @@ CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const FilePath &file
BaseEditorDocumentProcessor *CppModelManager::cppEditorDocumentProcessor(const FilePath &filePath) BaseEditorDocumentProcessor *CppModelManager::cppEditorDocumentProcessor(const FilePath &filePath)
{ {
const auto document = instance()->cppEditorDocument(filePath); const auto document = cppEditorDocument(filePath);
return document ? document->processor() : nullptr; return document ? document->processor() : nullptr;
} }
@@ -1237,17 +1226,17 @@ WorkingCopy CppModelManager::buildWorkingCopyList()
return workingCopy; return workingCopy;
} }
WorkingCopy CppModelManager::workingCopy() const WorkingCopy CppModelManager::workingCopy()
{ {
return const_cast<CppModelManager *>(this)->buildWorkingCopyList(); return buildWorkingCopyList();
} }
QByteArray CppModelManager::codeModelConfiguration() const QByteArray CppModelManager::codeModelConfiguration()
{ {
return QByteArray::fromRawData(pp_configuration, qstrlen(pp_configuration)); return QByteArray::fromRawData(pp_configuration, qstrlen(pp_configuration));
} }
CppLocatorData *CppModelManager::locatorData() const CppLocatorData *CppModelManager::locatorData()
{ {
return &d->m_locatorData; return &d->m_locatorData;
} }
@@ -1308,14 +1297,14 @@ QFuture<void> CppModelManager::updateSourceFiles(const QSet<FilePath> &sourceFil
return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode); return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode);
} }
ProjectInfoList CppModelManager::projectInfos() const ProjectInfoList CppModelManager::projectInfos()
{ {
QReadLocker locker(&d->m_projectLock); QReadLocker locker(&d->m_projectLock);
return Utils::transform<QList<ProjectInfo::ConstPtr>>(d->m_projectData, return Utils::transform<QList<ProjectInfo::ConstPtr>>(d->m_projectData,
[](const ProjectData &d) { return d.projectInfo; }); [](const ProjectData &d) { return d.projectInfo; });
} }
ProjectInfo::ConstPtr CppModelManager::projectInfo(Project *project) const ProjectInfo::ConstPtr CppModelManager::projectInfo(Project *project)
{ {
QReadLocker locker(&d->m_projectLock); QReadLocker locker(&d->m_projectLock);
return d->m_projectData.value(project).projectInfo; return d->m_projectData.value(project).projectInfo;
@@ -1335,7 +1324,7 @@ void CppModelManager::removeProjectInfoFilesAndIncludesFromSnapshot(const Projec
} }
} }
const QList<CppEditorDocumentHandle *> CppModelManager::cppEditorDocuments() const const QList<CppEditorDocumentHandle *> CppModelManager::cppEditorDocuments()
{ {
QMutexLocker locker(&d->m_cppEditorDocumentsMutex); QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
return d->m_cppEditorDocuments.values(); return d->m_cppEditorDocuments.values();
@@ -1453,7 +1442,7 @@ void CppModelManagerPrivate::setupWatcher(const QFuture<void> &future, Project *
projectData->indexer->setFuture(future); projectData->indexer->setFuture(future);
} }
void CppModelManager::updateCppEditorDocuments(bool projectsUpdated) const void CppModelManager::updateCppEditorDocuments(bool projectsUpdated)
{ {
// Refresh visible documents // Refresh visible documents
QSet<IDocument *> visibleCppEditorDocuments; QSet<IDocument *> visibleCppEditorDocuments;
@@ -1534,7 +1523,7 @@ QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo::ConstPtr &ne
const QSet<FilePath> removedFiles = comparer.removedFiles(); const QSet<FilePath> removedFiles = comparer.removedFiles();
if (!removedFiles.isEmpty()) { if (!removedFiles.isEmpty()) {
filesRemoved = true; filesRemoved = true;
emit aboutToRemoveFiles(transform<QStringList>(removedFiles, &FilePath::toString)); emit m_instance->aboutToRemoveFiles(transform<QStringList>(removedFiles, &FilePath::toString));
removeFilesFromSnapshot(removedFiles); removeFilesFromSnapshot(removedFiles);
} }
} }
@@ -1570,10 +1559,10 @@ QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo::ConstPtr &ne
// Announce removed project parts // Announce removed project parts
if (!removedProjectParts.isEmpty()) if (!removedProjectParts.isEmpty())
emit projectPartsRemoved(removedProjectParts); emit m_instance->projectPartsRemoved(removedProjectParts);
// Announce added project parts // Announce added project parts
emit projectPartsUpdated(project); emit m_instance->projectPartsUpdated(project);
// Ideally, we would update all the editor documents that depend on the 'filesToReindex'. // Ideally, we would update all the editor documents that depend on the 'filesToReindex'.
// However, on e.g. a session restore first the editor documents are created and then the // However, on e.g. a session restore first the editor documents are created and then the
@@ -1588,25 +1577,25 @@ QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo::ConstPtr &ne
// It's safe to do this here, as only the UI thread writes to the map and no other thread // It's safe to do this here, as only the UI thread writes to the map and no other thread
// uses the indexer value. // uses the indexer value.
d->setupWatcher(indexingFuture, project, projectData, this); d->setupWatcher(indexingFuture, project, projectData, m_instance);
return indexingFuture; return indexingFuture;
} }
ProjectPart::ConstPtr CppModelManager::projectPartForId(const QString &projectPartId) const ProjectPart::ConstPtr CppModelManager::projectPartForId(const QString &projectPartId)
{ {
QReadLocker locker(&d->m_projectLock); QReadLocker locker(&d->m_projectLock);
return d->m_projectPartIdToProjectProjectPart.value(projectPartId); return d->m_projectPartIdToProjectProjectPart.value(projectPartId);
} }
QList<ProjectPart::ConstPtr> CppModelManager::projectPart(const FilePath &fileName) const QList<ProjectPart::ConstPtr> CppModelManager::projectPart(const FilePath &fileName)
{ {
QReadLocker locker(&d->m_projectLock); QReadLocker locker(&d->m_projectLock);
return d->m_fileToProjectParts.value(fileName.canonicalPath()); return d->m_fileToProjectParts.value(fileName.canonicalPath());
} }
QList<ProjectPart::ConstPtr> CppModelManager::projectPartFromDependencies( QList<ProjectPart::ConstPtr> CppModelManager::projectPartFromDependencies(
const FilePath &fileName) const const FilePath &fileName)
{ {
QSet<ProjectPart::ConstPtr> parts; QSet<ProjectPart::ConstPtr> parts;
const FilePaths deps = snapshot().filesDependingOn(fileName); const FilePaths deps = snapshot().filesDependingOn(fileName);
@@ -1631,10 +1620,10 @@ bool CppModelManager::isCppEditor(IEditor *editor)
bool CppModelManager::usesClangd(const TextEditor::TextDocument *document) bool CppModelManager::usesClangd(const TextEditor::TextDocument *document)
{ {
return instance()->d->m_activeModelManagerSupport->usesClangd(document); return d->m_activeModelManagerSupport->usesClangd(document);
} }
bool CppModelManager::isClangCodeModelActive() const bool CppModelManager::isClangCodeModelActive()
{ {
return d->m_activeModelManagerSupport != &d->m_builtinModelManagerSupport; return d->m_activeModelManagerSupport != &d->m_builtinModelManagerSupport;
} }
@@ -1642,19 +1631,19 @@ bool CppModelManager::isClangCodeModelActive() const
void CppModelManager::emitDocumentUpdated(Document::Ptr doc) void CppModelManager::emitDocumentUpdated(Document::Ptr doc)
{ {
if (replaceDocument(doc)) if (replaceDocument(doc))
emit documentUpdated(doc); emit m_instance->documentUpdated(doc);
} }
void CppModelManager::emitAbstractEditorSupportContentsUpdated(const QString &filePath, void CppModelManager::emitAbstractEditorSupportContentsUpdated(const QString &filePath,
const QString &sourcePath, const QString &sourcePath,
const QByteArray &contents) const QByteArray &contents)
{ {
emit abstractEditorSupportContentsUpdated(filePath, sourcePath, contents); emit m_instance->abstractEditorSupportContentsUpdated(filePath, sourcePath, contents);
} }
void CppModelManager::emitAbstractEditorSupportRemoved(const QString &filePath) void CppModelManager::emitAbstractEditorSupportRemoved(const QString &filePath)
{ {
emit abstractEditorSupportRemoved(filePath); emit m_instance->abstractEditorSupportRemoved(filePath);
} }
void CppModelManager::onProjectAdded(Project *) void CppModelManager::onProjectAdded(Project *)
@@ -1694,7 +1683,7 @@ void CppModelManager::onAboutToRemoveProject(Project *project)
} }
if (!idsOfRemovedProjectParts.isEmpty()) if (!idsOfRemovedProjectParts.isEmpty())
emit projectPartsRemoved(idsOfRemovedProjectParts); emit m_instance->projectPartsRemoved(idsOfRemovedProjectParts);
delayedGC(); delayedGC();
} }
@@ -1713,7 +1702,7 @@ void CppModelManager::onActiveProjectChanged(Project *project)
updateCppEditorDocuments(); updateCppEditorDocuments();
} }
void CppModelManager::onSourceFilesRefreshed() const void CppModelManager::onSourceFilesRefreshed()
{ {
if (CppIndexingSupport::isFindErrorsIndexingActive()) { if (CppIndexingSupport::isFindErrorsIndexingActive()) {
QTimer::singleShot(1, QCoreApplication::instance(), &QCoreApplication::quit); QTimer::singleShot(1, QCoreApplication::instance(), &QCoreApplication::quit);
@@ -1745,10 +1734,10 @@ void CppModelManager::onAboutToLoadSession()
GC(); GC();
} }
QSet<QString> CppModelManager::dependingInternalTargets(const FilePath &file) const QSet<QString> CppModelManager::dependingInternalTargets(const FilePath &file)
{ {
QSet<QString> result; QSet<QString> result;
const Snapshot snapshot = this->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
QTC_ASSERT(snapshot.contains(file), return result); QTC_ASSERT(snapshot.contains(file), return result);
bool wasHeader; bool wasHeader;
const FilePath correspondingFile const FilePath correspondingFile
@@ -1762,8 +1751,10 @@ QSet<QString> CppModelManager::dependingInternalTargets(const FilePath &file) co
return result; return result;
} }
QSet<QString> CppModelManager::internalTargets(const FilePath &filePath) const QSet<QString> CppModelManager::internalTargets(const FilePath &filePath)
{ {
QTC_ASSERT(m_instance, return {});
const QList<ProjectPart::ConstPtr> projectParts = projectPart(filePath); const QList<ProjectPart::ConstPtr> projectParts = projectPart(filePath);
// if we have no project parts it's most likely a header with declarations only and CMake based // if we have no project parts it's most likely a header with declarations only and CMake based
if (projectParts.isEmpty()) if (projectParts.isEmpty())
@@ -1931,7 +1922,7 @@ void CppModelManager::setupFallbackProjectPart()
QMutexLocker locker(&d->m_fallbackProjectPartMutex); QMutexLocker locker(&d->m_fallbackProjectPartMutex);
d->m_fallbackProjectPart = part; d->m_fallbackProjectPart = part;
} }
emit fallbackProjectPartUpdated(); emit m_instance->fallbackProjectPartUpdated();
} }
void CppModelManager::GC() void CppModelManager::GC()
@@ -1981,14 +1972,14 @@ void CppModelManager::GC()
} }
// Announce removing files and replace the snapshot // Announce removing files and replace the snapshot
emit aboutToRemoveFiles(notReachableFiles); emit m_instance->aboutToRemoveFiles(notReachableFiles);
replaceSnapshot(newSnapshot); replaceSnapshot(newSnapshot);
emit gcFinished(); emit m_instance->gcFinished();
} }
void CppModelManager::finishedRefreshingSourceFiles(const QSet<QString> &files) void CppModelManager::finishedRefreshingSourceFiles(const QSet<QString> &files)
{ {
emit sourceFilesRefreshed(files); emit m_instance->sourceFilesRefreshed(files);
} }
void CppModelManager::activateClangCodeModel( void CppModelManager::activateClangCodeModel(
@@ -1998,12 +1989,12 @@ void CppModelManager::activateClangCodeModel(
d->m_activeModelManagerSupport = d->m_extendedModelManagerSupport.get(); d->m_activeModelManagerSupport = d->m_extendedModelManagerSupport.get();
} }
CppCompletionAssistProvider *CppModelManager::completionAssistProvider() const CppCompletionAssistProvider *CppModelManager::completionAssistProvider()
{ {
return d->m_builtinModelManagerSupport.completionAssistProvider(); return d->m_builtinModelManagerSupport.completionAssistProvider();
} }
TextEditor::BaseHoverHandler *CppModelManager::createHoverHandler() const TextEditor::BaseHoverHandler *CppModelManager::createHoverHandler()
{ {
return d->m_builtinModelManagerSupport.createHoverHandler(); return d->m_builtinModelManagerSupport.createHoverHandler();
} }
@@ -2012,7 +2003,7 @@ void CppModelManager::followSymbol(const CursorInEditor &data,
const LinkHandler &processLinkCallback, const LinkHandler &processLinkCallback,
bool resolveTarget, bool inNextSplit, Backend backend) bool resolveTarget, bool inNextSplit, Backend backend)
{ {
instance()->modelManagerSupport(backend)->followSymbol(data, processLinkCallback, modelManagerSupport(backend)->followSymbol(data, processLinkCallback,
resolveTarget, inNextSplit); resolveTarget, inNextSplit);
} }
@@ -2020,7 +2011,7 @@ void CppModelManager::followSymbolToType(const CursorInEditor &data,
const LinkHandler &processLinkCallback, const LinkHandler &processLinkCallback,
bool inNextSplit, Backend backend) bool inNextSplit, Backend backend)
{ {
instance()->modelManagerSupport(backend)->followSymbolToType(data, processLinkCallback, modelManagerSupport(backend)->followSymbolToType(data, processLinkCallback,
inNextSplit); inNextSplit);
} }
@@ -2028,11 +2019,11 @@ void CppModelManager::switchDeclDef(const CursorInEditor &data,
const LinkHandler &processLinkCallback, const LinkHandler &processLinkCallback,
Backend backend) Backend backend)
{ {
instance()->modelManagerSupport(backend)->switchDeclDef(data, processLinkCallback); modelManagerSupport(backend)->switchDeclDef(data, processLinkCallback);
} }
BaseEditorDocumentProcessor *CppModelManager::createEditorDocumentProcessor( BaseEditorDocumentProcessor *CppModelManager::createEditorDocumentProcessor(
TextEditor::TextDocument *baseTextDocument) const TextEditor::TextDocument *baseTextDocument)
{ {
return d->m_activeModelManagerSupport->createEditorDocumentProcessor(baseTextDocument); return d->m_activeModelManagerSupport->createEditorDocumentProcessor(baseTextDocument);
} }
@@ -2093,7 +2084,7 @@ bool CppModelManager::setExtraDiagnostics(const QString &fileName,
const QList<Document::DiagnosticMessage> &diagnostics) const QList<Document::DiagnosticMessage> &diagnostics)
{ {
d->m_diagnosticMessages = diagnostics; d->m_diagnosticMessages = diagnostics;
emit diagnosticsChanged(fileName, kind); emit m_instance->diagnosticsChanged(fileName, kind);
return true; return true;
} }

View File

@@ -80,95 +80,95 @@ public:
static CppModelManager *instance(); static CppModelManager *instance();
void registerJsExtension(); static void registerJsExtension();
// Documented in source file. // Documented in source file.
enum ProgressNotificationMode { enum ProgressNotificationMode {
ForcedProgressNotification, ForcedProgressNotification,
ReservedProgressNotification ReservedProgressNotification
}; };
QFuture<void> updateSourceFiles(const QSet<Utils::FilePath> &sourceFiles, static QFuture<void> updateSourceFiles(const QSet<Utils::FilePath> &sourceFiles,
ProgressNotificationMode mode = ReservedProgressNotification); ProgressNotificationMode mode = ReservedProgressNotification);
void updateCppEditorDocuments(bool projectsUpdated = false) const; static void updateCppEditorDocuments(bool projectsUpdated = false);
WorkingCopy workingCopy() const; static WorkingCopy workingCopy();
QByteArray codeModelConfiguration() const; static QByteArray codeModelConfiguration();
CppLocatorData *locatorData() const; static CppLocatorData *locatorData();
bool setExtraDiagnostics(const QString &fileName, static bool setExtraDiagnostics(const QString &fileName,
const QString &kind, const QString &kind,
const QList<Document::DiagnosticMessage> &diagnostics); const QList<Document::DiagnosticMessage> &diagnostics);
const QList<Document::DiagnosticMessage> diagnosticMessages(); static const QList<Document::DiagnosticMessage> diagnosticMessages();
ProjectInfoList projectInfos() const; static ProjectInfoList projectInfos();
ProjectInfo::ConstPtr projectInfo(ProjectExplorer::Project *project) const; static ProjectInfo::ConstPtr projectInfo(ProjectExplorer::Project *project);
QFuture<void> updateProjectInfo(const ProjectInfo::ConstPtr &newProjectInfo, static QFuture<void> updateProjectInfo(const ProjectInfo::ConstPtr &newProjectInfo,
const QSet<Utils::FilePath> &additionalFiles = {}); const QSet<Utils::FilePath> &additionalFiles = {});
/// \return The project part with the given project file /// \return The project part with the given project file
ProjectPart::ConstPtr projectPartForId(const QString &projectPartId) const; static ProjectPart::ConstPtr projectPartForId(const QString &projectPartId);
/// \return All project parts that mention the given file name as one of the sources/headers. /// \return All project parts that mention the given file name as one of the sources/headers.
QList<ProjectPart::ConstPtr> projectPart(const Utils::FilePath &fileName) const; static QList<ProjectPart::ConstPtr> projectPart(const Utils::FilePath &fileName);
QList<ProjectPart::ConstPtr> projectPart(const QString &fileName) const static QList<ProjectPart::ConstPtr> projectPart(const QString &fileName)
{ return projectPart(Utils::FilePath::fromString(fileName)); } { return projectPart(Utils::FilePath::fromString(fileName)); }
/// This is a fall-back function: find all files that includes the file directly or indirectly, /// This is a fall-back function: find all files that includes the file directly or indirectly,
/// and return its \c ProjectPart list for use with this file. /// and return its \c ProjectPart list for use with this file.
QList<ProjectPart::ConstPtr> projectPartFromDependencies(const Utils::FilePath &fileName) const; static QList<ProjectPart::ConstPtr> projectPartFromDependencies(const Utils::FilePath &fileName);
/// \return A synthetic \c ProjectPart which consists of all defines/includes/frameworks from /// \return A synthetic \c ProjectPart which consists of all defines/includes/frameworks from
/// all loaded projects. /// all loaded projects.
ProjectPart::ConstPtr fallbackProjectPart(); static ProjectPart::ConstPtr fallbackProjectPart();
CPlusPlus::Snapshot snapshot() const; static CPlusPlus::Snapshot snapshot();
Document::Ptr document(const Utils::FilePath &filePath) const; static Document::Ptr document(const Utils::FilePath &filePath);
bool replaceDocument(Document::Ptr newDoc); static bool replaceDocument(Document::Ptr newDoc);
void emitDocumentUpdated(Document::Ptr doc); static void emitDocumentUpdated(Document::Ptr doc);
void emitAbstractEditorSupportContentsUpdated(const QString &filePath, static void emitAbstractEditorSupportContentsUpdated(const QString &filePath,
const QString &sourcePath, const QString &sourcePath,
const QByteArray &contents); const QByteArray &contents);
void emitAbstractEditorSupportRemoved(const QString &filePath); static void emitAbstractEditorSupportRemoved(const QString &filePath);
static bool isCppEditor(Core::IEditor *editor); static bool isCppEditor(Core::IEditor *editor);
static bool usesClangd(const TextEditor::TextDocument *document); static bool usesClangd(const TextEditor::TextDocument *document);
bool isClangCodeModelActive() const; static bool isClangCodeModelActive();
QSet<AbstractEditorSupport*> abstractEditorSupports() const; static QSet<AbstractEditorSupport*> abstractEditorSupports();
void addExtraEditorSupport(AbstractEditorSupport *editorSupport); static void addExtraEditorSupport(AbstractEditorSupport *editorSupport);
void removeExtraEditorSupport(AbstractEditorSupport *editorSupport); static void removeExtraEditorSupport(AbstractEditorSupport *editorSupport);
const QList<CppEditorDocumentHandle *> cppEditorDocuments() const; static const QList<CppEditorDocumentHandle *> cppEditorDocuments();
CppEditorDocumentHandle *cppEditorDocument(const Utils::FilePath &filePath) const; static CppEditorDocumentHandle *cppEditorDocument(const Utils::FilePath &filePath);
static BaseEditorDocumentProcessor *cppEditorDocumentProcessor(const Utils::FilePath &filePath); static BaseEditorDocumentProcessor *cppEditorDocumentProcessor(const Utils::FilePath &filePath);
void registerCppEditorDocument(CppEditorDocumentHandle *cppEditorDocument); static void registerCppEditorDocument(CppEditorDocumentHandle *cppEditorDocument);
void unregisterCppEditorDocument(const QString &filePath); static void unregisterCppEditorDocument(const QString &filePath);
QList<int> references(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context); static QList<int> references(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context);
SignalSlotType getSignalSlotType(const Utils::FilePath &filePath, static SignalSlotType getSignalSlotType(const Utils::FilePath &filePath,
const QByteArray &content, const QByteArray &content,
int position) const; int position);
void renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context, static void renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context,
const QString &replacement = QString(), const QString &replacement = QString(),
const std::function<void()> &callback = {}); const std::function<void()> &callback = {});
void renameUsages(const CPlusPlus::Document::Ptr &doc, static void renameUsages(const CPlusPlus::Document::Ptr &doc,
const QTextCursor &cursor, const QTextCursor &cursor,
const CPlusPlus::Snapshot &snapshot, const CPlusPlus::Snapshot &snapshot,
const QString &replacement, const QString &replacement,
const std::function<void()> &callback); const std::function<void()> &callback);
void findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context); static void findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context);
void findMacroUsages(const CPlusPlus::Macro &macro); static void findMacroUsages(const CPlusPlus::Macro &macro);
void renameMacroUsages(const CPlusPlus::Macro &macro, const QString &replacement); static void renameMacroUsages(const CPlusPlus::Macro &macro, const QString &replacement);
void finishedRefreshingSourceFiles(const QSet<QString> &files); static void finishedRefreshingSourceFiles(const QSet<QString> &files);
void activateClangCodeModel(std::unique_ptr<ModelManagerSupport> &&modelManagerSupport); static void activateClangCodeModel(std::unique_ptr<ModelManagerSupport> &&modelManagerSupport);
CppCompletionAssistProvider *completionAssistProvider() const; static CppCompletionAssistProvider *completionAssistProvider();
BaseEditorDocumentProcessor *createEditorDocumentProcessor( static BaseEditorDocumentProcessor *createEditorDocumentProcessor(
TextEditor::TextDocument *baseTextDocument) const; TextEditor::TextDocument *baseTextDocument);
TextEditor::BaseHoverHandler *createHoverHandler() const; static TextEditor::BaseHoverHandler *createHoverHandler();
static FollowSymbolUnderCursor &builtinFollowSymbol(); static FollowSymbolUnderCursor &builtinFollowSymbol();
enum class Backend { Builtin, Best }; enum class Backend { Builtin, Best };
@@ -196,22 +196,22 @@ public:
const CPlusPlus::LookupContext &context, const CPlusPlus::LookupContext &context,
const Utils::LinkHandler &callback); const Utils::LinkHandler &callback);
CppIndexingSupport *indexingSupport(); static CppIndexingSupport *indexingSupport();
Utils::FilePaths projectFiles(); static Utils::FilePaths projectFiles();
ProjectExplorer::HeaderPaths headerPaths(); static ProjectExplorer::HeaderPaths headerPaths();
// Use this *only* for auto tests // Use this *only* for auto tests
void setHeaderPaths(const ProjectExplorer::HeaderPaths &headerPaths); static void setHeaderPaths(const ProjectExplorer::HeaderPaths &headerPaths);
ProjectExplorer::Macros definedMacros(); static ProjectExplorer::Macros definedMacros();
void enableGarbageCollector(bool enable); static void enableGarbageCollector(bool enable);
SymbolFinder *symbolFinder(); static SymbolFinder *symbolFinder();
QThreadPool *sharedThreadPool(); static QThreadPool *sharedThreadPool();
static QSet<Utils::FilePath> timeStampModifiedFiles(const QList<Document::Ptr> &documentsToCheck); static QSet<Utils::FilePath> timeStampModifiedFiles(const QList<Document::Ptr> &documentsToCheck);
@@ -219,34 +219,34 @@ public:
static const Utils::FilePath &configurationFileName(); static const Utils::FilePath &configurationFileName();
static const Utils::FilePath &editorConfigurationFileName(); static const Utils::FilePath &editorConfigurationFileName();
void setLocatorFilter(std::unique_ptr<Core::ILocatorFilter> &&filter); static void setLocatorFilter(std::unique_ptr<Core::ILocatorFilter> &&filter);
void setClassesFilter(std::unique_ptr<Core::ILocatorFilter> &&filter); static void setClassesFilter(std::unique_ptr<Core::ILocatorFilter> &&filter);
void setIncludesFilter(std::unique_ptr<Core::ILocatorFilter> &&filter); static void setIncludesFilter(std::unique_ptr<Core::ILocatorFilter> &&filter);
void setFunctionsFilter(std::unique_ptr<Core::ILocatorFilter> &&filter); static void setFunctionsFilter(std::unique_ptr<Core::ILocatorFilter> &&filter);
void setSymbolsFindFilter(std::unique_ptr<Core::IFindFilter> &&filter); static void setSymbolsFindFilter(std::unique_ptr<Core::IFindFilter> &&filter);
void setCurrentDocumentFilter(std::unique_ptr<Core::ILocatorFilter> &&filter); static void setCurrentDocumentFilter(std::unique_ptr<Core::ILocatorFilter> &&filter);
Core::ILocatorFilter *locatorFilter() const; static Core::ILocatorFilter *locatorFilter();
Core::ILocatorFilter *classesFilter() const; static Core::ILocatorFilter *classesFilter();
Core::ILocatorFilter *includesFilter() const; static Core::ILocatorFilter *includesFilter();
Core::ILocatorFilter *functionsFilter() const; static Core::ILocatorFilter *functionsFilter();
Core::IFindFilter *symbolsFindFilter() const; static Core::IFindFilter *symbolsFindFilter();
Core::ILocatorFilter *currentDocumentFilter() const; static Core::ILocatorFilter *currentDocumentFilter();
/* /*
* try to find build system target that depends on the given file - if the file is no header * try to find build system target that depends on the given file - if the file is no header
* try to find the corresponding header and use this instead to find the respective target * try to find the corresponding header and use this instead to find the respective target
*/ */
QSet<QString> dependingInternalTargets(const Utils::FilePath &file) const; static QSet<QString> dependingInternalTargets(const Utils::FilePath &file);
QSet<QString> internalTargets(const Utils::FilePath &filePath) const; static QSet<QString> internalTargets(const Utils::FilePath &filePath);
void renameIncludes(const Utils::FilePath &oldFilePath, const Utils::FilePath &newFilePath); static void renameIncludes(const Utils::FilePath &oldFilePath, const Utils::FilePath &newFilePath);
// for VcsBaseSubmitEditor // for VcsBaseSubmitEditor
Q_INVOKABLE QSet<QString> symbolsInFiles(const QSet<Utils::FilePath> &files) const; Q_INVOKABLE QSet<QString> symbolsInFiles(const QSet<Utils::FilePath> &files) const;
ModelManagerSupport *modelManagerSupport(Backend backend) const; static ModelManagerSupport *modelManagerSupport(Backend backend);
signals: signals:
/// Project data might be locked while this is emitted. /// Project data might be locked while this is emitted.
@@ -271,40 +271,37 @@ signals:
void diagnosticsChanged(const QString &fileName, const QString &kind); void diagnosticsChanged(const QString &fileName, const QString &kind);
public slots: public slots:
void updateModifiedSourceFiles(); static void updateModifiedSourceFiles();
void GC(); static void GC();
private: private:
// This should be executed in the GUI thread. // This should be executed in the GUI thread.
friend class Tests::ModelManagerTestHelper; friend class Tests::ModelManagerTestHelper;
void onAboutToLoadSession(); static void onAboutToLoadSession();
void onProjectAdded(ProjectExplorer::Project *project); static void onProjectAdded(ProjectExplorer::Project *project);
void onAboutToRemoveProject(ProjectExplorer::Project *project); static void onAboutToRemoveProject(ProjectExplorer::Project *project);
void onActiveProjectChanged(ProjectExplorer::Project *project); static void onActiveProjectChanged(ProjectExplorer::Project *project);
void onSourceFilesRefreshed() const; static void onSourceFilesRefreshed();
void onCurrentEditorChanged(Core::IEditor *editor); static void onCurrentEditorChanged(Core::IEditor *editor);
void onCoreAboutToClose(); static void onCoreAboutToClose();
void setupFallbackProjectPart(); static void setupFallbackProjectPart();
void delayedGC(); static void delayedGC();
void recalculateProjectPartMappings(); static void recalculateProjectPartMappings();
void replaceSnapshot(const CPlusPlus::Snapshot &newSnapshot); static void replaceSnapshot(const CPlusPlus::Snapshot &newSnapshot);
void removeFilesFromSnapshot(const QSet<Utils::FilePath> &removedFiles); static void removeFilesFromSnapshot(const QSet<Utils::FilePath> &removedFiles);
void removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo); static void removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo);
WorkingCopy buildWorkingCopyList(); static WorkingCopy buildWorkingCopyList();
void ensureUpdated(); static void ensureUpdated();
Utils::FilePaths internalProjectFiles() const; static Utils::FilePaths internalProjectFiles();
ProjectExplorer::HeaderPaths internalHeaderPaths() const; static ProjectExplorer::HeaderPaths internalHeaderPaths();
ProjectExplorer::Macros internalDefinedMacros() const; static ProjectExplorer::Macros internalDefinedMacros();
void dumpModelManagerConfiguration(const QString &logFileId); static void dumpModelManagerConfiguration(const QString &logFileId);
void initCppTools(); static void initCppTools();
private:
Internal::CppModelManagerPrivate *d;
}; };
} // CppEditor } // CppEditor

View File

@@ -164,7 +164,7 @@ private:
static ProjectPart::ConstPtr projectPartOfEditorDocument(const FilePath &filePath) static ProjectPart::ConstPtr projectPartOfEditorDocument(const FilePath &filePath)
{ {
auto *editorDocument = CppModelManager::instance()->cppEditorDocument(filePath); auto *editorDocument = CppModelManager::cppEditorDocument(filePath);
QTC_ASSERT(editorDocument, return ProjectPart::ConstPtr()); QTC_ASSERT(editorDocument, return ProjectPart::ConstPtr());
return editorDocument->processor()->parser()->projectPartInfo().projectPart; return editorDocument->processor()->parser()->projectPartInfo().projectPart;
} }
@@ -173,7 +173,6 @@ static ProjectPart::ConstPtr projectPartOfEditorDocument(const FilePath &filePat
void ModelManagerTest::testPathsAreClean() void ModelManagerTest::testPathsAreClean()
{ {
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata")); const MyTestDataDir testDataDir(_("testdata"));
@@ -188,9 +187,9 @@ void ModelManagerTest::testPathsAreClean()
const auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}), const auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}),
{part}); {part});
mm->updateProjectInfo(pi); CppModelManager::updateProjectInfo(pi);
ProjectExplorer::HeaderPaths headerPaths = mm->headerPaths(); ProjectExplorer::HeaderPaths headerPaths = CppModelManager::headerPaths();
QCOMPARE(headerPaths.size(), 2); QCOMPARE(headerPaths.size(), 2);
QVERIFY(headerPaths.contains(HeaderPath::makeUser(testDataDir.includeDir()))); QVERIFY(headerPaths.contains(HeaderPath::makeUser(testDataDir.includeDir())));
QVERIFY(headerPaths.contains(HeaderPath::makeFramework(testDataDir.frameworksDir()))); QVERIFY(headerPaths.contains(HeaderPath::makeFramework(testDataDir.frameworksDir())));
@@ -203,7 +202,6 @@ void ModelManagerTest::testFrameworkHeaders()
QSKIP("Can't resolve framework soft links on Windows."); QSKIP("Can't resolve framework soft links on Windows.");
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata")); const MyTestDataDir testDataDir(_("testdata"));
@@ -221,11 +219,11 @@ void ModelManagerTest::testFrameworkHeaders()
const auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}), const auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}),
{part}); {part});
mm->updateProjectInfo(pi).waitForFinished(); CppModelManager::updateProjectInfo(pi).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
QVERIFY(mm->snapshot().contains(source)); QVERIFY(CppModelManager::snapshot().contains(source));
Document::Ptr doc = mm->document(source); Document::Ptr doc = CppModelManager::document(source);
QVERIFY(!doc.isNull()); QVERIFY(!doc.isNull());
CPlusPlus::Namespace *ns = doc->globalNamespace(); CPlusPlus::Namespace *ns = doc->globalNamespace();
QVERIFY(ns); QVERIFY(ns);
@@ -247,7 +245,6 @@ void ModelManagerTest::testFrameworkHeaders()
void ModelManagerTest::testRefreshAlsoIncludesOfProjectFiles() void ModelManagerTest::testRefreshAlsoIncludesOfProjectFiles()
{ {
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata")); const MyTestDataDir testDataDir(_("testdata"));
@@ -268,7 +265,7 @@ void ModelManagerTest::testRefreshAlsoIncludesOfProjectFiles()
QSet<FilePath> refreshedFiles = helper.updateProjectInfo(pi); QSet<FilePath> refreshedFiles = helper.updateProjectInfo(pi);
QCOMPARE(refreshedFiles.size(), 1); QCOMPARE(refreshedFiles.size(), 1);
QVERIFY(refreshedFiles.contains(testCpp)); QVERIFY(refreshedFiles.contains(testCpp));
CPlusPlus::Snapshot snapshot = mm->snapshot(); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
QVERIFY(snapshot.contains(testHeader)); QVERIFY(snapshot.contains(testHeader));
QVERIFY(snapshot.contains(testCpp)); QVERIFY(snapshot.contains(testCpp));
@@ -287,7 +284,7 @@ void ModelManagerTest::testRefreshAlsoIncludesOfProjectFiles()
QCOMPARE(refreshedFiles.size(), 1); QCOMPARE(refreshedFiles.size(), 1);
QVERIFY(refreshedFiles.contains(testCpp)); QVERIFY(refreshedFiles.contains(testCpp));
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
QVERIFY(snapshot.contains(testHeader)); QVERIFY(snapshot.contains(testHeader));
QVERIFY(snapshot.contains(testCpp)); QVERIFY(snapshot.contains(testCpp));
@@ -304,7 +301,6 @@ void ModelManagerTest::testRefreshAlsoIncludesOfProjectFiles()
void ModelManagerTest::testRefreshSeveralTimes() void ModelManagerTest::testRefreshSeveralTimes()
{ {
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata_refresh")); const MyTestDataDir testDataDir(_("testdata_refresh"));
@@ -323,7 +319,7 @@ void ModelManagerTest::testRefreshSeveralTimes()
}; };
const auto part = ProjectPart::create(project->projectFilePath(), rpp, {}, files); const auto part = ProjectPart::create(project->projectFilePath(), rpp, {}, files);
auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}), {part}); auto pi = ProjectInfo::create(ProjectUpdateInfo(project, KitInfo(nullptr), {}, {}), {part});
mm->updateProjectInfo(pi); CppModelManager::updateProjectInfo(pi);
CPlusPlus::Snapshot snapshot; CPlusPlus::Snapshot snapshot;
QSet<FilePath> refreshedFiles; QSet<FilePath> refreshedFiles;
@@ -344,7 +340,7 @@ void ModelManagerTest::testRefreshSeveralTimes()
QVERIFY(refreshedFiles.contains(testHeader2)); QVERIFY(refreshedFiles.contains(testHeader2));
QVERIFY(refreshedFiles.contains(testCpp)); QVERIFY(refreshedFiles.contains(testCpp));
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
QVERIFY(snapshot.contains(testHeader1)); QVERIFY(snapshot.contains(testHeader1));
QVERIFY(snapshot.contains(testHeader2)); QVERIFY(snapshot.contains(testHeader2));
QVERIFY(snapshot.contains(testCpp)); QVERIFY(snapshot.contains(testCpp));
@@ -366,7 +362,6 @@ void ModelManagerTest::testRefreshSeveralTimes()
void ModelManagerTest::testRefreshTestForChanges() void ModelManagerTest::testRefreshTestForChanges()
{ {
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata_refresh")); const MyTestDataDir testDataDir(_("testdata_refresh"));
const FilePath testCpp = testDataDir.filePath("source.cpp"); const FilePath testCpp = testDataDir.filePath("source.cpp");
@@ -381,7 +376,7 @@ void ModelManagerTest::testRefreshTestForChanges()
// Reindexing triggers a reparsing thread // Reindexing triggers a reparsing thread
helper.resetRefreshedSourceFiles(); helper.resetRefreshedSourceFiles();
QFuture<void> firstFuture = mm->updateProjectInfo(pi); QFuture<void> firstFuture = CppModelManager::updateProjectInfo(pi);
QVERIFY(firstFuture.isStarted() || firstFuture.isRunning()); QVERIFY(firstFuture.isStarted() || firstFuture.isRunning());
firstFuture.waitForFinished(); firstFuture.waitForFinished();
const QSet<FilePath> refreshedFiles = helper.waitForRefreshedSourceFiles(); const QSet<FilePath> refreshedFiles = helper.waitForRefreshedSourceFiles();
@@ -389,7 +384,7 @@ void ModelManagerTest::testRefreshTestForChanges()
QVERIFY(refreshedFiles.contains(testCpp)); QVERIFY(refreshedFiles.contains(testCpp));
// No reindexing since nothing has changed // No reindexing since nothing has changed
QFuture<void> subsequentFuture = mm->updateProjectInfo(pi); QFuture<void> subsequentFuture = CppModelManager::updateProjectInfo(pi);
QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished()); QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished());
} }
@@ -398,7 +393,6 @@ void ModelManagerTest::testRefreshTestForChanges()
void ModelManagerTest::testRefreshAddedAndPurgeRemoved() void ModelManagerTest::testRefreshAddedAndPurgeRemoved()
{ {
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const MyTestDataDir testDataDir(_("testdata_refresh")); const MyTestDataDir testDataDir(_("testdata_refresh"));
@@ -424,7 +418,7 @@ void ModelManagerTest::testRefreshAddedAndPurgeRemoved()
QVERIFY(refreshedFiles.contains(testHeader1)); QVERIFY(refreshedFiles.contains(testHeader1));
QVERIFY(refreshedFiles.contains(testCpp)); QVERIFY(refreshedFiles.contains(testCpp));
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
QVERIFY(snapshot.contains(testHeader1)); QVERIFY(snapshot.contains(testHeader1));
QVERIFY(snapshot.contains(testCpp)); QVERIFY(snapshot.contains(testCpp));
@@ -440,7 +434,7 @@ void ModelManagerTest::testRefreshAddedAndPurgeRemoved()
QCOMPARE(refreshedFiles.size(), 1); QCOMPARE(refreshedFiles.size(), 1);
QVERIFY(refreshedFiles.contains(testHeader2)); QVERIFY(refreshedFiles.contains(testHeader2));
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
QVERIFY(snapshot.contains(testHeader2)); QVERIFY(snapshot.contains(testHeader2));
QVERIFY(snapshot.contains(testCpp)); QVERIFY(snapshot.contains(testCpp));
// The removed project file is not anymore in the snapshot // The removed project file is not anymore in the snapshot
@@ -461,7 +455,6 @@ void ModelManagerTest::testRefreshTimeStampModifiedIfSourcefilesChange()
const FilePaths finalProjectFilePaths = toAbsolutePaths(finalProjectFiles, temporaryDir); const FilePaths finalProjectFilePaths = toAbsolutePaths(finalProjectFiles, temporaryDir);
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
const auto project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"), const auto project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"),
FilePath::fromString("blubb.pro")); FilePath::fromString("blubb.pro"));
@@ -480,7 +473,7 @@ void ModelManagerTest::testRefreshTimeStampModifiedIfSourcefilesChange()
refreshedFiles = helper.updateProjectInfo(pi); refreshedFiles = helper.updateProjectInfo(pi);
QCOMPARE(refreshedFiles.size(), initialProjectFilePaths.size()); QCOMPARE(refreshedFiles.size(), initialProjectFilePaths.size());
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
for (const FilePath &file : initialProjectFilePaths) { for (const FilePath &file : initialProjectFilePaths) {
QVERIFY(refreshedFiles.contains(file)); QVERIFY(refreshedFiles.contains(file));
QVERIFY(snapshot.contains(file)); QVERIFY(snapshot.contains(file));
@@ -509,7 +502,7 @@ void ModelManagerTest::testRefreshTimeStampModifiedIfSourcefilesChange()
refreshedFiles = helper.updateProjectInfo(pi); refreshedFiles = helper.updateProjectInfo(pi);
QCOMPARE(refreshedFiles.size(), finalProjectFilePaths.size()); QCOMPARE(refreshedFiles.size(), finalProjectFilePaths.size());
snapshot = mm->snapshot(); snapshot = CppModelManager::snapshot();
for (const FilePath &file : finalProjectFilePaths) { for (const FilePath &file : finalProjectFilePaths) {
QVERIFY(refreshedFiles.contains(file)); QVERIFY(refreshedFiles.contains(file));
QVERIFY(snapshot.contains(file)); QVERIFY(snapshot.contains(file));
@@ -550,7 +543,6 @@ void ModelManagerTest::testSnapshotAfterTwoProjects()
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
ProjectCreator project1(&helper); ProjectCreator project1(&helper);
ProjectCreator project2(&helper); ProjectCreator project2(&helper);
CppModelManager *mm = CppModelManager::instance();
// Project 1 // Project 1
project1.create(_("test_modelmanager_snapshot_after_two_projects.1"), project1.create(_("test_modelmanager_snapshot_after_two_projects.1"),
@@ -559,10 +551,10 @@ void ModelManagerTest::testSnapshotAfterTwoProjects()
refreshedFiles = helper.updateProjectInfo(project1.projectInfo); refreshedFiles = helper.updateProjectInfo(project1.projectInfo);
QCOMPARE(refreshedFiles, Utils::toSet(project1.projectFiles)); QCOMPARE(refreshedFiles, Utils::toSet(project1.projectFiles));
const int snapshotSizeAfterProject1 = mm->snapshot().size(); const int snapshotSizeAfterProject1 = CppModelManager::snapshot().size();
for (const FilePath &file : std::as_const(project1.projectFiles)) for (const FilePath &file : std::as_const(project1.projectFiles))
QVERIFY(mm->snapshot().contains(file)); QVERIFY(CppModelManager::snapshot().contains(file));
// Project 2 // Project 2
project2.create(_("test_modelmanager_snapshot_after_two_projects.2"), project2.create(_("test_modelmanager_snapshot_after_two_projects.2"),
@@ -572,14 +564,14 @@ void ModelManagerTest::testSnapshotAfterTwoProjects()
refreshedFiles = helper.updateProjectInfo(project2.projectInfo); refreshedFiles = helper.updateProjectInfo(project2.projectInfo);
QCOMPARE(refreshedFiles, Utils::toSet(project2.projectFiles)); QCOMPARE(refreshedFiles, Utils::toSet(project2.projectFiles));
const int snapshotSizeAfterProject2 = mm->snapshot().size(); const int snapshotSizeAfterProject2 = CppModelManager::snapshot().size();
QVERIFY(snapshotSizeAfterProject2 > snapshotSizeAfterProject1); QVERIFY(snapshotSizeAfterProject2 > snapshotSizeAfterProject1);
QVERIFY(snapshotSizeAfterProject2 >= snapshotSizeAfterProject1 + project2.projectFiles.size()); QVERIFY(snapshotSizeAfterProject2 >= snapshotSizeAfterProject1 + project2.projectFiles.size());
for (const FilePath &file : std::as_const(project1.projectFiles)) for (const FilePath &file : std::as_const(project1.projectFiles))
QVERIFY(mm->snapshot().contains(file)); QVERIFY(CppModelManager::snapshot().contains(file));
for (const FilePath &file : std::as_const(project2.projectFiles)) for (const FilePath &file : std::as_const(project2.projectFiles))
QVERIFY(mm->snapshot().contains(file)); QVERIFY(CppModelManager::snapshot().contains(file));
} }
/// Check: (1) For a project with a *.ui file an AbstractEditorSupport object /// Check: (1) For a project with a *.ui file an AbstractEditorSupport object
@@ -601,10 +593,9 @@ void ModelManagerTest::testExtraeditorsupportUiFiles()
// Check working copy. // Check working copy.
// An AbstractEditorSupport object should have been added for the ui_* file. // An AbstractEditorSupport object should have been added for the ui_* file.
CppModelManager *mm = CppModelManager::instance(); WorkingCopy workingCopy = CppModelManager::workingCopy();
WorkingCopy workingCopy = mm->workingCopy();
QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h" QCOMPARE(workingCopy.size(), 2); // CppModelManager::configurationFileName() and "ui_*.h"
QStringList fileNamesInWorkinCopy; QStringList fileNamesInWorkinCopy;
const WorkingCopy::Table &elements = workingCopy.elements(); const WorkingCopy::Table &elements = workingCopy.elements();
@@ -613,16 +604,16 @@ void ModelManagerTest::testExtraeditorsupportUiFiles()
fileNamesInWorkinCopy.sort(); fileNamesInWorkinCopy.sort();
const QString expectedUiHeaderFileName = _("ui_mainwindow.h"); const QString expectedUiHeaderFileName = _("ui_mainwindow.h");
QCOMPARE(fileNamesInWorkinCopy.at(0), mm->configurationFileName().toString()); QCOMPARE(fileNamesInWorkinCopy.at(0), CppModelManager::configurationFileName().toString());
QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName); QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName);
// Check CppSourceProcessor / includes. // Check CppSourceProcessor / includes.
// The CppSourceProcessor is expected to find the ui_* file in the working copy. // The CppSourceProcessor is expected to find the ui_* file in the working copy.
const FilePath fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp"); const FilePath fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp");
while (!mm->snapshot().document(fileIncludingTheUiFile)) while (!CppModelManager::snapshot().document(fileIncludingTheUiFile))
QCoreApplication::processEvents(); QCoreApplication::processEvents();
const CPlusPlus::Snapshot snapshot = mm->snapshot(); const CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
const Document::Ptr document = snapshot.document(fileIncludingTheUiFile); const Document::Ptr document = snapshot.document(fileIncludingTheUiFile);
QVERIFY(document); QVERIFY(document);
const FilePaths includedFiles = document->includedFiles(); const FilePaths includedFiles = document->includedFiles();
@@ -640,7 +631,6 @@ void ModelManagerTest::testGcIfLastCppeditorClosed()
MyTestDataDir testDataDirectory(_("testdata_guiproject1")); MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
const FilePath file = testDataDirectory.filePath("main.cpp"); const FilePath file = testDataDirectory.filePath("main.cpp");
CppModelManager *mm = CppModelManager::instance();
helper.resetRefreshedSourceFiles(); helper.resetRefreshedSourceFiles();
// Open a file in the editor // Open a file in the editor
@@ -648,8 +638,8 @@ void ModelManagerTest::testGcIfLastCppeditorClosed()
Core::IEditor *editor = Core::EditorManager::openEditor(file); Core::IEditor *editor = Core::EditorManager::openEditor(file);
QVERIFY(editor); QVERIFY(editor);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
QVERIFY(mm->workingCopy().get(file)); QVERIFY(CppModelManager::workingCopy().get(file));
// Wait until the file is refreshed // Wait until the file is refreshed
helper.waitForRefreshedSourceFiles(); helper.waitForRefreshedSourceFiles();
@@ -659,8 +649,8 @@ void ModelManagerTest::testGcIfLastCppeditorClosed()
helper.waitForFinishedGc(); helper.waitForFinishedGc();
// Check: File is removed from the snapshpt // Check: File is removed from the snapshpt
QVERIFY(!mm->workingCopy().get(file)); QVERIFY(!CppModelManager::workingCopy().get(file));
QVERIFY(!mm->snapshot().contains(file)); QVERIFY(!CppModelManager::snapshot().contains(file));
} }
/// Check: Files that are open in the editor are not garbage collected. /// Check: Files that are open in the editor are not garbage collected.
@@ -671,7 +661,6 @@ void ModelManagerTest::testDontGcOpenedFiles()
MyTestDataDir testDataDirectory(_("testdata_guiproject1")); MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
const FilePath file = testDataDirectory.filePath("main.cpp"); const FilePath file = testDataDirectory.filePath("main.cpp");
CppModelManager *mm = CppModelManager::instance();
helper.resetRefreshedSourceFiles(); helper.resetRefreshedSourceFiles();
// Open a file in the editor // Open a file in the editor
@@ -679,24 +668,24 @@ void ModelManagerTest::testDontGcOpenedFiles()
Core::IEditor *editor = Core::EditorManager::openEditor(file); Core::IEditor *editor = Core::EditorManager::openEditor(file);
QVERIFY(editor); QVERIFY(editor);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
// Wait until the file is refreshed and check whether it is in the working copy // Wait until the file is refreshed and check whether it is in the working copy
helper.waitForRefreshedSourceFiles(); helper.waitForRefreshedSourceFiles();
QVERIFY(mm->workingCopy().get(file)); QVERIFY(CppModelManager::workingCopy().get(file));
// Run the garbage collector // Run the garbage collector
mm->GC(); CppModelManager::GC();
// Check: File is still there // Check: File is still there
QVERIFY(mm->workingCopy().get(file)); QVERIFY(CppModelManager::workingCopy().get(file));
QVERIFY(mm->snapshot().contains(file)); QVERIFY(CppModelManager::snapshot().contains(file));
// Close editor // Close editor
Core::EditorManager::closeDocuments({editor->document()}); Core::EditorManager::closeDocuments({editor->document()});
helper.waitForFinishedGc(); helper.waitForFinishedGc();
QVERIFY(mm->snapshot().isEmpty()); QVERIFY(CppModelManager::snapshot().isEmpty());
} }
namespace { namespace {
@@ -735,8 +724,6 @@ void ModelManagerTest::testDefinesPerProject()
const FilePath main2File = testDataDirectory.filePath("main2.cpp"); const FilePath main2File = testDataDirectory.filePath("main2.cpp");
const FilePath header = testDataDirectory.filePath("header.h"); const FilePath header = testDataDirectory.filePath("header.h");
CppModelManager *mm = CppModelManager::instance();
const auto project = helper.createProject(_("test_modelmanager_defines_per_project"), const auto project = helper.createProject(_("test_modelmanager_defines_per_project"),
Utils::FilePath::fromString("blubb.pro")); Utils::FilePath::fromString("blubb.pro"));
@@ -758,7 +745,7 @@ void ModelManagerTest::testDefinesPerProject()
const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2}); const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2});
helper.updateProjectInfo(pi); helper.updateProjectInfo(pi);
QCOMPARE(mm->snapshot().size(), 4); QCOMPARE(CppModelManager::snapshot().size(), 4);
// Open a file in the editor // Open a file in the editor
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
@@ -778,9 +765,9 @@ void ModelManagerTest::testDefinesPerProject()
EditorCloser closer(editor); EditorCloser closer(editor);
QVERIFY(editor); QVERIFY(editor);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
Document::Ptr doc = mm->document(i.filePath); Document::Ptr doc = CppModelManager::document(i.filePath);
QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName); QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName);
} }
} }
@@ -796,8 +783,6 @@ void ModelManagerTest::testPrecompiledHeaders()
const FilePath pch1File = testDataDirectory.filePath("pch1.h"); const FilePath pch1File = testDataDirectory.filePath("pch1.h");
const FilePath pch2File = testDataDirectory.filePath("pch2.h"); const FilePath pch2File = testDataDirectory.filePath("pch2.h");
CppModelManager *mm = CppModelManager::instance();
const auto project = helper.createProject(_("test_modelmanager_defines_per_project_pch"), const auto project = helper.createProject(_("test_modelmanager_defines_per_project_pch"),
Utils::FilePath::fromString("blubb.pro")); Utils::FilePath::fromString("blubb.pro"));
@@ -820,7 +805,7 @@ void ModelManagerTest::testPrecompiledHeaders()
const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2}); const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2});
helper.updateProjectInfo(pi); helper.updateProjectInfo(pi);
QCOMPARE(mm->snapshot().size(), 4); QCOMPARE(CppModelManager::snapshot().size(), 4);
// Open a file in the editor // Open a file in the editor
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
@@ -842,18 +827,17 @@ void ModelManagerTest::testPrecompiledHeaders()
EditorCloser closer(editor); EditorCloser closer(editor);
QVERIFY(editor); QVERIFY(editor);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
auto parser = BuiltinEditorDocumentParser::get(filePath); auto parser = BuiltinEditorDocumentParser::get(filePath);
QVERIFY(parser); QVERIFY(parser);
BaseEditorDocumentParser::Configuration config = parser->configuration(); BaseEditorDocumentParser::Configuration config = parser->configuration();
config.usePrecompiledHeaders = true; config.usePrecompiledHeaders = true;
parser->setConfiguration(config); parser->setConfiguration(config);
parser->update({CppModelManager::instance()->workingCopy(), nullptr, parser->update({CppModelManager::workingCopy(), nullptr,Utils::Language::Cxx, false});
Utils::Language::Cxx, false});
// Check if defines from pch are considered // Check if defines from pch are considered
Document::Ptr document = mm->document(filePath); Document::Ptr document = CppModelManager::document(filePath);
QCOMPARE(nameOfFirstDeclaration(document), firstDeclarationName); QCOMPARE(nameOfFirstDeclaration(document), firstDeclarationName);
// Check if declarations from pch are considered // Check if declarations from pch are considered
@@ -876,8 +860,6 @@ void ModelManagerTest::testDefinesPerEditor()
const FilePath main2File = testDataDirectory.filePath("main2.cpp"); const FilePath main2File = testDataDirectory.filePath("main2.cpp");
const FilePath header = testDataDirectory.filePath("header.h"); const FilePath header = testDataDirectory.filePath("header.h");
CppModelManager *mm = CppModelManager::instance();
const auto project = helper.createProject(_("test_modelmanager_defines_per_editor"), const auto project = helper.createProject(_("test_modelmanager_defines_per_editor"),
Utils::FilePath::fromString("blubb.pro")); Utils::FilePath::fromString("blubb.pro"));
@@ -896,7 +878,7 @@ void ModelManagerTest::testDefinesPerEditor()
const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2}); const auto pi = ProjectInfo::create({project, KitInfo(nullptr), {}, {}}, {part1, part2});
helper.updateProjectInfo(pi); helper.updateProjectInfo(pi);
QCOMPARE(mm->snapshot().size(), 4); QCOMPARE(CppModelManager::snapshot().size(), 4);
// Open a file in the editor // Open a file in the editor
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
@@ -916,17 +898,16 @@ void ModelManagerTest::testDefinesPerEditor()
EditorCloser closer(editor); EditorCloser closer(editor);
QVERIFY(editor); QVERIFY(editor);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
const FilePath filePath = editor->document()->filePath(); const FilePath filePath = editor->document()->filePath();
const auto parser = BaseEditorDocumentParser::get(filePath); const auto parser = BaseEditorDocumentParser::get(filePath);
BaseEditorDocumentParser::Configuration config = parser->configuration(); BaseEditorDocumentParser::Configuration config = parser->configuration();
config.editorDefines = editorDefines.toUtf8(); config.editorDefines = editorDefines.toUtf8();
parser->setConfiguration(config); parser->setConfiguration(config);
parser->update({CppModelManager::instance()->workingCopy(), nullptr, parser->update({CppModelManager::workingCopy(), nullptr, Utils::Language::Cxx, false});
Utils::Language::Cxx, false});
Document::Ptr doc = mm->document(main1File); Document::Ptr doc = CppModelManager::document(main1File);
QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName); QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName);
} }
} }
@@ -986,7 +967,7 @@ void ModelManagerTest::testUpdateEditorsAfterProjectUpdate()
void ModelManagerTest::testRenameIncludes() void ModelManagerTest::testRenameIncludes()
{ {
struct ModelManagerGCHelper { struct ModelManagerGCHelper {
~ModelManagerGCHelper() { CppModelManager::instance()->GC(); } ~ModelManagerGCHelper() { CppModelManager::GC(); }
} GCHelper; } GCHelper;
Q_UNUSED(GCHelper) // do not warn about being unused Q_UNUSED(GCHelper) // do not warn about being unused
@@ -997,7 +978,6 @@ void ModelManagerTest::testRenameIncludes()
const QStringList fileNames = {"foo.h", "foo.cpp", "main.cpp"}; const QStringList fileNames = {"foo.h", "foo.cpp", "main.cpp"};
const FilePath oldHeader = FilePath::fromString(workingDir.filePath("foo.h")); const FilePath oldHeader = FilePath::fromString(workingDir.filePath("foo.h"));
const FilePath newHeader = FilePath::fromString(workingDir.filePath("bar.h")); const FilePath newHeader = FilePath::fromString(workingDir.filePath("bar.h"));
CppModelManager *modelManager = CppModelManager::instance();
const MyTestDataDir testDir(_("testdata_project1")); const MyTestDataDir testDir(_("testdata_project1"));
// Copy test files to a temporary directory // Copy test files to a temporary directory
@@ -1012,9 +992,9 @@ void ModelManagerTest::testRenameIncludes()
} }
// Update the c++ model manager and check for the old includes // Update the c++ model manager and check for the old includes
modelManager->updateSourceFiles(sourceFiles).waitForFinished(); CppModelManager::updateSourceFiles(sourceFiles).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
CPlusPlus::Snapshot snapshot = modelManager->snapshot(); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
for (const FilePath &sourceFile : std::as_const(sourceFiles)) { for (const FilePath &sourceFile : std::as_const(sourceFiles)) {
QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<FilePath>{oldHeader}); QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<FilePath>{oldHeader});
} }
@@ -1025,9 +1005,9 @@ void ModelManagerTest::testRenameIncludes()
Core::HandleIncludeGuards::Yes)); Core::HandleIncludeGuards::Yes));
// Update the c++ model manager again and check for the new includes // Update the c++ model manager again and check for the new includes
modelManager->updateSourceFiles(sourceFiles).waitForFinished(); CppModelManager::updateSourceFiles(sourceFiles).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
snapshot = modelManager->snapshot(); snapshot = CppModelManager::snapshot();
for (const FilePath &sourceFile : std::as_const(sourceFiles)) { for (const FilePath &sourceFile : std::as_const(sourceFiles)) {
QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<FilePath>{newHeader}); QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<FilePath>{newHeader});
} }
@@ -1036,7 +1016,7 @@ void ModelManagerTest::testRenameIncludes()
void ModelManagerTest::testRenameIncludesInEditor() void ModelManagerTest::testRenameIncludesInEditor()
{ {
struct ModelManagerGCHelper { struct ModelManagerGCHelper {
~ModelManagerGCHelper() { CppModelManager::instance()->GC(); } ~ModelManagerGCHelper() { CppModelManager::GC(); }
} GCHelper; } GCHelper;
Q_UNUSED(GCHelper) // do not warn about being unused Q_UNUSED(GCHelper) // do not warn about being unused
@@ -1054,7 +1034,6 @@ void ModelManagerTest::testRenameIncludesInEditor()
const QString headerWithMalformedGuard(workingDir.filePath(_("baz3.h"))); const QString headerWithMalformedGuard(workingDir.filePath(_("baz3.h")));
const QString renamedHeaderWithMalformedGuard(workingDir.filePath(_("foobar5000.h"))); const QString renamedHeaderWithMalformedGuard(workingDir.filePath(_("foobar5000.h")));
const FilePath mainFile = FilePath::fromString(workingDir.filePath("main.cpp")); const FilePath mainFile = FilePath::fromString(workingDir.filePath("main.cpp"));
CppModelManager *modelManager = CppModelManager::instance();
const MyTestDataDir testDir(_("testdata_project1")); const MyTestDataDir testDir(_("testdata_project1"));
ModelManagerTestHelper helper; ModelManagerTestHelper helper;
@@ -1072,9 +1051,9 @@ void ModelManagerTest::testRenameIncludesInEditor()
} }
// Update the c++ model manager and check for the old includes // Update the c++ model manager and check for the old includes
modelManager->updateSourceFiles(sourceFiles).waitForFinished(); CppModelManager::updateSourceFiles(sourceFiles).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
CPlusPlus::Snapshot snapshot = modelManager->snapshot(); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
for (const FilePath &sourceFile : std::as_const(sourceFiles)) { for (const FilePath &sourceFile : std::as_const(sourceFiles)) {
QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QCOMPARE(snapshot.allIncludesForDocument(sourceFile),
QSet<FilePath>{headerWithPragmaOnce}); QSet<FilePath>{headerWithPragmaOnce});
@@ -1087,8 +1066,8 @@ void ModelManagerTest::testRenameIncludesInEditor()
EditorCloser editorCloser(editor); EditorCloser editorCloser(editor);
const QScopeGuard cleanup([] { Core::DocumentManager::saveAllModifiedDocumentsSilently(); }); const QScopeGuard cleanup([] { Core::DocumentManager::saveAllModifiedDocumentsSilently(); });
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(modelManager->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
QVERIFY(modelManager->workingCopy().get(mainFile)); QVERIFY(CppModelManager::workingCopy().get(mainFile));
// Test the renaming of a header file where a pragma once guard is present // Test the renaming of a header file where a pragma once guard is present
QVERIFY(Core::FileUtils::renameFile(headerWithPragmaOnce, QVERIFY(Core::FileUtils::renameFile(headerWithPragmaOnce,
@@ -1150,9 +1129,9 @@ void ModelManagerTest::testRenameIncludesInEditor()
// Update the c++ model manager again and check for the new includes // Update the c++ model manager again and check for the new includes
TestCase::waitForProcessedEditorDocument(mainFile); TestCase::waitForProcessedEditorDocument(mainFile);
modelManager->updateSourceFiles(sourceFiles).waitForFinished(); CppModelManager::updateSourceFiles(sourceFiles).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
snapshot = modelManager->snapshot(); snapshot = CppModelManager::snapshot();
for (const FilePath &sourceFile : std::as_const(sourceFiles)) { for (const FilePath &sourceFile : std::as_const(sourceFiles)) {
QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QCOMPARE(snapshot.allIncludesForDocument(sourceFile),
QSet<FilePath>{renamedHeaderWithPragmaOnce}); QSet<FilePath>{renamedHeaderWithPragmaOnce});
@@ -1170,35 +1149,34 @@ void ModelManagerTest::testDocumentsAndRevisions()
const QSet<FilePath> filesToIndex = {filePath1,filePath2}; const QSet<FilePath> filesToIndex = {filePath1,filePath2};
QVERIFY(TestCase::parseFiles(filesToIndex)); QVERIFY(TestCase::parseFiles(filesToIndex));
CppModelManager *modelManager = CppModelManager::instance(); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath1), 1U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 1U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 1U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 1U);
// Open editor for file 1 // Open editor for file 1
TextEditor::BaseTextEditor *editor1; TextEditor::BaseTextEditor *editor1;
QVERIFY(helper.openCppEditor(filePath1, &editor1)); QVERIFY(helper.openCppEditor(filePath1, &editor1));
helper.closeEditorAtEndOfTestCase(editor1); helper.closeEditorAtEndOfTestCase(editor1);
QVERIFY(TestCase::waitForProcessedEditorDocument(filePath1)); QVERIFY(TestCase::waitForProcessedEditorDocument(filePath1));
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 2U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath1), 2U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 1U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 1U);
// Index again // Index again
QVERIFY(TestCase::parseFiles(filesToIndex)); QVERIFY(TestCase::parseFiles(filesToIndex));
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 3U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath1), 3U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 2U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 2U);
// Open editor for file 2 // Open editor for file 2
TextEditor::BaseTextEditor *editor2; TextEditor::BaseTextEditor *editor2;
QVERIFY(helper.openCppEditor(filePath2, &editor2)); QVERIFY(helper.openCppEditor(filePath2, &editor2));
helper.closeEditorAtEndOfTestCase(editor2); helper.closeEditorAtEndOfTestCase(editor2);
QVERIFY(TestCase::waitForProcessedEditorDocument(filePath2)); QVERIFY(TestCase::waitForProcessedEditorDocument(filePath2));
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 3U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath1), 3U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 3U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 3U);
// Index again // Index again
QVERIFY(TestCase::parseFiles(filesToIndex)); QVERIFY(TestCase::parseFiles(filesToIndex));
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 4U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath1), 4U);
VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 4U); VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 4U);
} }
} // CppEditor::Internal } // CppEditor::Internal

View File

@@ -81,8 +81,7 @@ void CppProjectUpdater::update(const ProjectUpdateInfo &projectUpdateInfo,
} }
} }
GeneratedCodeModelSupport::update(extraCompilers); GeneratedCodeModelSupport::update(extraCompilers);
auto updateFuture = CppModelManager::instance()->updateProjectInfo(storage->projectInfo, auto updateFuture = CppModelManager::updateProjectInfo(storage->projectInfo, compilerFiles);
compilerFiles);
m_futureSynchronizer.addFuture(updateFuture); m_futureSynchronizer.addFuture(updateFuture);
m_taskTree.release()->deleteLater(); m_taskTree.release()->deleteLater();
}; };

View File

@@ -95,8 +95,8 @@ BaseQuickFixTestCase::BaseQuickFixTestCase(const QList<TestDocumentPtr> &testDoc
// Set appropriate include paths // Set appropriate include paths
if (!headerPaths.isEmpty()) { if (!headerPaths.isEmpty()) {
m_restoreHeaderPaths = true; m_restoreHeaderPaths = true;
m_headerPathsToRestore = m_modelManager->headerPaths(); m_headerPathsToRestore = CppModelManager::headerPaths();
m_modelManager->setHeaderPaths(headerPaths); CppModelManager::setHeaderPaths(headerPaths);
} }
// Update Code Model // Update Code Model
@@ -154,7 +154,7 @@ BaseQuickFixTestCase::~BaseQuickFixTestCase()
// Restore include paths // Restore include paths
if (m_restoreHeaderPaths) if (m_restoreHeaderPaths)
m_modelManager->setHeaderPaths(m_headerPathsToRestore); CppModelManager::setHeaderPaths(m_headerPathsToRestore);
// Remove created files from file system // Remove created files from file system
for (const TestDocumentPtr &testDocument : std::as_const(m_testDocuments)) for (const TestDocumentPtr &testDocument : std::as_const(m_testDocuments))

View File

@@ -51,7 +51,7 @@ CppQuickFixInterface::CppQuickFixInterface(CppEditorWidget *editor, AssistReason
: AssistInterface(editor->textCursor(), editor->textDocument()->filePath(), reason) : AssistInterface(editor->textCursor(), editor->textDocument()->filePath(), reason)
, m_editor(editor) , m_editor(editor)
, m_semanticInfo(editor->semanticInfo()) , m_semanticInfo(editor->semanticInfo())
, m_snapshot(CppModelManager::instance()->snapshot()) , m_snapshot(CppModelManager::snapshot())
, m_currentFile(CppRefactoringChanges::file(editor, m_semanticInfo.doc)) , m_currentFile(CppRefactoringChanges::file(editor, m_semanticInfo.doc))
, m_context(m_semanticInfo.doc, m_snapshot) , m_context(m_semanticInfo.doc, m_snapshot)
{ {

View File

@@ -1899,10 +1899,9 @@ ProjectExplorer::HeaderPaths relevantHeaderPaths(const QString &filePath)
{ {
ProjectExplorer::HeaderPaths headerPaths; ProjectExplorer::HeaderPaths headerPaths;
CppModelManager *modelManager = CppModelManager::instance(); const QList<ProjectPart::ConstPtr> projectParts = CppModelManager::projectPart(filePath);
const QList<ProjectPart::ConstPtr> projectParts = modelManager->projectPart(filePath);
if (projectParts.isEmpty()) { // Not part of any project, better use all include paths than none if (projectParts.isEmpty()) { // Not part of any project, better use all include paths than none
headerPaths += modelManager->headerPaths(); headerPaths += CppModelManager::headerPaths();
} else { } else {
for (const ProjectPart::ConstPtr &part : projectParts) for (const ProjectPart::ConstPtr &part : projectParts)
headerPaths += part->headerPaths; headerPaths += part->headerPaths;
@@ -1997,7 +1996,7 @@ QList<IndexItem::Ptr> matchName(const Name *name, QString *className)
QString simpleName; QString simpleName;
QList<IndexItem::Ptr> matches; QList<IndexItem::Ptr> matches;
CppLocatorData *locatorData = CppModelManager::instance()->locatorData(); CppLocatorData *locatorData = CppModelManager::locatorData();
const Overview oo; const Overview oo;
if (const QualifiedNameId *qualifiedName = name->asQualifiedNameId()) { if (const QualifiedNameId *qualifiedName = name->asQualifiedNameId()) {
const Name *name = qualifiedName->name(); const Name *name = qualifiedName->name();

View File

@@ -217,8 +217,7 @@ void CppRefactoringFile::fileChanged()
CppRefactoringChangesData::CppRefactoringChangesData(const Snapshot &snapshot) CppRefactoringChangesData::CppRefactoringChangesData(const Snapshot &snapshot)
: m_snapshot(snapshot) : m_snapshot(snapshot)
, m_modelManager(CppModelManager::instance()) , m_workingCopy(CppModelManager::workingCopy())
, m_workingCopy(m_modelManager->workingCopy())
{} {}
void CppRefactoringChangesData::indentSelection(const QTextCursor &selection, void CppRefactoringChangesData::indentSelection(const QTextCursor &selection,
@@ -249,7 +248,7 @@ void CppRefactoringChangesData::reindentSelection(const QTextCursor &selection,
void CppRefactoringChangesData::fileChanged(const FilePath &filePath) void CppRefactoringChangesData::fileChanged(const FilePath &filePath)
{ {
m_modelManager->updateSourceFiles({filePath}); CppModelManager::updateSourceFiles({filePath});
} }
} // CppEditor } // CppEditor

View File

@@ -76,7 +76,6 @@ public:
void fileChanged(const Utils::FilePath &filePath) override; void fileChanged(const Utils::FilePath &filePath) override;
CPlusPlus::Snapshot m_snapshot; CPlusPlus::Snapshot m_snapshot;
CppModelManager *m_modelManager;
WorkingCopy m_workingCopy; WorkingCopy m_workingCopy;
}; };

View File

@@ -178,7 +178,7 @@ void SemanticInfoUpdater::updateDetached(const SemanticInfo::Source &source)
return; return;
} }
d->m_future = Utils::asyncRun(CppModelManager::instance()->sharedThreadPool(), d->m_future = Utils::asyncRun(CppModelManager::sharedThreadPool(),
&SemanticInfoUpdaterPrivate::update_helper, d.data(), source); &SemanticInfoUpdaterPrivate::update_helper, d.data(), source);
} }

View File

@@ -34,7 +34,6 @@ class SourcePreprocessor
{ {
public: public:
SourcePreprocessor() SourcePreprocessor()
: m_cmm(CppModelManager::instance())
{ {
cleanUp(); cleanUp();
} }
@@ -47,7 +46,7 @@ public:
TestIncludePaths::directoryOfTestFile())}); TestIncludePaths::directoryOfTestFile())});
sourceProcessor->run(filePath); sourceProcessor->run(filePath);
Document::Ptr document = m_cmm->document(filePath); Document::Ptr document = CppModelManager::document(filePath);
return document; return document;
} }
@@ -59,12 +58,9 @@ public:
private: private:
void cleanUp() void cleanUp()
{ {
m_cmm->GC(); CppModelManager::GC();
QVERIFY(m_cmm->snapshot().isEmpty()); QVERIFY(CppModelManager::snapshot().isEmpty());
} }
private:
CppModelManager *m_cmm;
}; };
/// Check: Resolved and unresolved includes are properly tracked. /// Check: Resolved and unresolved includes are properly tracked.

View File

@@ -151,8 +151,8 @@ bool CppToolsJsExtension::hasQObjectParent(const QString &klassName) const
const IndexItem::Ptr item = candidates.first(); const IndexItem::Ptr item = candidates.first();
// Find class in AST. // Find class in AST.
const CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot snapshot = CppModelManager::snapshot();
const WorkingCopy workingCopy = CppModelManager::instance()->workingCopy(); const WorkingCopy workingCopy = CppModelManager::workingCopy();
std::optional<QByteArray> source = workingCopy.source(item->filePath()); std::optional<QByteArray> source = workingCopy.source(item->filePath());
if (!source) { if (!source) {
const Utils::expected_str<QByteArray> contents = item->filePath().fileContents(); const Utils::expected_str<QByteArray> contents = item->filePath().fileContents();

View File

@@ -149,15 +149,15 @@ VerifyCleanCppModelManager::~VerifyCleanCppModelManager() {
bool VerifyCleanCppModelManager::isClean(bool testOnlyForCleanedProjects) bool VerifyCleanCppModelManager::isClean(bool testOnlyForCleanedProjects)
{ {
CppModelManager *mm = CppModelManager::instance(); RETURN_FALSE_IF_NOT(CppModelManager::projectInfos().isEmpty());
RETURN_FALSE_IF_NOT(mm->projectInfos().isEmpty()); RETURN_FALSE_IF_NOT(CppModelManager::headerPaths().isEmpty());
RETURN_FALSE_IF_NOT(mm->headerPaths().isEmpty()); RETURN_FALSE_IF_NOT(CppModelManager::definedMacros().isEmpty());
RETURN_FALSE_IF_NOT(mm->definedMacros().isEmpty()); RETURN_FALSE_IF_NOT(CppModelManager::projectFiles().isEmpty());
RETURN_FALSE_IF_NOT(mm->projectFiles().isEmpty());
if (!testOnlyForCleanedProjects) { if (!testOnlyForCleanedProjects) {
RETURN_FALSE_IF_NOT(mm->snapshot().isEmpty()); RETURN_FALSE_IF_NOT(CppModelManager::snapshot().isEmpty());
RETURN_FALSE_IF_NOT(mm->workingCopy().size() == 1); RETURN_FALSE_IF_NOT(CppModelManager::workingCopy().size() == 1);
RETURN_FALSE_IF_NOT(mm->workingCopy().get(mm->configurationFileName())); RETURN_FALSE_IF_NOT(CppModelManager::workingCopy()
.get(CppModelManager::configurationFileName()));
} }
return true; return true;
} }
@@ -170,9 +170,9 @@ namespace CppEditor::Tests {
static bool closeEditorsWithoutGarbageCollectorInvocation(const QList<Core::IEditor *> &editors) static bool closeEditorsWithoutGarbageCollectorInvocation(const QList<Core::IEditor *> &editors)
{ {
CppModelManager::instance()->enableGarbageCollector(false); CppModelManager::enableGarbageCollector(false);
const bool closeEditorsSucceeded = Core::EditorManager::closeEditors(editors, false); const bool closeEditorsSucceeded = Core::EditorManager::closeEditors(editors, false);
CppModelManager::instance()->enableGarbageCollector(true); CppModelManager::enableGarbageCollector(true);
return closeEditorsSucceeded; return closeEditorsSucceeded;
} }
@@ -188,8 +188,7 @@ static bool snapshotContains(const CPlusPlus::Snapshot &snapshot, const QSet<Fil
} }
TestCase::TestCase(bool runGarbageCollector) TestCase::TestCase(bool runGarbageCollector)
: m_modelManager(CppModelManager::instance()) : m_succeededSoFar(false)
, m_succeededSoFar(false)
, m_runGarbageCollector(runGarbageCollector) , m_runGarbageCollector(runGarbageCollector)
{ {
if (m_runGarbageCollector) if (m_runGarbageCollector)
@@ -239,12 +238,12 @@ bool TestCase::openCppEditor(const FilePath &filePath, TextEditor::BaseTextEdito
CPlusPlus::Snapshot TestCase::globalSnapshot() CPlusPlus::Snapshot TestCase::globalSnapshot()
{ {
return CppModelManager::instance()->snapshot(); return CppModelManager::snapshot();
} }
bool TestCase::garbageCollectGlobalSnapshot() bool TestCase::garbageCollectGlobalSnapshot()
{ {
CppModelManager::instance()->GC(); CppModelManager::GC();
return globalSnapshot().isEmpty(); return globalSnapshot().isEmpty();
} }
@@ -269,7 +268,7 @@ static bool waitForProcessedEditorDocument_internal(CppEditorDocumentHandle *edi
bool TestCase::waitForProcessedEditorDocument(const FilePath &filePath, int timeOutInMs) bool TestCase::waitForProcessedEditorDocument(const FilePath &filePath, int timeOutInMs)
{ {
auto *editorDocument = CppModelManager::instance()->cppEditorDocument(filePath); auto *editorDocument = CppModelManager::cppEditorDocument(filePath);
return waitForProcessedEditorDocument_internal(editorDocument, timeOutInMs); return waitForProcessedEditorDocument_internal(editorDocument, timeOutInMs);
} }
@@ -282,7 +281,7 @@ CPlusPlus::Document::Ptr TestCase::waitForRehighlightedSemanticDocument(CppEdito
bool TestCase::parseFiles(const QSet<FilePath> &filePaths) bool TestCase::parseFiles(const QSet<FilePath> &filePaths)
{ {
CppModelManager::instance()->updateSourceFiles(filePaths).waitForFinished(); CppModelManager::updateSourceFiles(filePaths).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
const CPlusPlus::Snapshot snapshot = globalSnapshot(); const CPlusPlus::Snapshot snapshot = globalSnapshot();
if (snapshot.isEmpty()) { if (snapshot.isEmpty()) {
@@ -349,7 +348,7 @@ bool TestCase::waitUntilProjectIsFullyOpened(Project *project, int timeOutInMs)
[project]() { [project]() {
return ProjectManager::startupBuildSystem() return ProjectManager::startupBuildSystem()
&& !ProjectManager::startupBuildSystem()->isParsing() && !ProjectManager::startupBuildSystem()->isParsing()
&& CppModelManager::instance()->projectInfo(project); && CppModelManager::projectInfo(project);
}, },
timeOutInMs); timeOutInMs);
} }
@@ -405,7 +404,7 @@ ProjectInfo::ConstPtr ProjectOpenerAndCloser::open(const FilePath &projectFile,
if (TestCase::waitUntilProjectIsFullyOpened(project)) { if (TestCase::waitUntilProjectIsFullyOpened(project)) {
m_openProjects.append(project); m_openProjects.append(project);
return CppModelManager::instance()->projectInfo(project); return CppModelManager::projectInfo(project);
} }
return {}; return {};

View File

@@ -32,7 +32,6 @@ class IAssistProposal;
namespace CppEditor { namespace CppEditor {
class CppEditorWidget; class CppEditorWidget;
class CppModelManager;
namespace Internal::Tests { namespace Internal::Tests {
@@ -152,7 +151,6 @@ public:
static bool writeFile(const Utils::FilePath &filePath, const QByteArray &contents); static bool writeFile(const Utils::FilePath &filePath, const QByteArray &contents);
protected: protected:
CppModelManager *m_modelManager;
bool m_succeededSoFar; bool m_succeededSoFar;
private: private:

View File

@@ -81,7 +81,7 @@ UseSelectionsTestCase::UseSelectionsTestCase(CppTestDocument &testFile,
bool hasTimedOut; bool hasTimedOut;
const SelectionList selections = waitForUseSelections(&hasTimedOut); const SelectionList selections = waitForUseSelections(&hasTimedOut);
const bool clangCodeModel = CppModelManager::instance()->isClangCodeModelActive(); const bool clangCodeModel = CppModelManager::isClangCodeModelActive();
if (clangCodeModel) { if (clangCodeModel) {
QEXPECT_FAIL("local use as macro argument - argument eaten", "fails with CCM, find out why", QEXPECT_FAIL("local use as macro argument - argument eaten", "fails with CCM, find out why",
Abort); Abort);

View File

@@ -110,7 +110,7 @@ static bool waitUntilAProjectIsLoaded(int timeOutInMs = 30000)
timer.start(); timer.start();
while (timer.elapsed() < timeOutInMs) { while (timer.elapsed() < timeOutInMs) {
if (!CppModelManager::instance()->projectInfos().isEmpty()) if (!CppModelManager::projectInfos().isEmpty())
return true; return true;
QCoreApplication::processEvents(); QCoreApplication::processEvents();
@@ -132,7 +132,7 @@ TestActionsTestCase::TestActionsTestCase(const Actions &tokenActions, const Acti
// Collect files to process // Collect files to process
FilePaths filesToOpen; FilePaths filesToOpen;
QList<QPointer<ProjectExplorer::Project> > projects; QList<QPointer<ProjectExplorer::Project> > projects;
const QList<ProjectInfo::ConstPtr> projectInfos = m_modelManager->projectInfos(); const QList<ProjectInfo::ConstPtr> projectInfos = CppModelManager::projectInfos();
for (const ProjectInfo::ConstPtr &info : projectInfos) { for (const ProjectInfo::ConstPtr &info : projectInfos) {
qDebug() << "Project" << info->projectFilePath().toUserOutput() << "- files to process:" qDebug() << "Project" << info->projectFilePath().toUserOutput() << "- files to process:"
@@ -162,8 +162,8 @@ TestActionsTestCase::TestActionsTestCase(const Actions &tokenActions, const Acti
QVERIFY(openCppEditor(filePath, &editor, &editorWidget)); QVERIFY(openCppEditor(filePath, &editor, &editorWidget));
QCOMPARE(DocumentModel::openedDocuments().size(), 1); QCOMPARE(DocumentModel::openedDocuments().size(), 1);
QVERIFY(m_modelManager->isCppEditor(editor)); QVERIFY(CppModelManager::isCppEditor(editor));
QVERIFY(m_modelManager->workingCopy().get(filePath)); QVERIFY(CppModelManager::workingCopy().get(filePath));
// Rehighlight // Rehighlight
waitForRehighlightedSemanticDocument(editorWidget); waitForRehighlightedSemanticDocument(editorWidget);

View File

@@ -331,7 +331,7 @@ F2TestCase::F2TestCase(CppEditorAction action,
switch (action) { switch (action) {
case FollowSymbolUnderCursorAction: { case FollowSymbolUnderCursorAction: {
CppEditorWidget *widget = initialTestFile->m_editorWidget; CppEditorWidget *widget = initialTestFile->m_editorWidget;
if (CppModelManager::instance()->isClangCodeModelActive()) { if (CppModelManager::isClangCodeModelActive()) {
if (curTestName == "testFollowSymbolQTCREATORBUG7903") if (curTestName == "testFollowSymbolQTCREATORBUG7903")
QSKIP((curTestName + " is not supported by Clang FollowSymbol").toLatin1()); QSKIP((curTestName + " is not supported by Clang FollowSymbol").toLatin1());
widget->enableTestMode(); widget->enableTestMode();

View File

@@ -49,10 +49,10 @@ private:
QSet<QObject *> m_cache; QSet<QObject *> m_cache;
}; };
GeneratedCodeModelSupport::GeneratedCodeModelSupport(CppModelManager *modelmanager, GeneratedCodeModelSupport::GeneratedCodeModelSupport(ExtraCompiler *generator,
ExtraCompiler *generator,
const FilePath &generatedFile) : const FilePath &generatedFile) :
AbstractEditorSupport(modelmanager, generator), m_generatedFilePath(generatedFile), AbstractEditorSupport(generator),
m_generatedFilePath(generatedFile),
m_generator(generator) m_generator(generator)
{ {
QLoggingCategory log("qtc.cppeditor.generatedcodemodelsupport", QtWarningMsg); QLoggingCategory log("qtc.cppeditor.generatedcodemodelsupport", QtWarningMsg);
@@ -66,8 +66,7 @@ GeneratedCodeModelSupport::GeneratedCodeModelSupport(CppModelManager *modelmanag
GeneratedCodeModelSupport::~GeneratedCodeModelSupport() GeneratedCodeModelSupport::~GeneratedCodeModelSupport()
{ {
CppModelManager::instance()->emitAbstractEditorSupportRemoved( CppModelManager::emitAbstractEditorSupportRemoved(m_generatedFilePath.toString());
m_generatedFilePath.toString());
QLoggingCategory log("qtc.cppeditor.generatedcodemodelsupport", QtWarningMsg); QLoggingCategory log("qtc.cppeditor.generatedcodemodelsupport", QtWarningMsg);
qCDebug(log) << "dtor ~generatedcodemodelsupport for" << m_generatedFilePath; qCDebug(log) << "dtor ~generatedcodemodelsupport for" << m_generatedFilePath;
} }
@@ -99,15 +98,13 @@ void GeneratedCodeModelSupport::update(const QList<ExtraCompiler *> &generators)
{ {
static QObjectCache extraCompilerCache; static QObjectCache extraCompilerCache;
CppModelManager * const mm = CppModelManager::instance();
for (ExtraCompiler *generator : generators) { for (ExtraCompiler *generator : generators) {
if (extraCompilerCache.contains(generator)) if (extraCompilerCache.contains(generator))
continue; continue;
extraCompilerCache.insert(generator); extraCompilerCache.insert(generator);
generator->forEachTarget([mm, generator](const FilePath &generatedFile) { generator->forEachTarget([generator](const FilePath &generatedFile) {
new GeneratedCodeModelSupport(mm, generator, generatedFile); new GeneratedCodeModelSupport(generator, generatedFile);
}); });
} }
} }

View File

@@ -15,8 +15,7 @@ class CPPEDITOR_EXPORT GeneratedCodeModelSupport : public AbstractEditorSupport
Q_OBJECT Q_OBJECT
public: public:
GeneratedCodeModelSupport(CppModelManager *modelmanager, GeneratedCodeModelSupport(ProjectExplorer::ExtraCompiler *generator,
ProjectExplorer::ExtraCompiler *generator,
const Utils::FilePath &generatedFile); const Utils::FilePath &generatedFile);
~GeneratedCodeModelSupport() override; ~GeneratedCodeModelSupport() override;

View File

@@ -511,14 +511,13 @@ namespace Internal {
static QList<Include> includesForSource(const FilePath &filePath) static QList<Include> includesForSource(const FilePath &filePath)
{ {
CppModelManager *cmm = CppModelManager::instance(); CppModelManager::GC();
cmm->GC();
QScopedPointer<CppSourceProcessor> sourceProcessor(CppModelManager::createSourceProcessor()); QScopedPointer<CppSourceProcessor> sourceProcessor(CppModelManager::createSourceProcessor());
sourceProcessor->setHeaderPaths({ProjectExplorer::HeaderPath::makeUser( sourceProcessor->setHeaderPaths({ProjectExplorer::HeaderPath::makeUser(
TestIncludePaths::globalIncludePath())}); TestIncludePaths::globalIncludePath())});
sourceProcessor->run(filePath); sourceProcessor->run(filePath);
Document::Ptr document = cmm->document(filePath); Document::Ptr document = CppModelManager::document(filePath);
return document->resolvedIncludes(); return document->resolvedIncludes();
} }

View File

@@ -81,7 +81,7 @@ QSet<FilePath> ModelManagerTestHelper::updateProjectInfo(
const ProjectInfo::ConstPtr &projectInfo) const ProjectInfo::ConstPtr &projectInfo)
{ {
resetRefreshedSourceFiles(); resetRefreshedSourceFiles();
CppModelManager::instance()->updateProjectInfo(projectInfo).waitForFinished(); CppModelManager::updateProjectInfo(projectInfo).waitForFinished();
QCoreApplication::processEvents(); QCoreApplication::processEvents();
return waitForRefreshedSourceFiles(); return waitForRefreshedSourceFiles();
} }

View File

@@ -476,7 +476,7 @@ void SymbolFinder::checkCacheConsistency(const FilePath &referenceFile, const Sn
const QString projectPartIdForFile(const FilePath &filePath) const QString projectPartIdForFile(const FilePath &filePath)
{ {
const QList<ProjectPart::ConstPtr> parts = CppModelManager::instance()->projectPart(filePath); const QList<ProjectPart::ConstPtr> parts = CppModelManager::projectPart(filePath);
if (!parts.isEmpty()) if (!parts.isEmpty())
return parts.first()->id(); return parts.first()->id();
return QString(); return QString();

View File

@@ -35,9 +35,8 @@ const char SETTINGS_GROUP[] = "CppSymbols";
const char SETTINGS_SYMBOLTYPES[] = "SymbolsToSearchFor"; const char SETTINGS_SYMBOLTYPES[] = "SymbolsToSearchFor";
const char SETTINGS_SEARCHSCOPE[] = "SearchScope"; const char SETTINGS_SEARCHSCOPE[] = "SearchScope";
SymbolsFindFilter::SymbolsFindFilter(CppModelManager *manager) SymbolsFindFilter::SymbolsFindFilter()
: m_manager(manager), : m_enabled(true),
m_enabled(true),
m_symbolsToSearch(SearchSymbols::AllTypes), m_symbolsToSearch(SearchSymbols::AllTypes),
m_scope(SymbolSearcher::SearchProjectsOnly) m_scope(SymbolSearcher::SearchProjectsOnly)
{ {
@@ -121,7 +120,7 @@ void SymbolsFindFilter::startSearch(SearchResult *search)
SymbolSearcher *symbolSearcher = new SymbolSearcher(parameters, projectFileNames); SymbolSearcher *symbolSearcher = new SymbolSearcher(parameters, projectFileNames);
connect(watcher, &QFutureWatcherBase::finished, connect(watcher, &QFutureWatcherBase::finished,
symbolSearcher, &QObject::deleteLater); symbolSearcher, &QObject::deleteLater);
watcher->setFuture(Utils::asyncRun(m_manager->sharedThreadPool(), watcher->setFuture(Utils::asyncRun(CppModelManager::sharedThreadPool(),
&SymbolSearcher::runSearch, symbolSearcher)); &SymbolSearcher::runSearch, symbolSearcher));
FutureProgress *progress = ProgressManager::addTask(watcher->future(), Tr::tr("Searching for Symbol"), FutureProgress *progress = ProgressManager::addTask(watcher->future(), Tr::tr("Searching for Symbol"),
Core::Constants::TASK_SEARCH); Core::Constants::TASK_SEARCH);

View File

@@ -18,8 +18,6 @@ namespace Core { class SearchResult; }
namespace Utils { class SearchResultItem; } namespace Utils { class SearchResultItem; }
namespace CppEditor { namespace CppEditor {
class CppModelManager;
namespace Internal { namespace Internal {
class SymbolsFindFilter : public Core::IFindFilter class SymbolsFindFilter : public Core::IFindFilter
@@ -30,7 +28,7 @@ public:
using SearchScope = SymbolSearcher::SearchScope; using SearchScope = SymbolSearcher::SearchScope;
public: public:
explicit SymbolsFindFilter(CppModelManager *manager); SymbolsFindFilter();
QString id() const override; QString id() const override;
QString displayName() const override; QString displayName() const override;
@@ -65,7 +63,6 @@ private:
QString toolTip(Utils::FindFlags findFlags) const; QString toolTip(Utils::FindFlags findFlags) const;
void startSearch(Core::SearchResult *search); void startSearch(Core::SearchResult *search);
CppModelManager *m_manager;
bool m_enabled; bool m_enabled;
QMap<QFutureWatcher<Utils::SearchResultItem> *, QPointer<Core::SearchResult> > m_watchers; QMap<QFutureWatcher<Utils::SearchResultItem> *, QPointer<Core::SearchResult> > m_watchers;
QPointer<Core::SearchResult> m_currentSearch; QPointer<Core::SearchResult> m_currentSearch;

View File

@@ -44,7 +44,7 @@ CPlusPlus::Symbol *AnalyzerUtils::findSymbolUnderCursor()
const int pos = tc.position(); const int pos = tc.position();
widget->convertPosition(pos, &line, &column); widget->convertPosition(pos, &line, &column);
const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot &snapshot = CppEditor::CppModelManager::snapshot();
CPlusPlus::Document::Ptr doc = snapshot.document(widget->textDocument()->filePath()); CPlusPlus::Document::Ptr doc = snapshot.document(widget->textDocument()->filePath());
QTC_ASSERT(doc, return nullptr); QTC_ASSERT(doc, return nullptr);

View File

@@ -189,7 +189,7 @@ CdbEngine::CdbEngine() :
this, &CdbEngine::updateLocals); this, &CdbEngine::updateLocals);
if (s->useCodeModel.value()) if (s->useCodeModel.value())
m_codeModelSnapshot = CppEditor::CppModelManager::instance()->snapshot(); m_codeModelSnapshot = CppEditor::CppModelManager::snapshot();
} }
void CdbEngine::init() void CdbEngine::init()
@@ -2500,7 +2500,7 @@ void CdbEngine::insertBreakpoint(const Breakpoint &bp)
BreakpointParameters response = parameters; BreakpointParameters response = parameters;
const QString responseId = breakPointCdbId(bp); const QString responseId = breakPointCdbId(bp);
QScopedPointer<BreakpointCorrectionContext> lineCorrection( QScopedPointer<BreakpointCorrectionContext> lineCorrection(
new BreakpointCorrectionContext(m_codeModelSnapshot, CppEditor::CppModelManager::instance()->workingCopy())); new BreakpointCorrectionContext(m_codeModelSnapshot, CppEditor::CppModelManager::workingCopy()));
if (!m_autoBreakPointCorrection if (!m_autoBreakPointCorrection
&& parameters.type == BreakpointByFileAndLine && parameters.type == BreakpointByFileAndLine
&& debuggerSettings()->cdbBreakPointCorrection.value()) { && debuggerSettings()->cdbBreakPointCorrection.value()) {

View File

@@ -154,7 +154,7 @@ bool DebuggerRunConfigurationAspect::useCppDebugger() const
static bool projectHasQmlDefines(ProjectExplorer::Project *project) static bool projectHasQmlDefines(ProjectExplorer::Project *project)
{ {
auto projectInfo = CppEditor::CppModelManager::instance()->projectInfo(project); auto projectInfo = CppEditor::CppModelManager::projectInfo(project);
if (!projectInfo) // we may have e.g. a Python project if (!projectInfo) // we may have e.g. a Python project
return false; return false;
return Utils::anyOf(projectInfo->projectParts(), return Utils::anyOf(projectInfo->projectParts(),

View File

@@ -223,7 +223,7 @@ QStringList getUninitializedVariables(const Snapshot &snapshot,
QString cppFunctionAt(const FilePath &filePath, int line, int column) QString cppFunctionAt(const FilePath &filePath, int line, int column)
{ {
const Snapshot snapshot = CppModelManager::instance()->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
if (const Document::Ptr document = snapshot.document(filePath)) if (const Document::Ptr document = snapshot.document(filePath))
return document->functionAt(line, column); return document->functionAt(line, column);
@@ -240,7 +240,7 @@ QString cppExpressionAt(TextEditorWidget *editorWidget, int pos,
function->clear(); function->clear();
const FilePath filePath = editorWidget->textDocument()->filePath(); const FilePath filePath = editorWidget->textDocument()->filePath();
const Snapshot snapshot = CppModelManager::instance()->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
const Document::Ptr document = snapshot.document(filePath); const Document::Ptr document = snapshot.document(filePath);
QTextCursor tc = editorWidget->textCursor(); QTextCursor tc = editorWidget->textCursor();
QString expr; QString expr;
@@ -376,7 +376,7 @@ static void setValueAnnotationsHelper(BaseTextEditor *textEditor,
TextEditorWidget *widget = textEditor->editorWidget(); TextEditorWidget *widget = textEditor->editorWidget();
TextDocument *textDocument = widget->textDocument(); TextDocument *textDocument = widget->textDocument();
const FilePath filePath = loc.fileName(); const FilePath filePath = loc.fileName();
const Snapshot snapshot = CppModelManager::instance()->snapshot(); const Snapshot snapshot = CppModelManager::snapshot();
const Document::Ptr cppDocument = snapshot.document(filePath); const Document::Ptr cppDocument = snapshot.document(filePath);
if (!cppDocument) // For non-C++ documents. if (!cppDocument) // For non-C++ documents.
return; return;

View File

@@ -105,7 +105,7 @@ bool navigateToSlot(const QString &uiFileName,
*errorMessage = Tr::tr("The generated header of the form \"%1\" could not be found.\nRebuilding the project might help.").arg(uiFileName); *errorMessage = Tr::tr("The generated header of the form \"%1\" could not be found.\nRebuilding the project might help.").arg(uiFileName);
return false; return false;
} }
const CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::instance()->snapshot(); const CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::snapshot();
const DocumentPtr generatedHeaderDoc = snapshot.document(generatedHeaderFile); const DocumentPtr generatedHeaderDoc = snapshot.document(generatedHeaderFile);
if (!generatedHeaderDoc) { if (!generatedHeaderDoc) {
*errorMessage = Tr::tr("The generated header \"%1\" could not be found in the code model.\nRebuilding the project might help.").arg(generatedHeaderFile.toUserOutput()); *errorMessage = Tr::tr("The generated header \"%1\" could not be found in the code model.\nRebuilding the project might help.").arg(generatedHeaderFile.toUserOutput());

View File

@@ -499,7 +499,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
const QString uicedName = "ui_" + fi.completeBaseName() + ".h"; const QString uicedName = "ui_" + fi.completeBaseName() + ".h";
// Retrieve code model snapshot restricted to project of ui file or the working copy. // Retrieve code model snapshot restricted to project of ui file or the working copy.
Snapshot docTable = CppEditor::CppModelManager::instance()->snapshot(); Snapshot docTable = CppEditor::CppModelManager::snapshot();
Snapshot newDocTable; Snapshot newDocTable;
const Project *uiProject = ProjectManager::projectForFile(currentUiFile); const Project *uiProject = ProjectManager::projectForFile(currentUiFile);
if (uiProject) { if (uiProject) {
@@ -511,7 +511,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
} else { } else {
const FilePath configFileName = CppEditor::CppModelManager::configurationFileName(); const FilePath configFileName = CppEditor::CppModelManager::configurationFileName();
const CppEditor::WorkingCopy::Table elements = const CppEditor::WorkingCopy::Table elements =
CppEditor::CppModelManager::instance()->workingCopy().elements(); CppEditor::CppModelManager::workingCopy().elements();
for (auto it = elements.cbegin(), end = elements.cend(); it != end; ++it) { for (auto it = elements.cbegin(), end = elements.cend(); it != end; ++it) {
const Utils::FilePath &fileName = it.key(); const Utils::FilePath &fileName = it.key();
if (fileName != configFileName) if (fileName != configFileName)
@@ -578,7 +578,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
FilePath declFilePath; FilePath declFilePath;
if (!fun) { if (!fun) {
// add function declaration to cl // add function declaration to cl
CppEditor::WorkingCopy workingCopy = CppEditor::CppModelManager::instance()->workingCopy(); CppEditor::WorkingCopy workingCopy = CppEditor::CppModelManager::workingCopy();
declFilePath = declDoc->filePath(); declFilePath = declDoc->filePath();
getParsedDocument(declFilePath, workingCopy, docTable); getParsedDocument(declFilePath, workingCopy, docTable);
addDeclaration(docTable, declFilePath, cl, functionNameWithParameterNames); addDeclaration(docTable, declFilePath, cl, functionNameWithParameterNames);
@@ -587,8 +587,8 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
QList<Utils::FilePath> filePaths; QList<Utils::FilePath> filePaths;
for (auto it = docTable.begin(); it != docTable.end(); ++it) for (auto it = docTable.begin(); it != docTable.end(); ++it)
filePaths << it.key(); filePaths << it.key();
workingCopy = CppEditor::CppModelManager::instance()->workingCopy(); workingCopy = CppEditor::CppModelManager::workingCopy();
docTable = CppEditor::CppModelManager::instance()->snapshot(); docTable = CppEditor::CppModelManager::snapshot();
newDocTable = {}; newDocTable = {};
for (const auto &file : std::as_const(filePaths)) { for (const auto &file : std::as_const(filePaths)) {
const Document::Ptr doc = docTable.document(file); const Document::Ptr doc = docTable.document(file);
@@ -742,7 +742,7 @@ void QtCreatorIntegration::handleSymbolRenameStage2(
if (usesClangd) if (usesClangd)
editorWidget->textDocument()->setFilePath(uiHeader); editorWidget->textDocument()->setFilePath(uiHeader);
editorWidget->textDocument()->setPlainText(QString::fromUtf8(virtualContent)); editorWidget->textDocument()->setPlainText(QString::fromUtf8(virtualContent));
Snapshot snapshot = CppEditor::CppModelManager::instance()->snapshot(); Snapshot snapshot = CppEditor::CppModelManager::snapshot();
snapshot.remove(uiHeader); snapshot.remove(uiHeader);
snapshot.remove(editor->textDocument()->filePath()); snapshot.remove(editor->textDocument()->filePath());
const Document::Ptr cppDoc = snapshot.preprocessedDocument(virtualContent, uiHeader); const Document::Ptr cppDoc = snapshot.preprocessedDocument(virtualContent, uiHeader);
@@ -783,8 +783,8 @@ void QtCreatorIntegration::handleSymbolRenameStage2(
qCDebug(log) << "renaming with built-in code model"; qCDebug(log) << "renaming with built-in code model";
snapshot.insert(cppDoc); snapshot.insert(cppDoc);
snapshot.updateDependencyTable(); snapshot.updateDependencyTable();
CppEditor::CppModelManager::instance()->renameUsages(cppDoc, cursor, snapshot, CppEditor::CppModelManager::renameUsages(cppDoc, cursor, snapshot,
newName, callback); newName, callback);
} }
return; return;
} }

View File

@@ -21,8 +21,7 @@ QSet<QString> ClassViewController::findClassDeclarations(const FilePath &filePat
{ {
QSet<QString> classNames; QSet<QString> classNames;
CppEditor::CppModelManager *cppModelManager = CppEditor::CppModelManager::instance(); CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::snapshot();
CPlusPlus::Snapshot snapshot = cppModelManager->snapshot();
// scan original file // scan original file
CPlusPlus::Document::Ptr document = snapshot.document(filePath); CPlusPlus::Document::Ptr document = snapshot.document(filePath);

View File

@@ -146,8 +146,7 @@ void UpdateIncludeDependenciesVisitor::updateFilePaths()
void UpdateIncludeDependenciesVisitor::visitMComponent(qmt::MComponent *component) void UpdateIncludeDependenciesVisitor::visitMComponent(qmt::MComponent *component)
{ {
CppEditor::CppModelManager *cppModelManager = CppEditor::CppModelManager::instance(); CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::snapshot();
CPlusPlus::Snapshot snapshot = cppModelManager->snapshot();
const QStringList filePaths = findFilePathOfComponent(component); const QStringList filePaths = findFilePathOfComponent(component);
for (const QString &filePath : filePaths) { for (const QString &filePath : filePaths) {

View File

@@ -87,7 +87,7 @@ bool ElementTasks::hasClassDefinition(const qmt::MElement *element) const
if (auto klass = dynamic_cast<const qmt::MClass *>(element)) { if (auto klass = dynamic_cast<const qmt::MClass *>(element)) {
const QString qualifiedClassName = klass->umlNamespace().isEmpty() ? klass->name() const QString qualifiedClassName = klass->umlNamespace().isEmpty() ? klass->name()
: klass->umlNamespace() + "::" + klass->name(); : klass->umlNamespace() + "::" + klass->name();
auto *locatorData = CppModelManager::instance()->locatorData(); auto *locatorData = CppModelManager::locatorData();
if (!locatorData) if (!locatorData)
return false; return false;
const QList<IndexItem::Ptr> matches = locatorData->findSymbols(IndexItem::Class, const QList<IndexItem::Ptr> matches = locatorData->findSymbols(IndexItem::Class,
@@ -118,7 +118,7 @@ void ElementTasks::openClassDefinition(const qmt::MElement *element)
const QString qualifiedClassName = klass->umlNamespace().isEmpty() ? klass->name() const QString qualifiedClassName = klass->umlNamespace().isEmpty() ? klass->name()
: klass->umlNamespace() + "::" + klass->name(); : klass->umlNamespace() + "::" + klass->name();
auto *locatorData = CppModelManager::instance()->locatorData(); auto *locatorData = CppModelManager::locatorData();
if (!locatorData) if (!locatorData)
return; return;
const QList<IndexItem::Ptr> matches = locatorData->findSymbols(IndexItem::Class, const QList<IndexItem::Ptr> matches = locatorData->findSymbols(IndexItem::Class,

View File

@@ -216,8 +216,7 @@ qmt::MObject *PxNodeUtilities::findSameObject(const QStringList &relativeElement
bool PxNodeUtilities::isProxyHeader(const QString &file) const bool PxNodeUtilities::isProxyHeader(const QString &file) const
{ {
CppEditor::CppModelManager *cppModelManager = CppEditor::CppModelManager::instance(); CPlusPlus::Snapshot snapshot = CppEditor::CppModelManager::snapshot();
CPlusPlus::Snapshot snapshot = cppModelManager->snapshot();
CPlusPlus::Document::Ptr document = snapshot.document(Utils::FilePath::fromString(file)); CPlusPlus::Document::Ptr document = snapshot.document(Utils::FilePath::fromString(file));
if (document) { if (document) {