cpptoolsplugin.cpp 17 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12
** 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
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24 25 26
**
** 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
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

31
#include "cpptoolsconstants.h"
32
#include "cpptoolsplugin.h"
33
#include "cppfilesettingspage.h"
34
#include "cppcodemodelsettingspage.h"
35
#include "cppcodestylesettingspage.h"
36
#include "cppclassesfilter.h"
37
#include "cppfunctionsfilter.h"
38
#include "cppcurrentdocumentfilter.h"
con's avatar
con committed
39
#include "cppmodelmanager.h"
con's avatar
con committed
40
#include "cpplocatorfilter.h"
41
#include "symbolsfindfilter.h"
42
#include "cpptoolsjsextension.h"
43
#include "cpptoolssettings.h"
44
#include "cpptoolsreuse.h"
45
#include "cppprojectfile.h"
46
#include "cpplocatordata.h"
con's avatar
con committed
47

48
#include <coreplugin/actionmanager/actioncontainer.h>
49 50 51 52
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
53
#include <coreplugin/jsexpander.h>
54
#include <coreplugin/vcsmanager.h>
con's avatar
con committed
55
#include <cppeditor/cppeditorconstants.h>
56
#include <projectexplorer/projecttree.h>
57

Orgad Shaneh's avatar
Orgad Shaneh committed
58
#include <utils/fileutils.h>
59
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
60
#include <utils/macroexpander.h>
61
#include <utils/qtcassert.h>
62

63 64 65 66 67 68
#include <QtPlugin>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QMenu>
#include <QAction>
69

hjk's avatar
hjk committed
70
using namespace Core;
71
using namespace CPlusPlus;
con's avatar
con committed
72

73 74 75
namespace CppTools {
namespace Internal {

con's avatar
con committed
76 77
enum { debug = 0 };

78
static CppToolsPlugin *m_instance = 0;
79
static QHash<QString, QString> m_headerSourceMapping;
con's avatar
con committed
80

81 82 83
CppToolsPlugin::CppToolsPlugin()
    : m_fileSettings(new CppFileSettings)
    , m_codeModelSettings(new CppCodeModelSettings)
con's avatar
con committed
84 85 86 87 88 89 90
{
    m_instance = this;
}

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
91
    delete CppModelManager::instance();
con's avatar
con committed
92 93
}

94 95 96 97 98
CppToolsPlugin *CppToolsPlugin::instance()
{
    return m_instance;
}

99 100 101 102 103
void CppToolsPlugin::clearHeaderSourceCache()
{
    m_headerSourceMapping.clear();
}

104 105 106 107 108 109 110 111 112 113
Utils::FileName CppToolsPlugin::licenseTemplatePath()
{
    return Utils::FileName::fromString(m_instance->m_fileSettings->licenseTemplatePath);
}

QString CppToolsPlugin::licenseTemplate()
{
    return m_instance->m_fileSettings->licenseTemplate();
}

114 115 116 117 118 119 120 121 122 123
const QStringList &CppToolsPlugin::headerSearchPaths()
{
    return m_instance->m_fileSettings->headerSearchPaths;
}

const QStringList &CppToolsPlugin::sourceSearchPaths()
{
    return m_instance->m_fileSettings->sourceSearchPaths;
}

124 125 126 127 128 129 130 131 132 133 134
const QStringList &CppToolsPlugin::headerPrefixes()
{
    return m_instance->m_fileSettings->headerPrefixes;
}

const QStringList &CppToolsPlugin::sourcePrefixes()
{
    return m_instance->m_fileSettings->sourcePrefixes;
}


135
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
136
{
137 138
    Q_UNUSED(arguments)
    Q_UNUSED(error)
139

140 141
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

con's avatar
con committed
142
    // Objects
143
    CppModelManager *modelManager = CppModelManager::instance();
hjk's avatar
hjk committed
144
    connect(VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
145
            modelManager, SLOT(updateModifiedSourceFiles()));
146 147 148 149
    connect(DocumentManager::instance(), &DocumentManager::filesChangedInternally,
            [=](const QStringList &files) {
        modelManager->updateSourceFiles(files.toSet());
    });
Roberto Raggi's avatar
Roberto Raggi committed
150

151
    JsExpander::registerQObjectForJs(QLatin1String("Cpp"), new CppToolsJsExtension);
152

153 154 155 156 157 158 159
    CppLocatorData *locatorData = new CppLocatorData;
    connect(modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
            locatorData, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));

