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

#include "genericproject.h"
Tobias Hunger's avatar
Tobias Hunger committed
31

dt's avatar
dt committed
32
#include "genericbuildconfiguration.h"
Tobias Hunger's avatar
Tobias Hunger committed
33
#include "genericmakestep.h"
hjk's avatar
hjk committed
34
#include "genericprojectconstants.h"
Roberto Raggi's avatar
Roberto Raggi committed
35

hjk's avatar
hjk committed
36 37 38
#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
39 40
#include <coreplugin/mimedatabase.h>
#include <cpptools/cpptoolsconstants.h>
hjk's avatar
hjk committed
41 42
#include <cpptools/ModelManagerInterface.h>
#include <extensionsystem/pluginmanager.h>
43
#include <projectexplorer/abi.h>
Tobias Hunger's avatar
Tobias Hunger committed
44
#include <projectexplorer/buildsteplist.h>
45
#include <projectexplorer/headerpath.h>
Tobias Hunger's avatar
Tobias Hunger committed
46 47
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
Roberto Raggi's avatar
Roberto Raggi committed
48
#include <projectexplorer/projectexplorerconstants.h>
49
#include <qtsupport/customexecutablerunconfiguration.h>
50
#include <utils/fileutils.h>
hjk's avatar
hjk committed
51
#include <utils/qtcassert.h>
Roberto Raggi's avatar
Roberto Raggi committed
52

53 54
#include <QDir>
#include <QProcessEnvironment>
Roberto Raggi's avatar
Roberto Raggi committed
55

hjk's avatar
hjk committed
56
using namespace Core;
57
using namespace ProjectExplorer;
Roberto Raggi's avatar
Roberto Raggi committed
58

hjk's avatar
hjk committed
59 60 61
namespace GenericProjectManager {
namespace Internal {

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
static QList<Core::MimeType> cppMimeTypes()
{
    QStringList mimeTypesNames;
    mimeTypesNames << QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)
                   << QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)
                   << QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)
                   << QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)
                   << QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE);

    QList<Core::MimeType> mimeTypes;

    const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
    foreach (const QString &typeName, mimeTypesNames) {
        Core::MimeType mimeType = mimeDatabase->findByType(typeName);
        if (!mimeType.isNull())
            mimeTypes.append(mimeType);
    }

    return mimeTypes;
}

83
////////////////////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
84
//
85
// GenericProject
hjk's avatar
hjk committed
86
//
87 88
////////////////////////////////////////////////////////////////////////////////////

Roberto Raggi's avatar
Roberto Raggi committed
89
GenericProject::GenericProject(Manager *manager, const QString &fileName)
90
    : m_manager(manager),
Tobias Hunger's avatar
Tobias Hunger committed
91
      m_fileName(fileName)
Roberto Raggi's avatar
Roberto Raggi committed
92
{
hjk's avatar
hjk committed
93
    setProjectContext(Context(GenericProjectManager::Constants::PROJECTCONTEXT));
94
    setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));
95

96
    QFileInfo fileInfo(m_fileName);
97 98
    QDir dir = fileInfo.dir();

99
    m_projectName      = fileInfo.completeBaseName();
100 101 102
    m_filesFileName    = QFileInfo(dir, m_projectName + QLatin1String(".files")).absoluteFilePath();
    m_includesFileName = QFileInfo(dir, m_projectName + QLatin1String(".includes")).absoluteFilePath();
    m_configFileName   = QFileInfo(dir, m_projectName + QLatin1String(".config")).absoluteFilePath();
103

104 105 106 107
    m_creatorIDocument  = new GenericProjectFile(this, m_fileName, GenericProject::Everything);
    m_filesIDocument    = new GenericProjectFile(this, m_filesFileName, GenericProject::Files);
    m_includesIDocument = new GenericProjectFile(this, m_includesFileName, GenericProject::Configuration);
    m_configIDocument   = new GenericProjectFile(this, m_configFileName, GenericProject::Configuration);
108

hjk's avatar
hjk committed
109 110 111 112
    DocumentManager::addDocument(m_creatorIDocument);
    DocumentManager::addDocument(m_filesIDocument);
    DocumentManager::addDocument(m_includesIDocument);
    DocumentManager::addDocument(m_configIDocument);
