cpptoolsplugin.cpp 14.7 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con 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
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 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.
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
****************************************************************************/
hjk's avatar
hjk committed
29

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

46
#include <coreplugin/actionmanager/actioncontainer.h>
47 48 49 50
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
51
#include <coreplugin/vcsmanager.h>
con's avatar
con committed
52
#include <cppeditor/cppeditorconstants.h>
53

54
#include <utils/hostosinfo.h>
55
#include <utils/qtcassert.h>
56 57 58
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
59

60 61 62 63 64 65
#include <QtPlugin>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QMenu>
#include <QAction>
66

hjk's avatar
hjk committed
67
using namespace Core;
68
using namespace CPlusPlus;
con's avatar
con committed
69

70 71 72
namespace CppTools {
namespace Internal {

con's avatar
con committed
73 74
enum { debug = 0 };

75
static CppToolsPlugin *m_instance = 0;
76
static QHash<QString, QString> m_headerSourceMapping;
con's avatar
con committed
77

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

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
88
    delete CppModelManager::instance();
con's avatar
con committed
89 90
}

91 92 93 94 95
CppToolsPlugin *CppToolsPlugin::instance()
{
    return m_instance;
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
void CppToolsPlugin::clearHeaderSourceCache()
{
    m_headerSourceMapping.clear();
}

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

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

111
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
112
{
113 114
    Q_UNUSED(arguments)
    Q_UNUSED(error)
115

116 117
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

con's avatar
con committed
118
    // Objects
119
    CppModelManager *modelManager = CppModelManager::instance();
hjk's avatar
hjk committed
120
    connect(VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
121
            modelManager, SLOT(updateModifiedSourceFiles()));
hjk's avatar
hjk committed
122
    connect(DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
123
            modelManager, SLOT(updateSourceFiles(QStringList)));
Roberto Raggi's avatar
Roberto Raggi committed
124

125 126 127 128 129
    CppLocatorData *locatorData = new CppLocatorData(modelManager);
    addAutoReleasedObject(locatorData);
    addAutoReleasedObject(new CppLocatorFilter(locatorData));
    addAutoReleasedObject(new CppClassesFilter(locatorData));
    addAutoReleasedObject(new CppFunctionsFilter(locatorData));
130
    addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager));
131
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
132
//    addAutoReleasedObject(new CppCodeModelSettingsPage(m_codeModelSettings));
133
    addAutoReleasedObject(new SymbolsFindFilter(modelManager));
134 135
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
136
    // Menus
hjk's avatar
hjk committed
137 138
    ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
    ActionContainer *mcpptools = ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
139 140 141 142 143 144
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
hjk's avatar
hjk committed
145
    Context context(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
146 147

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

153
    QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
hjk's avatar
hjk committed
154
    command = ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
155 156 157
    command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
                                                ? tr("Meta+E, F4")
                                                : tr("Ctrl+E, F4")));
158 159 160
    mcpptools->addAction(command);
    connect(openInNextSplitAction, SIGNAL(triggered()), this, SLOT(switchHeaderSourceInNextSplit()));

con's avatar
con committed
161 162 163 164 165
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
166 167
    // The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
    // so, apply settings here
hjk's avatar
hjk committed
168
    m_fileSettings->fromSettings(ICore::settings());
169 170
    if (!m_fileSettings->applySuffixesToMimeDB())
        qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
171
    m_codeModelSettings->fromSettings(ICore::settings());
con's avatar
con committed
172 173
}

174
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
175
{
176
    return SynchronousShutdown;
177 178
}

179 180 181 182 183
QSharedPointer<CppCodeModelSettings> CppToolsPlugin::codeModelSettings() const
{
    return m_codeModelSettings;
}

con's avatar
con committed
184 185
void CppToolsPlugin::switchHeaderSource()
{
186
    QString otherFile = correspondingHeaderOrSource(
hjk's avatar
hjk committed
187
                EditorManager::currentDocument()->filePath());
188
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
189
        EditorManager::openEditor(otherFile);
190 191 192 193 194
}

void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
    QString otherFile = correspondingHeaderOrSource(
hjk's avatar
hjk committed
195
                EditorManager::currentDocument()->filePath());
196
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
197
        EditorManager::openEditor(otherFile, Id(), EditorManager::OpenInOtherSplit);
con's avatar
con committed
198 199
}

