cpptoolsplugin.cpp 13.1 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 "cppcodestylesettingspage.h"
34
#include "cppclassesfilter.h"
35
#include "cppfunctionsfilter.h"
36
#include "cppcurrentdocumentfilter.h"
con's avatar
con committed
37
#include "cppmodelmanager.h"
con's avatar
con committed
38
#include "cpplocatorfilter.h"
39
#include "symbolsfindfilter.h"
40
#include "cpptoolssettings.h"
41
#include "cpptoolsreuse.h"
42
#include "cppprojectfile.h"
43
#include "cpplocatordata.h"
con's avatar
con committed
44

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

53
#include <utils/hostosinfo.h>
54
#include <utils/qtcassert.h>
55

56 57 58 59 60 61
#include <QtPlugin>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QMenu>
#include <QAction>
62

hjk's avatar
hjk committed
63
using namespace Core;
64
using namespace CPlusPlus;
con's avatar
con committed
65

66 67 68
namespace CppTools {
namespace Internal {

con's avatar
con committed
69 70
enum { debug = 0 };

71
static CppToolsPlugin *m_instance = 0;
72
static QHash<QString, QString> m_headerSourceMapping;
con's avatar
con committed
73

74 75
CppToolsPlugin::CppToolsPlugin() :
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
76 77 78 79 80 81 82
{
    m_instance = this;
}

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
83
    delete CppModelManager::instance();
con's avatar
con committed
84 85
}

86 87 88 89 90
CppToolsPlugin *CppToolsPlugin::instance()
{
    return m_instance;
}

91
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
92
{
93 94
    Q_UNUSED(arguments)
    Q_UNUSED(error)
95

96 97
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

con's avatar
con committed
98
    // Objects
99
    CppModelManager *modelManager = CppModelManager::instance();
hjk's avatar
hjk committed
100
    VcsManager *vcsManager = ICore::vcsManager();
101
    connect(vcsManager, SIGNAL(repositoryChanged(QString)),
102
            modelManager, SLOT(updateModifiedSourceFiles()));
hjk's avatar
hjk committed
103
    connect(DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
104
            modelManager, SLOT(updateSourceFiles(QStringList)));
Roberto Raggi's avatar
Roberto Raggi committed
105

106 107 108 109 110
    CppLocatorData *locatorData = new CppLocatorData(modelManager);
    addAutoReleasedObject(locatorData);
    addAutoReleasedObject(new CppLocatorFilter(locatorData));
    addAutoReleasedObject(new CppClassesFilter(locatorData));
    addAutoReleasedObject(new CppFunctionsFilter(locatorData));
111
    addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager));
112
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
113
    addAutoReleasedObject(new SymbolsFindFilter(modelManager));
114 115
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
116
    // Menus
hjk's avatar
hjk committed
117 118
    ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
    ActionContainer *mcpptools = ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
119 120 121 122 123 124
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
hjk's avatar
hjk committed
125
    Context context(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
126 127

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

133
    QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
hjk's avatar
hjk committed
134
    command = ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
135 136 137
    command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
                                                ? tr("Meta+E, F4")
                                                : tr("Ctrl+E, F4")));
138 139 140
    mcpptools->addAction(command);
    connect(openInNextSplitAction, SIGNAL(triggered()), this, SLOT(switchHeaderSourceInNextSplit()));

con's avatar
con committed
141 142 143 144 145
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
146 147
    // The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
    // so, apply settings here
hjk's avatar
hjk committed
148
    m_fileSettings->fromSettings(ICore::settings());
149 150
    if (!m_fileSettings->applySuffixesToMimeDB())
        qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
con's avatar
con committed
151 152
}

153
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
154
{
155
    return SynchronousShutdown;
156 157
}

con's avatar
con committed
158 159
void CppToolsPlugin::switchHeaderSource()
{
160
    QString otherFile = correspondingHeaderOrSource(
hjk's avatar
hjk committed
161
                EditorManager::currentDocument()->filePath());
162
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
163
        EditorManager::openEditor(otherFile);
164 165 166 167 168
}