113

114
    m_rootNode = new GenericProjectNode(this, m_creatorIDocument);
115

116
    m_manager->registerProject(this);
Roberto Raggi's avatar
Roberto Raggi committed
117 118 119 120
}

GenericProject::~GenericProject()
{
121
    m_codeModelFuture.cancel();
122
    m_manager->unregisterProject(this);
123

124
    delete m_rootNode;
125 126
}

127
QString GenericProject::filesFileName() const
hjk's avatar
hjk committed
128 129 130
{
    return m_filesFileName;
}
131 132

QString GenericProject::includesFileName() const
hjk's avatar
hjk committed
133 134 135
{
    return m_includesFileName;
}
136 137

QString GenericProject::configFileName() const
hjk's avatar
hjk committed
138 139 140
{
    return m_configFileName;
}
141

142
static QStringList readLines(const QString &absoluteFileName)
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
{
    QStringList lines;

    QFile file(absoluteFileName);
    if (file.open(QFile::ReadOnly)) {
        QTextStream stream(&file);

        forever {
            QString line = stream.readLine();
            if (line.isNull())
                break;

            lines.append(line);
        }
    }

    return lines;
}

162
bool GenericProject::saveRawFileList(const QStringList &rawFileList)
163
{
164
    // Make sure we can open the file for writing
165 166 167 168 169 170 171
    Utils::FileSaver saver(filesFileName(), QIODevice::Text);
    if (!saver.hasError()) {
        QTextStream stream(saver.file());
        foreach (const QString &filePath, rawFileList)
            stream << filePath << QLatin1Char('\n');
        saver.setResult(&stream);
    }
hjk's avatar
hjk committed
172
    if (!saver.finalize(ICore::mainWindow()))
173 174 175
        return false;
    refresh(GenericProject::Files);
    return true;
176
}
177

178 179
bool GenericProject::addFiles(const QStringList &filePaths)
{
180 181 182 183 184
    QStringList newList = m_rawFileList;

    QDir baseDir(QFileInfo(m_fileName).dir());
    foreach (const QString &filePath, filePaths)
        newList.append(baseDir.relativeFilePath(filePath));
185

186
    return saveRawFileList(newList);
187 188 189 190
}

bool GenericProject::removeFiles(const QStringList &filePaths)
{
191
    QStringList newList = m_rawFileList;
192

193 194 195 196
    foreach (const QString &filePath, filePaths) {
        QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
        if (i != m_rawListEntries.end())
            newList.removeOne(i.value());
197
    }
198

199
    return saveRawFileList(newList);
200 201
}

202 203 204 205 206 207 208 209 210 211
bool GenericProject::setFiles(const QStringList &filePaths)
{
    QStringList newList;
    QDir baseDir(QFileInfo(m_fileName).dir());
    foreach (const QString &filePath, filePaths)
        newList.append(baseDir.relativeFilePath(filePath));

    return saveRawFileList(newList);
}

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
bool GenericProject::renameFile(const QString &filePath, const QString &newFilePath)
{
    QStringList newList = m_rawFileList;

    QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
    if (i != m_rawListEntries.end()) {
        int index = newList.indexOf(i.value());
        if (index != -1) {
            QDir baseDir(QFileInfo(m_fileName).dir());
            newList.replace(index, baseDir.relativeFilePath(newFilePath));
        }
    }

    return saveRawFileList(newList);
}

228
void GenericProject::parseProject(RefreshOptions options)
Roberto Raggi's avatar
Roberto Raggi committed
229
{
230 231 232
    if (options & Files) {
        m_rawListEntries.clear();
        m_rawFileList = readLines(filesFileName());
233
        m_files = processEntries(m_rawFileList, &m_rawListEntries);
234
    }
235

236
    if (options & Configuration) {
237
        m_projectIncludePaths = processEntries(readLines(includesFileName()));
238

239 240
        // TODO: Possibly load some configuration from the project file
        //QSettings projectInfo(m_fileName, QSettings::IniFormat);
Roberto Raggi's avatar
Roberto Raggi committed
241

242
        m_defines.clear();
Roberto Raggi's avatar
Roberto Raggi committed
243

244 245 246 247
        QFile configFile(configFileName());
        if (configFile.open(QFile::ReadOnly))
            m_defines = configFile.readAll();
    }
248

249 250
    if (options & Files)
        emit fileListChanged();
Roberto Raggi's avatar
Roberto Raggi committed
251 252
}

