summaryrefslogtreecommitdiffstats
path: root/config.tests/common
Commit message (Expand)AuthorAgeFilesLines
* Fix building of the C++11 config.test on Windows with ICLThiago Macieira2014-06-272-3/+3
* Allow Clang to compile without libc++Thiago Macieira2013-09-091-2/+6
* Disable app_bundle and lib_bundle when running configure testsTor Arne Vestbø2013-07-168-8/+1
* Update copyright year in Digia's license headersSergio Ahumada2013-01-187-7/+7
* Change copyrights from Nokia to DigiaIikka Eklund2012-09-228-199/+199
* Add c++11 option to configure.exeKai Koehne2012-09-132-0/+56
* Add configure-time checking for the SSE and AVX features on WindowsThiago Macieira2012-06-1213-24/+31
* Move the AVX and SSE tests to config.tests/commonThiago Macieira2012-06-1214-0/+397
n23'>23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "extracompiler.h"

#include "buildmanager.h"
#include "kitinformation.h"
#include "projectmanager.h"
#include "target.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/idocument.h>

#include <extensionsystem/pluginmanager.h>

#include <utils/async.h>
#include <utils/expected.h>
#include <utils/guard.h>
#include <utils/process.h>

#include <QDateTime>
#include <QLoggingCategory>
#include <QThreadPool>
#include <QTimer>

using namespace Core;
using namespace Tasking;
using namespace Utils;

namespace ProjectExplorer {

Q_GLOBAL_STATIC(QThreadPool, s_extraCompilerThreadPool);
Q_GLOBAL_STATIC(QList<ExtraCompilerFactory *>, factories);
Q_LOGGING_CATEGORY(log, "qtc.projectexplorer.extracompiler", QtWarningMsg);

class ExtraCompilerPrivate
{
public:
    const Project *project;
    FilePath source;
    FileNameToContentsHash contents;
    QDateTime compileTime;
    IEditor *lastEditor = nullptr;
    QMetaObject::Connection activeBuildConfigConnection;
    QMetaObject::Connection activeEnvironmentConnection;
    Guard lock;
    bool dirty = false;

    QTimer timer;

