builddirmanager.cpp 17.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "builddirmanager.h"
27
#include "cmakebuildconfiguration.h"
28
#include "cmakekitinformation.h"
29
#include "cmakeparser.h"
30
#include "cmakeprojectconstants.h"
31
#include "cmakeprojectmanager.h"
32
#include "cmakeprojectnodes.h"
33 34
#include "cmaketool.h"

35
#include <coreplugin/icore.h>
36
#include <coreplugin/documentmanager.h>
37
#include <coreplugin/messagemanager.h>
38
#include <coreplugin/editormanager/editormanager.h>
39
#include <coreplugin/progressmanager/progressmanager.h>
40
#include <cpptools/cpptoolsconstants.h>
41 42
#include <cpptools/projectpartbuilder.h>
#include <projectexplorer/headerpath.h>
43
#include <projectexplorer/kit.h>
44
#include <projectexplorer/kitinformation.h>
45
#include <projectexplorer/project.h>
46 47
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
48
#include <projectexplorer/target.h>
49
#include <projectexplorer/taskhub.h>
50
#include <projectexplorer/toolchain.h>
51 52

#include <utils/algorithm.h>
53
#include <utils/fileutils.h>
54
#include <utils/mimetypes/mimedatabase.h>
55
#include <utils/qtcassert.h>
56
#include <utils/qtcprocess.h>
57
#include <utils/runextensions.h>
58 59 60
#include <utils/synchronousprocess.h>

#include <QDateTime>
Tobias Hunger's avatar
Tobias Hunger committed
61
#include <QFile>
62
#include <QFileInfo>
63
#include <QMessageBox>
64 65 66 67
#include <QRegularExpression>
#include <QSet>
#include <QTemporaryDir>

68 69
using namespace ProjectExplorer;