253
void GenericProject::refresh(RefreshOptions options)
Roberto Raggi's avatar
Roberto Raggi committed
254
{
255 256 257
    QSet<QString> oldFileList;
    if (!(options & Configuration))
        oldFileList = m_files.toSet();
258

259 260 261
    parseProject(options);

    if (options & Files)
262
        m_rootNode->refresh(oldFileList);
Roberto Raggi's avatar
Roberto Raggi committed
263

264
    CPlusPlus::CppModelManagerInterface *modelManager =
265
        CPlusPlus::CppModelManagerInterface::instance();
Roberto Raggi's avatar
Roberto Raggi committed
266

267
    if (modelManager) {
268
        CPlusPlus::CppModelManagerInterface::ProjectInfo pinfo = modelManager->projectInfo(this);
269 270 271
        pinfo.clearProjectParts();
        CPlusPlus::CppModelManagerInterface::ProjectPart::Ptr part(
                    new CPlusPlus::CppModelManagerInterface::ProjectPart);
Roberto Raggi's avatar
Roberto Raggi committed
272

273
        Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::instance()->defaultKit();
274
        if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
275 276
            QStringList cxxflags; // FIXME: Can we do better?
            part->defines = tc->predefinedMacros(cxxflags);
277
            part->defines += '\n';
Roberto Raggi's avatar
Roberto Raggi committed
278

279
            foreach (const HeaderPath &headerPath, tc->systemHeaderPaths(cxxflags, SysRootKitInformation::sysRoot(k))) {
280
                if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
281
                    part->frameworkPaths.append(headerPath.path());
282
                else
283
                    part->includePaths.append(headerPath.path());
284
            }
Roberto Raggi's avatar
Roberto Raggi committed
285 286
        }

287 288
        part->includePaths += allIncludePaths();
        part->defines += m_defines;
Roberto Raggi's avatar
Roberto Raggi committed
289 290

        // ### add _defines.
291 292

        // Add any C/C++ files to be parsed
293 294 295
        const QList<Core::MimeType> mimeTypes = cppMimeTypes();
        QFileInfo fileInfo;

296
        foreach (const QString &file, files()) {
297 298 299 300 301 302 303
            fileInfo.setFile(file);
            foreach (const Core::MimeType &mimeType, mimeTypes) {
                if (mimeType.matchesFile(fileInfo)) {
                    part->sourceFiles += file;
                    break;
                }
            }
304
        }
Roberto Raggi's avatar
Roberto Raggi committed
305

306 307 308
        QStringList filesToUpdate;

        if (options & Configuration) {
309
            filesToUpdate = part->sourceFiles;
310
            filesToUpdate.append(CPlusPlus::CppModelManagerInterface::configurationFileName());
311 312
            // Full update, if there's a code model update, cancel it
            m_codeModelFuture.cancel();
313 314
        } else if (options & Files) {
            // Only update files that got added to the list
315
            QSet<QString> newFileList = part->sourceFiles.toSet();
316 317 318
            newFileList.subtract(oldFileList);
            filesToUpdate.append(newFileList.toList());
        }
319

320 321
        pinfo.appendProjectPart(part);

Roberto Raggi's avatar
Roberto Raggi committed
322
        modelManager->updateProjectInfo(pinfo);
323
        m_codeModelFuture = modelManager->updateSourceFiles(filesToUpdate);
Roberto Raggi's avatar
Roberto Raggi committed
324 325 326
    }
}

327
/**
328 329 330 331 332
 * Expands environment variables in the given \a string when they are written
 * like $$(VARIABLE).
 */
static void expandEnvironmentVariables(const QProcessEnvironment &env, QString &string)
{
333
    static QRegExp candidate(QLatin1String("\\$\\$\\((.+)\\)"));
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

    int index = candidate.indexIn(string);
    while (index != -1) {
        const QString value = env.value(candidate.cap(1));

        string.replace(index, candidate.matchedLength(), value);
        index += value.length();

        index = candidate.indexIn(string, index);
    }
}