200
static QStringList findFilesInProject(const QString &name,
201
                                   const ProjectExplorer::Project *project)
con's avatar
con committed
202 203
{
    if (debug)
204 205 206
        qDebug() << Q_FUNC_INFO << name << project;

    if (!project)
207
        return QStringList();
208 209 210 211 212

    QString pattern = QString(1, QLatin1Char('/'));
    pattern += name;
    const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
    const QStringList::const_iterator pcend = projectFiles.constEnd();
213
    QStringList candidateList;
214 215
    for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it) {
        if (it->endsWith(pattern))
216
            candidateList.append(*it);
con's avatar
con committed
217
    }
218
    return candidateList;
con's avatar
con committed
219 220 221 222
}

// Return the suffixes that should be checked when trying to find a
// source belonging to a header and vice versa
223
static QStringList matchingCandidateSuffixes(ProjectFile::Kind kind)
con's avatar
con committed
224
{
225 226 227 228 229 230
    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
231 232 233 234
        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();
235 236
    case ProjectFile::CSource:
    case ProjectFile::ObjCSource:
hjk's avatar
hjk committed
237
        return MimeDatabase::findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes();
238 239 240 241
    case ProjectFile::CXXSource:
    case ProjectFile::ObjCXXSource:
    case ProjectFile::CudaSource:
    case ProjectFile::OpenCLSource:
hjk's avatar
hjk committed
242
        return MimeDatabase::findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes();
243 244
    default:
        return QStringList();
con's avatar
con committed
245 246 247
    }
}

248 249 250 251 252 253 254 255 256 257 258 259 260
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;
}

261 262 263 264 265 266 267 268
static QStringList baseDirWithAllDirectories(const QDir &baseDir, const QStringList &directories)
{
    QStringList result;
    foreach (const QString &dir, directories)
        result << QDir::cleanPath(baseDir.absoluteFilePath(dir));
    return result;
}

269 270 271 272 273 274 275 276 277
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;
}

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

307 308 309
} // namespace Internal

QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
con's avatar
con committed
310
{
311
    using namespace Internal;
312

313
    const QFileInfo fi(fileName);
314 315
    ProjectFile::Kind kind = ProjectFile::classify(fileName);
    const bool isHeader = ProjectFile::isHeader(kind);
316
    if (wasHeader)
317 318
        *wasHeader = isHeader;
    if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
319
        return m_headerSourceMapping.value(fi.absoluteFilePath());
con's avatar
con committed
320 321

    if (debug)
322
        qDebug() << Q_FUNC_INFO << fileName <<  kind;
con's avatar
con committed
323

324
    if (kind == ProjectFile::Unclassified)
con's avatar
con committed
325 326
        return QString();

327
    const QString baseName = fi.completeBaseName();
328
    const QString privateHeaderSuffix = QLatin1String("_p");
329
    const QStringList suffixes = matchingCandidateSuffixes(kind);
con's avatar
con committed
330

331
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
332
    if (isHeader) {
con's avatar
con committed
333 334 335
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
336
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
337 338
        }
    } else {
339 340 341 342 343 344
        QString privateHeaderBaseName = baseName;
        privateHeaderBaseName.append(privateHeaderSuffix);
        candidateFileNames += baseNameWithAllSuffixes(privateHeaderBaseName, suffixes);
    }

    const QDir absoluteDir = fi.absoluteDir();
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    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);

    // 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;
#ifdef Q_OS_WIN
            const QString normalized = Utils::normalizePathName(candidateFilePath);
#else
            const QString normalized = candidateFilePath;
#endif
            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();
            }
367
        }
368 369
    }

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    // Find files in the current project
    ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject();
    if (currentProject) {
        const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames,
                                                                  currentProject);
        if (!path.isEmpty())
            return path;
    }

    // Find files in other projects
    CppModelManager *modelManager = CppModelManager::instance();
    QList<CppModelManagerInterface::ProjectInfo> projectInfos = modelManager->projectInfos();
    foreach (const CppModelManagerInterface::ProjectInfo &projectInfo, projectInfos) {
        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
390
    }
391

con's avatar
con committed
392 393 394
    return QString();
}

395
} // namespace CppTools
con's avatar
con committed
396

397
Q_EXPORT_PLUGIN(CppTools::Internal::CppToolsPlugin)