    connect(modelManager, SIGNAL(aboutToRemoveFiles(QStringList)),
            locatorData, SLOT(onAboutToRemoveFiles(QStringList)));

160 161 162 163
    addAutoReleasedObject(locatorData);
    addAutoReleasedObject(new CppLocatorFilter(locatorData));
    addAutoReleasedObject(new CppClassesFilter(locatorData));
    addAutoReleasedObject(new CppFunctionsFilter(locatorData));
164
    addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, m_stringTable));
165
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
166
    addAutoReleasedObject(new CppCodeModelSettingsPage(m_codeModelSettings));
167
    addAutoReleasedObject(new SymbolsFindFilter(modelManager));
168 169
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
170
    // Menus
hjk's avatar
hjk committed
171 172
    ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
    ActionContainer *mcpptools = ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
173 174 175 176 177 178
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
179
    Context context(CppEditor::Constants::CPPEDITOR_ID);
con's avatar
con committed
180 181

    QAction *switchAction = new QAction(tr("Switch Header/Source"), this);
hjk's avatar
hjk committed
182
    Command *command = ActionManager::registerAction(switchAction, Constants::SWITCH_HEADER_SOURCE, context, true);
con's avatar
con committed
183 184 185 186
    command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
    mcpptools->addAction(command);
    connect(switchAction, SIGNAL(triggered()), this, SLOT(switchHeaderSource()));

187
    QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
hjk's avatar
hjk committed
188
    command = ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
189 190 191
    command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
                                                ? tr("Meta+E, F4")
                                                : tr("Ctrl+E, F4")));
192 193 194
    mcpptools->addAction(command);
    connect(openInNextSplitAction, SIGNAL(triggered()), this, SLOT(switchHeaderSourceInNextSplit()));

hjk's avatar
hjk committed
195
    Utils::MacroExpander *expander = Utils::globalMacroExpander();
196 197 198 199 200 201
    expander->registerVariable("Cpp:LicenseTemplate",
                               tr("The license template."),
                               [this]() { return CppToolsPlugin::licenseTemplate(); });
    expander->registerFileVariables("Cpp:LicenseTemplatePath",
                                    tr("The configured path to the license template"),
                                    [this]() { return CppToolsPlugin::licenseTemplatePath().toString(); });
202

con's avatar
con committed
203 204 205 206 207
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
208 209
    // The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
    // so, apply settings here
hjk's avatar
hjk committed
210
    m_fileSettings->fromSettings(ICore::settings());
211 212
    if (!m_fileSettings->applySuffixesToMimeDB())
        qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
213
    m_codeModelSettings->fromSettings(ICore::settings());
con's avatar
con committed
214 215
}

216
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
217
{
218
    return SynchronousShutdown;
219 220
}

221 222 223 224 225
QSharedPointer<CppCodeModelSettings> CppToolsPlugin::codeModelSettings() const
{
    return m_codeModelSettings;
}

226 227 228 229 230
StringTable &CppToolsPlugin::stringTable()
{
    return instance()->m_stringTable;
}

con's avatar
con committed
231 232
void CppToolsPlugin::switchHeaderSource()
{
233
    CppTools::switchHeaderSource();
234 235 236 237 238
}

void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
    QString otherFile = correspondingHeaderOrSource(
hjk's avatar
hjk committed
239
                EditorManager::currentDocument()->filePath());
240
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
241
        EditorManager::openEditor(otherFile, Id(), EditorManager::OpenInOtherSplit);
con's avatar
con committed
242 243
}

244
static QStringList findFilesInProject(const QString &name,
245
                                   const ProjectExplorer::Project *project)