/**
 * Expands environment variables and converts the path from relative to the
 * project to an absolute path.
 *
350
 * The \a map variable is an optional argument that will map the returned
351
 * absolute paths back to their original \a entries.
352
 */
353 354
QStringList GenericProject::processEntries(const QStringList &paths,
                                           QHash<QString, QString> *map) const
Roberto Raggi's avatar
Roberto Raggi committed
355
{
356
    const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
357
    const QDir projectDir(QFileInfo(m_fileName).dir());
358

Roberto Raggi's avatar
Roberto Raggi committed
359
    QStringList absolutePaths;
360
    foreach (const QString &path, paths) {
361 362
        QString trimmedPath = path.trimmed();
        if (trimmedPath.isEmpty())
363 364
            continue;

365 366
        expandEnvironmentVariables(env, trimmedPath);

367 368
        trimmedPath = Utils::FileName::fromUserInput(trimmedPath).toString();

369
        const QString absPath = QFileInfo(projectDir, trimmedPath).absoluteFilePath();
370 371
        absolutePaths.append(absPath);
        if (map)
372
            map->insert(absPath, trimmedPath);
Roberto Raggi's avatar
Roberto Raggi committed
373 374 375 376 377
    }
    absolutePaths.removeDuplicates();
    return absolutePaths;
}

Roberto Raggi's avatar
Roberto Raggi committed
378 379 380
QStringList GenericProject::allIncludePaths() const
{
    QStringList paths;
381 382
    paths += m_includePaths;
    paths += m_projectIncludePaths;
Roberto Raggi's avatar
Roberto Raggi committed
383 384 385 386 387
    paths.removeDuplicates();
    return paths;
}

QStringList GenericProject::projectIncludePaths() const
hjk's avatar
hjk committed
388 389 390
{
    return m_projectIncludePaths;
}
Roberto Raggi's avatar
Roberto Raggi committed
391

Roberto Raggi's avatar
Roberto Raggi committed
392
QStringList GenericProject::files() const
hjk's avatar
hjk committed
393 394 395
{
    return m_files;
}
Roberto Raggi's avatar
Roberto Raggi committed
396 397

QStringList GenericProject::includePaths() const
hjk's avatar
hjk committed
398 399 400
{
    return m_includePaths;
}
Roberto Raggi's avatar
Roberto Raggi committed
401 402

void GenericProject::setIncludePaths(const QStringList &includePaths)
hjk's avatar
hjk committed
403 404 405
{
    m_includePaths = includePaths;
}
Roberto Raggi's avatar
Roberto Raggi committed
406

Roberto Raggi's avatar
Roberto Raggi committed
407
QByteArray GenericProject::defines() const
hjk's avatar
hjk committed
408 409 410
{
    return m_defines;
}
Roberto Raggi's avatar
Roberto Raggi committed
411

412
QString GenericProject::displayName() const
Roberto Raggi's avatar
Roberto Raggi committed
413
{
414
    return m_projectName;
Roberto Raggi's avatar
Roberto Raggi committed
415 416
}

hjk's avatar
hjk committed
417
Id GenericProject::id() const
Tobias Hunger's avatar
Tobias Hunger committed
418
{
hjk's avatar
hjk committed
419
    return Id(Constants::GENERICPROJECT_ID);
Tobias Hunger's avatar
Tobias Hunger committed
420 421
}

hjk's avatar
hjk committed
422
IDocument *GenericProject::document() const
Roberto Raggi's avatar
Roberto Raggi committed
423
{
424
    return m_creatorIDocument;
Roberto Raggi's avatar
Roberto Raggi committed
425 426
}

427
IProjectManager *GenericProject::projectManager() const
Roberto Raggi's avatar
Roberto Raggi committed
428
{
429
    return m_manager;
Roberto Raggi's avatar
Roberto Raggi committed
430 431
}

432
GenericProjectNode *GenericProject::rootProjectNode() const
Roberto Raggi's avatar
Roberto Raggi committed
433
{
434
    return m_rootNode;
Roberto Raggi's avatar
Roberto Raggi committed
435 436 437 438
}

