builddirmanager.cpp 15.1 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"
Tobias Hunger's avatar
Tobias Hunger committed
27

28
#include "cmakebuildconfiguration.h"
29
#include "cmakebuildstep.h"
30
#include "cmakekitinformation.h"
31
#include "cmakeprojectnodes.h"
32 33
#include "cmaketool.h"

34
#include <coreplugin/icore.h>
35
#include <projectexplorer/kit.h>
36
#include <projectexplorer/kitinformation.h>
37
#include <projectexplorer/project.h>
38
#include <projectexplorer/projectexplorerconstants.h>
39
#include <projectexplorer/target.h>
40
#include <projectexplorer/taskhub.h>
41
#include <projectexplorer/toolchain.h>
42 43

#include <utils/algorithm.h>
44
#include <utils/fileutils.h>
45 46
#include <utils/qtcassert.h>

47
#include <QDir>
48
#include <QMessageBox>
49
#include <QPushButton>
50 51
#include <QSet>

52 53
using namespace ProjectExplorer;

54 55 56 57 58 59 60
namespace CMakeProjectManager {
namespace Internal {

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

61
BuildDirManager::BuildDirManager(CMakeBuildConfiguration *bc) :
62
    m_buildConfiguration(bc)
63
{
64
    QTC_ASSERT(bc, return);
65

66
    m_reparseTimer.setSingleShot(true);
67

68
    connect(&m_reparseTimer, &QTimer::timeout, this, &BuildDirManager::parse);
69 70
}

71 72
BuildDirManager::~BuildDirManager() = default;

73 74
const Utils::FileName BuildDirManager::workDirectory() const
{
75
    const Utils::FileName bdir = m_buildConfiguration->buildDirectory();
76 77
    const CMakeTool *cmake = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
    if (bdir.exists()) {
78
        return bdir;
79 80 81 82 83 84 85
    } else {
        if (cmake && cmake->autoCreateBuildDirectory()) {
            if (!QDir().mkpath(bdir.toString()))
                emitErrorOccured(tr("Failed to create build directory \"%1\".").arg(bdir.toUserOutput()));
            return bdir;
        }
    }
86
    if (!m_tempDir) {
87
        m_tempDir.reset(new Utils::TemporaryDirectory("qtc-cmake-XXXXXXXX"));
88 89 90 91
        if (!m_tempDir->isValid()) {
            emitErrorOccured(tr("Failed to create temporary directory \"%1\".")
                             .arg(QDir::toNativeSeparators(m_tempDir->path())));
        }
92
    }
93
    return Utils::FileName::fromString(m_tempDir->path());
94 95
}

96 97
void BuildDirManager::emitDataAvailable()
{
98
    if (!isParsing())
99 100 101
        emit dataAvailable();
}

102 103 104 105 106 107 108
void BuildDirManager::emitErrorOccured(const QString &message) const
{
    m_isHandlingError = true;
    emit errorOccured(message);
    m_isHandlingError = false;
}

109
void BuildDirManager::updateReaderType(std::function<void()> todo)
110
{
111 112
    BuildDirReader::Parameters p(m_buildConfiguration);
    p.buildDirectory = workDirectory();
113

114 115 116 117 118
    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,
119
                this, &BuildDirManager::emitDataAvailable);
120
        connect(m_reader.get(), &BuildDirReader::errorOccured,
121
                this, &BuildDirManager::emitErrorOccured);
122 123 124
        connect(m_reader.get(), &BuildDirReader::dirty, this, &BuildDirManager::becameDirty);
    }
    m_reader->setParameters(p);
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    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);
}

140
void BuildDirManager::parseOnceReaderReady(bool force, bool checkForChanges)
141
{
142 143
    TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);

144
    m_buildTargets.clear();
145
    m_cmakeCache.clear();
146 147
    if (checkForChanges)
        checkConfiguration();
148 149 150 151 152 153 154 155 156 157 158
    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";
159 160
    const QByteArray CMAKE_C_COMPILER_KEY = "CMAKE_C_COMPILER";
    const QByteArray CMAKE_CXX_COMPILER_KEY = "CMAKE_CXX_COMPILER";
161 162

    const QByteArrayList criticalKeys
163
            = {GENERATOR_KEY, CMAKE_COMMAND_KEY, CMAKE_C_COMPILER_KEY, CMAKE_CXX_COMPILER_KEY};
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

    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);
213 214 215
}

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

220
void BuildDirManager::becameDirty()
221 222 223 224
{
    if (isParsing())
        return;

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

    if (bc != m_buildConfiguration)
        return;

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

235
    m_reparseTimer.start(1000);
236 237
}

238
void BuildDirManager::forceReparse()
239 240 241 242 243 244 245 246 247 248
{
    forceReparseImpl(true);
}

void BuildDirManager::forceReparseWithoutCheckingForChanges()
{
    forceReparseImpl(false);
}

void BuildDirManager::forceReparseImpl(bool checkForChanges)
249
{
250 251
    QTC_ASSERT(!m_isHandlingError, return);

252 253 254
    if (m_buildConfiguration->target()->activeBuildConfiguration() != m_buildConfiguration)
        return;

255
    CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
256 257
    QTC_ASSERT(tool, return);

258
    m_reader.reset(); // Force reparse by forcing in a new reader
259
    updateReaderType([this, checkForChanges]() { parseOnceReaderReady(true, checkForChanges); });
260 261
}

262
void BuildDirManager::resetData()
263
{
264 265
    QTC_ASSERT(!m_isHandlingError, return);

266 267
    if (m_reader)
        m_reader->resetData();
268

Tobias Hunger's avatar
Tobias Hunger committed
269
    m_cmakeCache.clear();
270
    m_reader.reset();
271 272

    m_buildTargets.clear();
273 274
}