con's avatar
con committed
246 247
{
    if (debug)
248 249 250
        qDebug() << Q_FUNC_INFO << name << project;

    if (!project)
251
        return QStringList();
252 253 254 255 256

    QString pattern = QString(1, QLatin1Char('/'));
    pattern += name;
    const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
    const QStringList::const_iterator pcend = projectFiles.constEnd();
257
    QStringList candidateList;
258 259
    for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it) {
        if (it->endsWith(pattern))
260
            candidateList.append(*it);
con's avatar
con committed
261
    }
262
    return candidateList;
con's avatar
con committed
263 264 265 266
}

// Return the suffixes that should be checked when trying to find a
// source belonging to a header and vice versa
267
static QStringList matchingCandidateSuffixes(ProjectFile::Kind kind)
con's avatar
con committed
268
{
269 270 271 272 273 274
    switch (kind) {
     // Note that C/C++ headers are undistinguishable
    case ProjectFile::CHeader:
    case ProjectFile::CXXHeader:
    case ProjectFile::ObjCHeader:
    case ProjectFile::ObjCXXHeader:
hjk's avatar
hjk committed
275 276 277 278
        return MimeDatabase::findByType(QLatin1String(Constants::C_SOURCE_MIMETYPE)).suffixes()
                + MimeDatabase::findByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)).suffixes()
                + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE)).suffixes()
                + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
279 280
    case ProjectFile::CSource:
    case ProjectFile::ObjCSource:
hjk's avatar
hjk committed
281
        return MimeDatabase::findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes();
282 283 284 285
    case ProjectFile::CXXSource:
    case ProjectFile::ObjCXXSource:
    case ProjectFile::CudaSource:
    case ProjectFile::OpenCLSource:
hjk's avatar
hjk committed
286
        return MimeDatabase::findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes();
287 288
    default:
        return QStringList();
con's avatar
con committed
289 290 291
    }
}

292 293 294 295 296 297 298 299 300 301 302 303 304
static QStringList baseNameWithAllSuffixes(const QString &baseName, const QStringList &suffixes)
{
    QStringList result;
    const QChar dot = QLatin1Char('.');
    foreach (const QString &suffix, suffixes) {
        QString fileName = baseName;
        fileName += dot;
        fileName += suffix;
        result += fileName;
    }
    return result;
}

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static QStringList baseNamesWithAllPrefixes(const QStringList &baseNames, bool isHeader)
{
    QStringList result;
    const QStringList &sourcePrefixes = m_instance->sourcePrefixes();
    const QStringList &headerPrefixes = m_instance->headerPrefixes();

    foreach (const QString &name, baseNames) {
        foreach (const QString &prefix, isHeader ? headerPrefixes : sourcePrefixes) {
            if (name.startsWith(prefix)) {
                QString nameWithoutPrefix = name.mid(prefix.size());
                result += nameWithoutPrefix;
                foreach (const QString &prefix, isHeader ? sourcePrefixes : headerPrefixes)
                    result += prefix + nameWithoutPrefix;
            }
        }
        foreach (const QString &prefix, isHeader ? sourcePrefixes : headerPrefixes)
            result += prefix + name;

    }
    return result;
}

327 328 329 330 331 332 333 334
static QStringList baseDirWithAllDirectories(const QDir &baseDir, const QStringList &directories)
{
    QStringList result;
    foreach (const QString &dir, directories)
        result << QDir::cleanPath(baseDir.absoluteFilePath(dir));
    return result;
}

335 336 337 338 339 340 341 342 343
static int commonStringLength(const QString &s1, const QString &s2)
{
    int length = qMin(s1.length(), s2.length());
    for (int i = 0; i < length; ++i)
        if (s1[i] != s2[i])
            return i;
    return length;
}

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
static QString correspondingHeaderOrSourceInProject(const QFileInfo &fileInfo,
                                                    const QStringList &candidateFileNames,
                                                    const ProjectExplorer::Project *project)
{
    QString bestFileName;
    int compareValue = 0;
    const QString filePath = fileInfo.filePath();
    foreach (const QString &candidateFileName, candidateFileNames) {
        const QStringList projectFiles = findFilesInProject(candidateFileName, project);
        // Find the file having the most common path with fileName
        foreach (const QString &projectFile, projectFiles) {
            int value = commonStringLength(filePath, projectFile);
            if (value > compareValue) {
                compareValue = value;
                bestFileName = projectFile;
            }
        }
    }
    if (!bestFileName.isEmpty()) {
        const QFileInfo candidateFi(bestFileName);
        QTC_ASSERT(candidateFi.isFile(), return QString());
        m_headerSourceMapping[fileInfo.absoluteFilePath()] = candidateFi.absoluteFilePath();
        m_headerSourceMapping[candidateFi.absoluteFilePath()] = fileInfo.absoluteFilePath();
        return candidateFi.absoluteFilePath();
    }

    return QString();
}