    std::unique_ptr<TaskTree> m_taskTree;
};

ExtraCompiler::ExtraCompiler(const Project *project, const FilePath &source,
                             const FilePaths &targets, QObject *parent) :
    QObject(parent), d(std::make_unique<ExtraCompilerPrivate>())
{
    d->project = project;
    d->source = source;
    for (const FilePath &target : targets)
        d->contents.insert(target, QByteArray());
    d->timer.setSingleShot(true);

    connect(&d->timer, &QTimer::timeout, this, &ExtraCompiler::compileIfDirty);
    connect(BuildManager::instance(), &BuildManager::buildStateChanged,
            this, &ExtraCompiler::onTargetsBuilt);

    connect(ProjectManager::instance(), &ProjectManager::projectRemoved,
            this, [this](Project *project) {
        if (project == d->project)
            deleteLater();
    });

    EditorManager *editorManager = EditorManager::instance();
    connect(editorManager, &EditorManager::currentEditorChanged,
            this, &ExtraCompiler::onEditorChanged);
    connect(editorManager, &EditorManager::editorAboutToClose,
            this, &ExtraCompiler::onEditorAboutToClose);

    // Use existing target files, where possible. Otherwise run the compiler.
    QDateTime sourceTime = d->source.lastModified();
    for (const FilePath &target : targets) {
        if (!target.exists()) {
            d->dirty = true;
            continue;
        }

        QDateTime lastModified = target.lastModified();
        if (lastModified < sourceTime)
            d->dirty = true;

        if (!d->compileTime.isValid() || d->compileTime > lastModified)
            d->compileTime = lastModified;

        const expected_str<QByteArray> contents = target.fileContents();
        QTC_ASSERT_EXPECTED(contents, return);

        setContent(target, *contents);
    }
}

ExtraCompiler::~ExtraCompiler() = default;

const Project *ExtraCompiler::project() const
{
    return d->project;
}

FilePath ExtraCompiler::source() const
{
    return d->source;
}

QByteArray ExtraCompiler::content(const FilePath &file) const
{
    return d->contents.value(file);
}

FilePaths ExtraCompiler::targets() const
{
    return d->contents.keys();
}

void ExtraCompiler::forEachTarget(std::function<void (const FilePath &)> func) const
{
    for (auto it = d->contents.constBegin(), end = d->contents.constEnd(); it != end; ++it)
        func(it.key());
}

void ExtraCompiler::updateCompileTime()
{
    d->compileTime = QDateTime::currentDateTime();
}

QThreadPool *ExtraCompiler::extraCompilerThreadPool()
{
    return s_extraCompilerThreadPool();
}

GroupItem ExtraCompiler::compileFileItem()
{
    return taskItemImpl(fromFileProvider());
}

void ExtraCompiler::compileFile()
{
    compileImpl(fromFileProvider());
}

void ExtraCompiler::compileContent(const QByteArray &content)
{
    compileImpl([content] { return content; });
}

void ExtraCompiler::compileImpl(const ContentProvider &provider)
{
    const auto finalize = [=] {
        d->m_taskTree.release()->deleteLater();
    };
    d->m_taskTree.reset(new TaskTree({taskItemImpl(provider)}));
    connect(d->m_taskTree.get(), &TaskTree::done, this, finalize);
    connect(d->m_taskTree.get(), &TaskTree::errorOccurred, this, finalize);
    d->m_taskTree->start();
}

void ExtraCompiler::compileIfDirty()
{
    qCDebug(log) << Q_FUNC_INFO;
    if (!d->lock.isLocked() && d->dirty && d->lastEditor) {
        qCDebug(log) << '\t' << "about to compile";
        d->dirty = false;
        compileContent(d->lastEditor->document()->contents());
    }
}

ExtraCompiler::ContentProvider ExtraCompiler::fromFileProvider() const
{
    const auto provider = [fileName = source()] {
        QFile file(fileName.toString());
        if (!file.open(QFile::ReadOnly | QFile::Text))
            return QByteArray();
        return file.readAll();
    };
    return provider;
}

bool ExtraCompiler::isDirty() const
{
    return d->dirty;
}

void ExtraCompiler::block()
{
    qCDebug(log) << Q_FUNC_INFO;
    d->lock.lock();
}

void ExtraCompiler::unblock()
{
    qCDebug(log) << Q_FUNC_INFO;
    d->lock.unlock();
    if (!d->lock.isLocked() && !d->timer.isActive())
        d->timer.start();
}

void ExtraCompiler::onTargetsBuilt(Project *project)
{
    if (project != d->project || BuildManager::isBuilding(project))
        return;

    // This is mostly a fall back for the cases when the generator couldn't be run.
    // It pays special attention to the case where a source file was newly created
    const QDateTime sourceTime = d->source.lastModified();
    if (d->compileTime.isValid() && d->compileTime >= sourceTime)
        return;

    forEachTarget([&](const FilePath &target) {
        QFileInfo fi(target.toFileInfo());
        QDateTime generateTime = fi.exists() ? fi.lastModified() : QDateTime();
        if (generateTime.isValid() && (generateTime > sourceTime)) {
            if (d->compileTime >= generateTime)
                return;

            const expected_str<QByteArray> contents = target.fileContents();
            QTC_ASSERT_EXPECTED(contents, return);

            d->compileTime = generateTime;
            setContent(target, *contents);
        }
    });
}

void ExtraCompiler::onEditorChanged(IEditor *editor)
{
    // Handle old editor
    if (d->lastEditor) {
        IDocument *doc = d->lastEditor->document();
        disconnect(doc, &IDocument::contentsChanged,
                   this, &ExtraCompiler::setDirty);

        if (d->dirty) {
            d->dirty = false;
            compileContent(doc->contents());
        }
    }

    if (editor && editor->document()->filePath() == d->source) {
        d->lastEditor = editor;

        // Handle new editor
        connect(d->lastEditor->document(), &IDocument::contentsChanged,
                this, &ExtraCompiler::setDirty);
    } else {
        d->lastEditor = nullptr;
    }
}

void ExtraCompiler::setDirty()
{
    d->dirty = true;
    d->timer.start(1000);
}

void ExtraCompiler::onEditorAboutToClose(IEditor *editor)
{
    if (d->lastEditor != editor)
        return;

    // Oh no our editor is going to be closed
    // get the content first
    IDocument *doc = d->lastEditor->document();
    disconnect(doc, &IDocument::contentsChanged,
               this, &ExtraCompiler::setDirty);
    if (d->dirty) {
        d->dirty = false;
        compileContent(doc->contents());
    }
    d->lastEditor = nullptr;
}

Environment ExtraCompiler::buildEnvironment() const
{
    Target *target = project()->activeTarget();
    if (!target)
        return Environment::systemEnvironment();

    if (BuildConfiguration *bc = target->activeBuildConfiguration())
        return bc->environment();

    const EnvironmentItems changes = EnvironmentKitAspect::environmentChanges(target->kit());
    Environment env = Environment::systemEnvironment();
    env.modify(changes);
    return env;
}

void ExtraCompiler::setContent(const FilePath &file, const QByteArray &contents)
{
    qCDebug(log).noquote() << Q_FUNC_INFO << contents;
    auto it = d->contents.find(file);
    if (it != d->contents.end()) {
        if (it.value() != contents) {
            it.value() = contents;
            emit contentsChanged(file);
        }
    }
}

ExtraCompilerFactory::ExtraCompilerFactory(QObject *parent)
    : QObject(parent)
{
    factories->append(this);
}

ExtraCompilerFactory::~ExtraCompilerFactory()
{
    factories->removeAll(this);
}

QList<ExtraCompilerFactory *> ExtraCompilerFactory::extraCompilerFactories()
{
    return *factories();
}

ProcessExtraCompiler::ProcessExtraCompiler(const Project *project, const FilePath &source,
                                           const FilePaths &targets, QObject *parent) :
    ExtraCompiler(project, source, targets, parent)
{ }

GroupItem ProcessExtraCompiler::taskItemImpl(const ContentProvider &provider)
{
    const auto setupTask = [=](Async<FileNameToContentsHash> &async) {
        async.setThreadPool(extraCompilerThreadPool());
        // The passed synchronizer has cancelOnWait set to true by default.
        async.setFutureSynchronizer(ExtensionSystem::PluginManager::futureSynchronizer());
        async.setConcurrentCallData(&ProcessExtraCompiler::runInThread, this, command(),
                                    workingDirectory(), arguments(), provider, buildEnvironment());
    };
    const auto taskDone = [=](const Async<FileNameToContentsHash> &async) {
        if (!async.isResultAvailable())
            return;
        const FileNameToContentsHash data = async.result();
        if (data.isEmpty())
            return; // There was some kind of error...
        for (auto it = data.constBegin(), end = data.constEnd(); it != end; ++it)
            setContent(it.key(), it.value());
        updateCompileTime();
    };
    return AsyncTask<FileNameToContentsHash>(setupTask, taskDone);
}

FilePath ProcessExtraCompiler::workingDirectory() const
{
    return FilePath();
}

QStringList ProcessExtraCompiler::arguments() const
{
    return QStringList();
}

bool ProcessExtraCompiler::prepareToRun(const QByteArray &sourceContents)
{
    Q_UNUSED(sourceContents)
    return true;
}

Tasks ProcessExtraCompiler::parseIssues(const QByteArray &stdErr)
{
    Q_UNUSED(stdErr)
    return {};
}

void ProcessExtraCompiler::runInThread(QPromise<FileNameToContentsHash> &promise,
                                       const FilePath &cmd, const FilePath &workDir,
                                       const QStringList &args, const ContentProvider &provider,
                                       const Environment &env)
{
    if (cmd.isEmpty() || !cmd.toFileInfo().isExecutable())
        return;

    const QByteArray sourceContents = provider();
    if (sourceContents.isNull() || !prepareToRun(sourceContents))
        return;

    Process process;

    process.setEnvironment(env);
    if (!workDir.isEmpty())
        process.setWorkingDirectory(workDir);
    process.setCommand({ cmd, args });
    process.setWriteData(sourceContents);
    process.start();
    if (!process.waitForStarted())
        return;

    while (!promise.isCanceled()) {
        if (process.waitForFinished(200))
            break;
    }

    if (promise.isCanceled())
        return;

    promise.addResult(handleProcessFinished(&process));
}

} // namespace ProjectExplorer