275 276 277 278 279
bool BuildDirManager::updateCMakeStateBeforeBuild()
{
    return m_reparseTimer.isActive();
}

280 281 282 283 284
bool BuildDirManager::persistCMakeState()
{
    if (!m_tempDir)
        return false;

285 286 287
    const QString buildDir = m_buildConfiguration->buildDirectory().toString();
    QDir dir(buildDir);
    dir.mkpath(buildDir);
288

289
    m_tempDir.reset(nullptr);
290

291
    QTimer::singleShot(0, this, &BuildDirManager::parse); // make sure signals only happen afterwards!
292 293 294
    return true;
}

295
void BuildDirManager::generateProjectTree(CMakeProjectNode *root, const QList<const FileNode *> &allFiles)
296
{
297
    QTC_ASSERT(!m_isHandlingError, return);
298
    QTC_ASSERT(m_reader, return);
299 300 301

    const Utils::FileName projectFile = m_buildConfiguration->target()->project()->projectFilePath();

302
    m_reader->generateProjectTree(root, allFiles);
303 304
}

305
void BuildDirManager::updateCodeModel(CppTools::RawProjectParts &rpps)
306
{
307
    QTC_ASSERT(!m_isHandlingError, return);
308 309
    QTC_ASSERT(m_reader, return);
    return m_reader->updateCodeModel(rpps);
310 311
}

312 313
void BuildDirManager::parse()
{
314
    updateReaderType([this]() { parseOnceReaderReady(false); });
315 316
}

317 318
void BuildDirManager::clearCache()
{
319 320
    QTC_ASSERT(!m_isHandlingError, return);

321 322
    auto cmakeCache = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeCache.txt"));
    auto cmakeFiles = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeFiles"));
323 324 325 326 327 328 329 330 331 332 333

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

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

    forceReparse();
}

334 335 336 337 338 339 340 341 342 343 344 345
static CMakeBuildTarget utilityTarget(const QString &title, const BuildDirManager *bdm)
{
    CMakeBuildTarget target;

    target.title = title;
    target.targetType = UtilityType;
    target.workingDirectory = bdm->buildConfiguration()->buildDirectory();
    target.sourceDirectory = bdm->buildConfiguration()->target()->project()->projectDirectory();

    return target;
}

346 347
QList<CMakeBuildTarget> BuildDirManager::buildTargets() const
{
348 349
    QTC_ASSERT(!m_isHandlingError, return {});

350 351
    if (!m_reader)
        return QList<CMakeBuildTarget>();
352 353 354 355
    if (m_buildTargets.isEmpty()) {
        m_buildTargets.append(utilityTarget(CMakeBuildStep::allTarget(), this));
        m_buildTargets.append(utilityTarget(CMakeBuildStep::cleanTarget(), this));
        m_buildTargets.append(utilityTarget(CMakeBuildStep::installTarget(), this));
356 357
        m_buildTargets.append(utilityTarget(CMakeBuildStep::testTarget(), this));

358
        m_buildTargets.append(Utils::filtered(m_reader->buildTargets(), [](const CMakeBuildTarget &bt) {
359 360 361 362
            return bt.title != CMakeBuildStep::allTarget()
                    && bt.title != CMakeBuildStep::cleanTarget()
                    && bt.title != CMakeBuildStep::installTarget()
                    && bt.title != CMakeBuildStep::testTarget();
363
        }));
364
    }
365
    return m_buildTargets;
366 367
}

Tobias Hunger's avatar
Tobias Hunger committed
368
CMakeConfig BuildDirManager::parsedConfiguration() const
Tobias Hunger's avatar
Tobias Hunger committed
369
{
370 371
    QTC_ASSERT(!m_isHandlingError, return {});

372 373
    if (!m_reader)
        return m_cmakeCache;
374
    if (m_cmakeCache.isEmpty())
375
        m_cmakeCache = m_reader->takeParsedConfiguration();
376 377 378 379

    for (auto &ci : m_cmakeCache)
        ci.inCMakeCache = true;

Tobias Hunger's avatar
Tobias Hunger committed
380
    return m_cmakeCache;
Tobias Hunger's avatar
Tobias Hunger committed
381 382
}

383 384 385 386 387 388 389 390 391 392 393 394 395
CMakeConfig BuildDirManager::parseConfiguration(const Utils::FileName &cacheFile, QString *errorMessage)
{
    if (!cacheFile.exists()) {
        if (errorMessage)
            *errorMessage = tr("CMakeCache.txt file not found.");
        return { };
    }
    CMakeConfig result = CMakeConfigItem::itemsFromFile(cacheFile, errorMessage);
    if (!errorMessage->isEmpty())
        return { };
    return result;
}

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

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

    CMakeConfig newConfig;
    QSet<QString> changedKeys;
    QSet<QString> removedKeys;
409
    foreach (const CMakeConfigItem &iBc, m_buildConfiguration->cmakeConfiguration()) {
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        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));
442
        auto *defaultButton = box->addButton(tr("Overwrite Changes in CMake"), QMessageBox::RejectRole);
443
        auto *applyButton = box->addButton(tr("Apply Changes to Project"), QMessageBox::ApplyRole);
444
        box->setDefaultButton(defaultButton);
445

446 447
        box->exec();
        if (box->clickedButton() == applyButton)
448
            m_buildConfiguration->setCMakeConfiguration(newConfig);
Tobias Hunger's avatar
Tobias Hunger committed
449
    }
450 451
}

452 453
void BuildDirManager::maybeForceReparse()
{
454 455 456
    if (m_isHandlingError)
        return;

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