QStringList GenericProject::files(FilesMode fileMode) const
{
439
    Q_UNUSED(fileMode)
440
    return m_files;
Roberto Raggi's avatar
Roberto Raggi committed
441 442
}

Tobias Hunger's avatar
Tobias Hunger committed
443
QStringList GenericProject::buildTargets() const
Roberto Raggi's avatar
Roberto Raggi committed
444 445 446 447 448 449 450
{
    QStringList targets;
    targets.append(QLatin1String("all"));
    targets.append(QLatin1String("clean"));
    return targets;
}

451 452 453 454
bool GenericProject::fromMap(const QVariantMap &map)
{
    if (!Project::fromMap(map))
        return false;
Roberto Raggi's avatar
Roberto Raggi committed
455

Tobias Hunger's avatar
Tobias Hunger committed
456 457 458
    Kit *defaultKit = KitManager::instance()->defaultKit();
    if (!activeTarget() && defaultKit)
        addTarget(createTarget(defaultKit));
Tobias Hunger's avatar
Tobias Hunger committed
459

460 461 462 463 464 465 466 467 468
    // Sanity check: We need both a buildconfiguration and a runconfiguration!
    QList<Target *> targetList = targets();
    foreach (Target *t, targetList) {
        if (!t->activeBuildConfiguration()) {
            removeTarget(t);
            delete t;
            continue;
        }
        if (!t->activeRunConfiguration())
469
            t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
470 471
    }

Roberto Raggi's avatar
Roberto Raggi committed
472
    setIncludePaths(allIncludePaths());
473

Tobias Hunger's avatar
Tobias Hunger committed
474
    refresh(Everything);
475
    return true;
476 477
}

Roberto Raggi's avatar
Roberto Raggi committed
478
////////////////////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
479
//
Roberto Raggi's avatar
Roberto Raggi committed
480
// GenericProjectFile
hjk's avatar
hjk committed
481
//
Roberto Raggi's avatar
Roberto Raggi committed
482
////////////////////////////////////////////////////////////////////////////////////
483

484
GenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)
hjk's avatar
hjk committed
485
    : IDocument(parent),
486
      m_project(parent),
487 488
      m_fileName(fileName),
      m_options(options)
Roberto Raggi's avatar
Roberto Raggi committed
489 490
{ }

491
bool GenericProjectFile::save(QString *, const QString &, bool)
Roberto Raggi's avatar
Roberto Raggi committed
492 493 494 495 496 497
{
    return false;
}

QString GenericProjectFile::fileName() const
{
498
    return m_fileName;
Roberto Raggi's avatar
Roberto Raggi committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512
}

QString GenericProjectFile::defaultPath() const
{
    return QString();
}

QString GenericProjectFile::suggestedFileName() const
{
    return QString();
}

QString GenericProjectFile::mimeType() const
{
513
    return QLatin1String(Constants::GENERICMIMETYPE);
Roberto Raggi's avatar
Roberto Raggi committed
514 515 516 517 518 519 520 521 522 523 524 525
}

bool GenericProjectFile::isModified() const
{
    return false;
}

bool GenericProjectFile::isSaveAsAllowed() const
{
    return false;
}

dt's avatar
dt committed
526 527 528 529
void GenericProjectFile::rename(const QString &newName)
{
    // Can't happen
    Q_UNUSED(newName);
530
    QTC_CHECK(false);
dt's avatar
dt committed
531 532
}

hjk's avatar
hjk committed
533
IDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
Roberto Raggi's avatar
Roberto Raggi committed
534
{
535 536 537 538 539
    Q_UNUSED(state)
    Q_UNUSED(type)
    return BehaviorSilent;
}

540
bool GenericProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
541
{
542
    Q_UNUSED(errorString)
543
    Q_UNUSED(flag)
544 545 546
    if (type == TypePermissions)
        return true;
    m_project->refresh(m_options);
547
    return true;
Roberto Raggi's avatar
Roberto Raggi committed
548
}
hjk's avatar
hjk committed
549 550 551

} // namespace Internal
} // namespace GenericProjectManager