70 71 72 73 74 75 76
namespace CMakeProjectManager {
namespace Internal {

// --------------------------------------------------------------------
// BuildDirManager:
// --------------------------------------------------------------------

77
BuildDirManager::BuildDirManager(CMakeBuildConfiguration *bc) :
78
    m_buildConfiguration(bc)
79
{
80
    QTC_ASSERT(bc, return);
81

82
    m_reparseTimer.setSingleShot(true);
83

84
    connect(&m_reparseTimer, &QTimer::timeout, this, &BuildDirManager::parse);
85 86 87

    connect(&m_futureWatcher, &QFutureWatcher<QList<FileNode *>>::finished,
            this, &BuildDirManager::emitDataAvailable);
88 89
}

90 91
BuildDirManager::~BuildDirManager() = default;

92 93
const Utils::FileName BuildDirManager::workDirectory() const
{
94
    const Utils::FileName bdir = m_buildConfiguration->buildDirectory();
95 96
    if (bdir.exists())
        return bdir;
97 98 99 100 101 102
    if (!m_tempDir) {
        const QString path = QDir::tempPath() + QLatin1String("/qtc-cmake-XXXXXX");
        m_tempDir.reset(new QTemporaryDir(path));
        if (!m_tempDir->isValid())
            emit errorOccured(tr("Failed to create temporary directory using template \"%1\".").arg(path));
    }
103
    return Utils::FileName::fromString(m_tempDir->path());
104 105
}

106 107 108 109 110 111
void BuildDirManager::emitDataAvailable()
{
    if (!isParsing() && m_futureWatcher.isFinished())
        emit dataAvailable();
}

112
void BuildDirManager::updateReaderType(std::function<void()> todo)
113
{
114 115
    BuildDirReader::Parameters p(m_buildConfiguration);
    p.buildDirectory = workDirectory();
116

117 118 119 120 121
    if (!m_reader || !m_reader->isCompatible(p)) {
        m_reader.reset(BuildDirReader::createReader(p));
        connect(m_reader.get(), &BuildDirReader::configurationStarted,
                this, &BuildDirManager::configurationStarted);
        connect(m_reader.get(), &BuildDirReader::dataAvailable,
122
                this, &BuildDirManager::emitDataAvailable);
123 124 125 126 127
        connect(m_reader.get(), &BuildDirReader::errorOccured,
                this, &BuildDirManager::errorOccured);
        connect(m_reader.get(), &BuildDirReader::dirty, this, &BuildDirManager::becameDirty);
    }
    m_reader->setParameters(p);
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    if (m_reader->isReady())
        todo();
    else
        connect(m_reader.get(), &BuildDirReader::isReadyNow, this, todo);
}

void BuildDirManager::updateReaderData()
{
    BuildDirReader::Parameters p(m_buildConfiguration);
    p.buildDirectory = workDirectory();

    m_reader->setParameters(p);
}

void BuildDirManager::parseOnceReaderReady(bool force)
{
145 146 147 148 149 150
    m_futureInterface.reset(new QFutureInterface<QList<ProjectExplorer::FileNode *>>());
    m_futureWatcher.setFuture(m_futureInterface->future());

    Core::ProgressManager::addTask(m_futureInterface->future(), "Scan CMake project tree", "CMake.Scan.Tree");
    Utils::runAsync([this]() { BuildDirManager::asyncScanForFiles(*m_futureInterface); });

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    checkConfiguration();
    m_reader->stop();
    m_reader->parse(force);
}

void BuildDirManager::maybeForceReparseOnceReaderReady()
{
    checkConfiguration();

    const QByteArray GENERATOR_KEY = "CMAKE_GENERATOR";
    const QByteArray EXTRA_GENERATOR_KEY = "CMAKE_EXTRA_GENERATOR";
    const QByteArray CMAKE_COMMAND_KEY = "CMAKE_COMMAND";

    const QByteArrayList criticalKeys
            = QByteArrayList() << GENERATOR_KEY << CMAKE_COMMAND_KEY;

    const CMakeConfig currentConfig = parsedConfiguration();

    Kit *k = m_buildConfiguration->target()->kit();
    const CMakeTool *tool = CMakeKitInformation::cmakeTool(k);
    QTC_ASSERT(tool, return); // No cmake... we should not have ended up here in the first place
    const QString extraKitGenerator = CMakeGeneratorKitInformation::extraGenerator(k);
    const QString mainKitGenerator = CMakeGeneratorKitInformation::generator(k);
    CMakeConfig targetConfig = m_buildConfiguration->cmakeConfiguration();
    targetConfig.append(CMakeConfigItem(GENERATOR_KEY, CMakeConfigItem::INTERNAL,
                                        QByteArray(), mainKitGenerator.toUtf8()));
    if (!extraKitGenerator.isEmpty())
        targetConfig.append(CMakeConfigItem(EXTRA_GENERATOR_KEY, CMakeConfigItem::INTERNAL,
                                            QByteArray(), extraKitGenerator.toUtf8()));
    targetConfig.append(CMakeConfigItem(CMAKE_COMMAND_KEY, CMakeConfigItem::INTERNAL,
                                        QByteArray(), tool->cmakeExecutable().toUserOutput().toUtf8()));
    Utils::sort(targetConfig, CMakeConfigItem::sortOperator());

    bool mustReparse = false;
    auto ccit = currentConfig.constBegin();
    auto kcit = targetConfig.constBegin();

    while (ccit != currentConfig.constEnd() && kcit != targetConfig.constEnd()) {
        if (ccit->key == kcit->key) {
            if (ccit->value != kcit->value) {
                if (criticalKeys.contains(kcit->key)) {
                        clearCache();
                        return;
                }
                mustReparse = true;
            }
            ++ccit;
            ++kcit;
        } else {
            if (ccit->key < kcit->key) {
                ++ccit;
            } else {
                ++kcit;
                mustReparse = true;
            }
        }
    }

    // If we have keys that do not exist yet, then reparse.
    //
    // The critical keys *must* be set in cmake configuration, so those were already
    // handled above.
    if (mustReparse || kcit != targetConfig.constEnd())
        parseOnceReaderReady(true);
215 216 217
}

bool BuildDirManager::isParsing() const
218
{
219
    return m_reader && m_reader->isParsing();
220 221
}

222
void BuildDirManager::becameDirty()
223 224 225 226
{
    if (isParsing())
        return;

227 228 229 230 231 232
    Target *t = m_buildConfiguration->target()->project()->activeTarget();
    BuildConfiguration *bc = t ? t->activeBuildConfiguration() : nullptr;

    if (bc != m_buildConfiguration)
        return;

233 234 235 236
    const CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
    if (!tool->isAutoRun())
        return;

237
    m_reparseTimer.start(1000);
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
void BuildDirManager::asyncScanForFiles(QFutureInterface<QList<FileNode *> > &fi)
{
    fi.reportStarted();
    Utils::MimeDatabase mdb;

    QList<FileNode *> nodes
            = FileNode::scanForFiles(m_buildConfiguration->target()->project()->projectDirectory(),
                                     [&mdb](const Utils::FileName &fn) -> FileNode * {
                                         QTC_ASSERT(!fn.isEmpty(), return nullptr);
                                         const Utils::MimeType mimeType = mdb.mimeTypeForFile(fn.toString());
                                         FileType type = FileType::Unknown;
                                         if (mimeType.isValid()) {
                                             const QString mt = mimeType.name();
                                             if (mt == CppTools::Constants::C_SOURCE_MIMETYPE
                                                     || mt == CppTools::Constants::CPP_SOURCE_MIMETYPE
                                                     || mt == CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE
                                                     || mt == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE
                                                     || mt == CppTools::Constants::QDOC_MIMETYPE
                                                     || mt == CppTools::Constants::MOC_MIMETYPE)
                                                 type = FileType::Source;
                                             else if (mt == CppTools::Constants::C_HEADER_MIMETYPE
                                                      || mt == CppTools::Constants::CPP_HEADER_MIMETYPE)
                                                 type = FileType::Header;
                                             else if (mt == ProjectExplorer::Constants::FORM_MIMETYPE)
                                                 type = FileType::Form;
                                             else if (mt == ProjectExplorer::Constants::RESOURCE_MIMETYPE)
                                                 type = FileType::Resource;
                                             else if (mt == ProjectExplorer::Constants::SCXML_MIMETYPE)
                                                 type = FileType::StateChart;
                                             else if (mt == CMakeProjectManager::Constants::CMAKEPROJECTMIMETYPE
                                                      || mt == CMakeProjectManager::Constants::CMAKEMIMETYPE)
                                                 type = FileType::Project;
                                             else if (mt == ProjectExplorer::Constants::QML_MIMETYPE)
                                                 type = FileType::QML;
                                         }
                                         return new FileNode(fn, type, false);
                                     },
                                     &fi);
    fi.setProgressValue(m_futureInterface->progressMaximum());
    fi.reportResult(nodes);
    fi.reportFinished();
}

283 284
void BuildDirManager::forceReparse()
{
285 286 287
    if (m_buildConfiguration->target()->activeBuildConfiguration() != m_buildConfiguration)
        return;

288
    CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
289 290
    QTC_ASSERT(tool, return);

291
    m_reader.reset(); // Force reparse by forcing in a new reader
292
    updateReaderType([this]() { parseOnceReaderReady(true); });
293 294
}

295
void BuildDirManager::resetData()
296
{
297 298
    if (m_reader)
        m_reader->resetData();
299

Tobias Hunger's avatar
Tobias Hunger committed
300
    m_cmakeCache.clear();
301
    m_futureInterface.reset();
302 303

    m_reader.reset(nullptr);
304 305
}

306 307 308 309 310
bool BuildDirManager::updateCMakeStateBeforeBuild()
{
    return m_reparseTimer.isActive();
}

311 312 313 314 315
bool BuildDirManager::persistCMakeState()
{
    if (!m_tempDir)
        return false;

316 317 318
    const QString buildDir = m_buildConfiguration->buildDirectory().toString();
    QDir dir(buildDir);
    dir.mkpath(buildDir);
319

320
    m_tempDir.reset(nullptr);
321

322
    QTimer::singleShot(0, this, &BuildDirManager::parse); // make sure signals only happen afterwards!
323 324 325
    return true;
}

326 327
void BuildDirManager::generateProjectTree(CMakeProjectNode *root)
{
328
    QTC_ASSERT(m_reader, return);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    QTC_ASSERT(m_futureInterface, return);

    const Utils::FileName projectFile = m_buildConfiguration->target()->project()->projectFilePath();
    QList<FileNode *> tmp = Utils::filtered(m_futureInterface->future().result(),
                                            [projectFile](const FileNode *fn) -> bool {
            const Utils::FileName &path = fn->filePath();
            return path != projectFile && !path.toString().startsWith(projectFile.toString() + ".user");
    });
    Utils::sort(tmp, ProjectExplorer::Node::sortByPath);

    m_futureInterface.reset(); // Make sure to flush the stale results

    const QList<FileNode *> allFiles = tmp;
    m_reader->generateProjectTree(root, allFiles);
    QSet<FileNode *> usedNodes;
    foreach (FileNode *fn, root->recursiveFileNodes())
        usedNodes.insert(fn);

    QList<FileNode *> leftOvers = Utils::filtered(allFiles, [&usedNodes](FileNode *fn) {
            return !usedNodes.contains(fn);
    });
    qDeleteAll(leftOvers);
351 352
}

353 354
QSet<Core::Id> BuildDirManager::updateCodeModel(CppTools::ProjectPartBuilder &ppBuilder)
{
355 356
    QTC_ASSERT(m_reader, return QSet<Core::Id>());
    return m_reader->updateCodeModel(ppBuilder);
357 358
}

359 360
void BuildDirManager::parse()
{
361 362
    TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);

363
    updateReaderType([this]() { parseOnceReaderReady(false); });
364 365
}

366 367
void BuildDirManager::clearCache()
{
368 369
    auto cmakeCache = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeCache.txt"));
    auto cmakeFiles = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeFiles"));
370 371 372 373 374 375 376 377 378 379 380

    const bool mustCleanUp = cmakeCache.exists() || cmakeFiles.exists();
    if (!mustCleanUp)
        return;

    Utils::FileUtils::removeRecursively(cmakeCache);
    Utils::FileUtils::removeRecursively(cmakeFiles);

    forceReparse();
}

381 382
QList<CMakeBuildTarget> BuildDirManager::buildTargets() const
{
383 384
    if (!m_reader)
        return QList<CMakeBuildTarget>();
385
    return m_reader->buildTargets();
386 387
}

Tobias Hunger's avatar
Tobias Hunger committed
388
CMakeConfig BuildDirManager::parsedConfiguration() const
Tobias Hunger's avatar
Tobias Hunger committed
389
{
390 391
    if (!m_reader)
        return m_cmakeCache;
392 393
    if (m_cmakeCache.isEmpty())
        m_cmakeCache = m_reader->parsedConfiguration();
Tobias Hunger's avatar
Tobias Hunger committed
394
    return m_cmakeCache;
Tobias Hunger's avatar
Tobias Hunger committed
395 396
}

397 398 399 400 401
void BuildDirManager::checkConfiguration()
{
    if (m_tempDir) // always throw away changes in the tmpdir!
        return;

402
    Kit *k = m_buildConfiguration->target()->kit();
403
    const CMakeConfig cache = m_reader->parsedConfiguration();
404 405 406 407 408 409
    if (cache.isEmpty())
        return; // No cache file yet.

    CMakeConfig newConfig;
    QSet<QString> changedKeys;
    QSet<QString> removedKeys;
410
    foreach (const CMakeConfigItem &iBc, m_buildConfiguration->cmakeConfiguration()) {
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        const CMakeConfigItem &iCache
                = Utils::findOrDefault(cache, [&iBc](const CMakeConfigItem &i) { return i.key == iBc.key; });
        if (iCache.isNull()) {
            removedKeys << QString::fromUtf8(iBc.key);
        } else if (QString::fromUtf8(iCache.value) != iBc.expandedValue(k)) {
            changedKeys << QString::fromUtf8(iBc.key);
            newConfig.append(iCache);
        } else {
            newConfig.append(iBc);
        }
    }

    if (!changedKeys.isEmpty() || !removedKeys.isEmpty()) {
        QSet<QString> total = removedKeys + changedKeys;
        QStringList keyList = total.toList();
        Utils::sort(keyList);
        QString table = QLatin1String("<table>");
        foreach (const QString &k, keyList) {
            QString change;
            if (removedKeys.contains(k))
                change = tr("<removed>");
            else
                change = QString::fromUtf8(CMakeConfigItem::valueOf(k.toUtf8(), cache)).trimmed();
            if (change.isEmpty())
                change = tr("<empty>");
            table += QString::fromLatin1("\n<tr><td>%1</td><td>%2</td></tr>").arg(k).arg(change.toHtmlEscaped());
        }
        table += QLatin1String("\n</table>");

        QPointer<QMessageBox> box = new QMessageBox(Core::ICore::mainWindow());
        box->setText(tr("CMake configuration has changed on disk."));
        box->setInformativeText(tr("The CMakeCache.txt file has changed: %1").arg(table));
443 444 445
        auto *defaultButton = box->addButton(tr("Overwrite Changes in CMake"), QMessageBox::RejectRole);
        box->addButton(tr("Apply Changes to Project"), QMessageBox::AcceptRole);
        box->setDefaultButton(defaultButton);
446 447

        int ret = box->exec();
448
        if (ret == QMessageBox::Apply) {
449
            m_buildConfiguration->setCMakeConfiguration(newConfig);
450
            updateReaderData(); // Apply changes to reader
451
        }
Tobias Hunger's avatar
Tobias Hunger committed
452
    }
453 454
}

455 456
void BuildDirManager::maybeForceReparse()
{
457 458 459 460 461
    if (!m_reader || !m_reader->hasData()) {
        forceReparse();
        return;
    }

462
    updateReaderType([this]() { maybeForceReparseOnceReaderReady(); });
463 464
}

465 466
} // namespace Internal
} // namespace CMakeProjectManager