void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
    QString otherFile = correspondingHeaderOrSource(
hjk's avatar
hjk committed
169
                EditorManager::currentDocument()->filePath());
170
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
171
        EditorManager::openEditor(otherFile, Id(), EditorManager::OpenInOtherSplit);
con's avatar
con committed
172 173
}

174
static QStringList findFilesInProject(const QString &name,
175
                                   const ProjectExplorer::Project *project)
con's avatar
con committed
176 177
{
    if (debug)
178 179 180
        qDebug() << Q_FUNC_INFO << name << project;

    if (!project)
181
        return QStringList();
182 183 184 185 186

    QString pattern = QString(1, QLatin1Char('/'));
    pattern += name;
    const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
    const QStringList::const_iterator pcend = projectFiles.constEnd();
187
    QStringList candidateList;
188 189
    for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it) {
        if (it->endsWith(pattern))
190
            candidateList.append(*it);
con's avatar
con committed
191
    }
192
    return candidateList;
con's avatar
con committed
193 194 195 196
}

// Return the suffixes that should be checked when trying to find a
// source belonging to a header and vice versa
197
static QStringList matchingCandidateSuffixes(ProjectFile::Kind kind)
con's avatar
con committed
198
{
199 200 201 202 203 204
    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
205 206 207 208
        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();
209 210
    case ProjectFile::CSource:
    case ProjectFile::ObjCSource:
hjk's avatar
hjk committed
211
        return MimeDatabase::findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes();
212 213 214 215
    case ProjectFile::CXXSource:
    case ProjectFile::ObjCXXSource:
    case ProjectFile::CudaSource:
    case ProjectFile::OpenCLSource:
hjk's avatar
hjk committed
216
        return MimeDatabase::findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes();
217 218
    default:
        return QStringList();
con's avatar
con committed
219 220 221
    }
}

222 223 224 225 226 227 228 229 230 231 232 233 234
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;
}

235 236 237 238 239 240 241 242 243
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;
}

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

273 274 275
} // namespace Internal

QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
con's avatar
con committed
276
{
277
    using namespace Internal;
278

279
    const QFileInfo fi(fileName);
280 281
    ProjectFile::Kind kind = ProjectFile::classify(fileName);
    const bool isHeader = ProjectFile::isHeader(kind);
282
    if (wasHeader)
283 284
        *wasHeader = isHeader;
    if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
285
        return m_headerSourceMapping.value(fi.absoluteFilePath());
con's avatar
con committed
286 287

    if (debug)
288
        qDebug() << Q_FUNC_INFO << fileName <<  kind;
con's avatar
con committed
289

290
    if (kind == ProjectFile::Unclassified)
con's avatar
con committed
291 292
        return QString();

293
    const QString baseName = fi.completeBaseName();
294
    const QString privateHeaderSuffix = QLatin1String("_p");
295
    const QStringList suffixes = matchingCandidateSuffixes(kind);
con's avatar
con committed
296

297
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
298
    if (isHeader) {
con's avatar
con committed
299 300 301
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
302
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
303 304
        }
    } else {
305 306 307 308 309 310 311 312
        QString privateHeaderBaseName = baseName;
        privateHeaderBaseName.append(privateHeaderSuffix);
        candidateFileNames += baseNameWithAllSuffixes(privateHeaderBaseName, suffixes);
    }

    const QDir absoluteDir = fi.absoluteDir();

    // Try to find a file in the same directory first
313 314
    foreach (const QString &candidateFileName, candidateFileNames) {
        const QFileInfo candidateFi(absoluteDir, candidateFileName);
315 316
        if (candidateFi.isFile()) {
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
317
            if (!isHeader || !baseName.endsWith(privateHeaderSuffix))
318
                m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
319
            return candidateFi.absoluteFilePath();
320
        }
321 322
    }

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    // 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
343
    }
344

con's avatar
con committed
345 346 347
    return QString();
}

348
} // namespace CppTools
con's avatar
con committed
349

350
Q_EXPORT_PLUGIN(CppTools::Internal::CppToolsPlugin)