373 374 375
} // namespace Internal

QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
con's avatar
con committed
376
{
377
    using namespace Internal;
378

379
    const QFileInfo fi(fileName);
380 381
    ProjectFile::Kind kind = ProjectFile::classify(fileName);
    const bool isHeader = ProjectFile::isHeader(kind);
382
    if (wasHeader)
383 384
        *wasHeader = isHeader;
    if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
385
        return m_headerSourceMapping.value(fi.absoluteFilePath());
con's avatar
con committed
386 387

    if (debug)
388
        qDebug() << Q_FUNC_INFO << fileName <<  kind;
con's avatar
con committed
389

390
    if (kind == ProjectFile::Unclassified)
con's avatar
con committed
391 392
        return QString();

393
    const QString baseName = fi.completeBaseName();
394
    const QString privateHeaderSuffix = QLatin1String("_p");
395
    const QStringList suffixes = matchingCandidateSuffixes(kind);
con's avatar
con committed
396

397
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
398
    if (isHeader) {
con's avatar
con committed
399 400 401
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
402
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
403 404
        }
    } else {
405 406 407 408 409 410
        QString privateHeaderBaseName = baseName;
        privateHeaderBaseName.append(privateHeaderSuffix);
        candidateFileNames += baseNameWithAllSuffixes(privateHeaderBaseName, suffixes);
    }

    const QDir absoluteDir = fi.absoluteDir();
411 412 413 414 415 416
    QStringList candidateDirs(absoluteDir.absolutePath());
    // If directory is not root, try matching against its siblings
    const QStringList searchPaths = isHeader ? m_instance->sourceSearchPaths()
                                             : m_instance->headerSearchPaths();
    candidateDirs += baseDirWithAllDirectories(absoluteDir, searchPaths);

417 418
    candidateFileNames += baseNamesWithAllPrefixes(candidateFileNames, isHeader);

419 420 421 422
    // Try to find a file in the same or sibling directories first
    foreach (const QString &candidateDir, candidateDirs) {
        foreach (const QString &candidateFileName, candidateFileNames) {
            const QString candidateFilePath = candidateDir + QLatin1Char('/') + candidateFileName;
Orgad Shaneh's avatar
Orgad Shaneh committed
423
            const QString normalized = Utils::FileUtils::normalizePathName(candidateFilePath);
424 425 426 427 428 429 430
            const QFileInfo candidateFi(normalized);
            if (candidateFi.isFile()) {
                m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
                if (!isHeader || !baseName.endsWith(privateHeaderSuffix))
                    m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
                return candidateFi.absoluteFilePath();
            }
431
        }
432 433
    }

434
    // Find files in the current project
435
    ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectTree::currentProject();
436 437 438 439 440 441 442
    if (currentProject) {
        const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames,
                                                                  currentProject);
        if (!path.isEmpty())
            return path;

    // Find files in other projects
443 444
    } else {
        CppModelManager *modelManager = CppModelManager::instance();
445 446
        QList<ProjectInfo> projectInfos = modelManager->projectInfos();
        foreach (const ProjectInfo &projectInfo, projectInfos) {
447 448 449 450 451 452 453 454
            const ProjectExplorer::Project *project = projectInfo.project().data();
            if (project == currentProject)
                continue; // We have already checked the current project.

            const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames, project);
            if (!path.isEmpty())
                return path;
        }
con's avatar
con committed
455
    }
456

con's avatar
con committed
457 458 459
    return QString();
}

460
} // namespace CppTools