cpptoolsplugin.cpp 12.5 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 "cpptoolsplugin.h"
31

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"
con's avatar
con committed
42

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

51
#include <utils/qtcassert.h>
52

53 54 55 56 57 58
#include <QtPlugin>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QMenu>
#include <QAction>
59 60

using namespace CPlusPlus;
con's avatar
con committed
61

62 63 64
namespace CppTools {
namespace Internal {

con's avatar
con committed
65 66
enum { debug = 0 };

67
static CppToolsPlugin *m_instance = 0;
68
static QHash<QString, QString> m_headerSourceMapping;
con's avatar
con committed
69

70 71
CppToolsPlugin::CppToolsPlugin() :
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
72 73 74 75 76 77 78
{
    m_instance = this;
}

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
79
    delete CppModelManager::instance();
con's avatar
con committed
80 81
}

82 83 84 85 86
CppToolsPlugin *CppToolsPlugin::instance()
{
    return m_instance;
}

87
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
88
{
89 90
    Q_UNUSED(arguments)
    Q_UNUSED(error)
91

92 93
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

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

102 103 104 105
    addAutoReleasedObject(new CppLocatorFilter(modelManager));
    addAutoReleasedObject(new CppClassesFilter(modelManager));
    addAutoReleasedObject(new CppFunctionsFilter(modelManager));
    addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, Core::ICore::editorManager()));
106
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
107
    addAutoReleasedObject(new SymbolsFindFilter(modelManager));
108 109
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
110
    // Menus
Eike Ziller's avatar
Eike Ziller committed
111 112
    Core::ActionContainer *mtools = Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
    Core::ActionContainer *mcpptools = Core::ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
113 114 115 116 117 118
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
119
    Core::Context context(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
120 121

    QAction *switchAction = new QAction(tr("Switch Header/Source"), this);
Eike Ziller's avatar
Eike Ziller committed
122
    Core::Command *command = Core::ActionManager::registerAction(switchAction, Constants::SWITCH_HEADER_SOURCE, context, true);
con's avatar
con committed
123 124 125 126
    command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
    mcpptools->addAction(command);
    connect(switchAction, SIGNAL(triggered()), this, SLOT(switchHeaderSource()));

127
    QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
128 129 130 131 132
    command = Core::ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
    command->setDefaultKeySequence(QKeySequence(Qt::CTRL + Qt::Key_E, Qt::Key_F4));
    mcpptools->addAction(command);
    connect(openInNextSplitAction, SIGNAL(triggered()), this, SLOT(switchHeaderSourceInNextSplit()));

con's avatar
con committed
133 134 135 136 137
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
138 139
    // The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
    // so, apply settings here
hjk's avatar
hjk committed
140
    m_fileSettings->fromSettings(Core::ICore::settings());
141 142
    if (!m_fileSettings->applySuffixesToMimeDB())
        qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
con's avatar
con committed
143 144
}

145
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
146
{
147
    return SynchronousShutdown;
148 149
}

con's avatar
con committed
150 151
void CppToolsPlugin::switchHeaderSource()
{
152 153 154 155 156 157 158 159 160 161 162 163
    QString otherFile = correspondingHeaderOrSource(
                Core::EditorManager::currentEditor()->document()->fileName());
    if (!otherFile.isEmpty())
        Core::EditorManager::openEditor(otherFile);
}

void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
    QString otherFile = correspondingHeaderOrSource(
                Core::EditorManager::currentEditor()->document()->fileName());
    if (!otherFile.isEmpty())
        Core::EditorManager::openEditorInNextSplit(otherFile);
con's avatar
con committed
164 165
}

166
static QStringList findFilesInProject(const QString &name,
167
                                   const ProjectExplorer::Project *project)
con's avatar
con committed
168 169
{
    if (debug)
170 171 172
        qDebug() << Q_FUNC_INFO << name << project;

    if (!project)
173
        return QStringList();
174 175 176 177 178

    QString pattern = QString(1, QLatin1Char('/'));
    pattern += name;
    const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
    const QStringList::const_iterator pcend = projectFiles.constEnd();
179
    QStringList candidateList;
180 181
    for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it) {
        if (it->endsWith(pattern))
182
            candidateList.append(*it);
con's avatar
con committed
183
    }
184
    return candidateList;
con's avatar
con committed
185 186 187
}

// Figure out file type
188 189 190 191
enum FileType {
    HeaderFile,
    C_SourceFile,
    CPP_SourceFile,
192
    ObjectiveCPP_SourceFile,
193 194
    UnknownType
};
con's avatar
con committed
195

196
static inline FileType fileType(const Core::MimeDatabase *mimeDatabase, const  QFileInfo & fi)
con's avatar
con committed
197
{
198
    const Core::MimeType mimeType = mimeDatabase->findByFile(fi);
con's avatar
con committed
199 200 201 202 203 204 205
    if (!mimeType)
        return UnknownType;
    const QString typeName = mimeType.type();
    if (typeName == QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE))
        return C_SourceFile;
    if (typeName == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE))
        return CPP_SourceFile;
206 207
    if (typeName == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
        return ObjectiveCPP_SourceFile;
con's avatar
con committed
208 209 210 211 212 213 214 215
    if (typeName == QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)
        || typeName == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))
        return HeaderFile;
    return UnknownType;
}

// Return the suffixes that should be checked when trying to find a
// source belonging to a header and vice versa
216
static QStringList matchingCandidateSuffixes(const Core::MimeDatabase *mimeDatabase, FileType type)
con's avatar
con committed
217 218 219 220 221
{
    switch (type) {
    case UnknownType:
        break;
    case HeaderFile: // Note that C/C++ headers are undistinguishable
222 223 224
        return mimeDatabase->findByType(QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)).suffixes()
               + mimeDatabase->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes()
               + mimeDatabase->findByType(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
con's avatar
con committed
225
    case C_SourceFile:
226
        return mimeDatabase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
con's avatar
con committed
227
    case CPP_SourceFile:
228
    case ObjectiveCPP_SourceFile:
229
        return mimeDatabase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
con's avatar
con committed
230 231 232 233
    }
    return QStringList();
}

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

247 248 249 250 251 252 253 254 255
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;
}

256 257 258
} // namespace Internal

QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
con's avatar
con committed
259
{
260
    using namespace Internal;
261

262
    const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
263 264 265
    const QFileInfo fi(fileName);
    if (m_headerSourceMapping.contains(fi.absoluteFilePath())) {
        if (wasHeader)
266
            *wasHeader = fileType(mimeDatabase, fi) == HeaderFile;
267 268
        return m_headerSourceMapping.value(fi.absoluteFilePath());
    }
con's avatar
con committed
269

270
    FileType type = fileType(mimeDatabase, fi);
271 272
    if (wasHeader)
        *wasHeader = type == HeaderFile;
con's avatar
con committed
273 274 275 276 277 278 279

    if (debug)
        qDebug() << Q_FUNC_INFO << fileName <<  type;

    if (type == UnknownType)
        return QString();

280
    const QString baseName = fi.completeBaseName();
281
    const QString privateHeaderSuffix = QLatin1String("_p");
282
    const QStringList suffixes = matchingCandidateSuffixes(mimeDatabase, type);
con's avatar
con committed
283

284
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
con's avatar
con committed
285 286 287 288
    if (type == HeaderFile) {
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
289
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
290 291
        }
    } else {
292 293 294 295 296 297 298 299
        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
300 301
    foreach (const QString &candidateFileName, candidateFileNames) {
        const QFileInfo candidateFi(absoluteDir, candidateFileName);
302 303
        if (candidateFi.isFile()) {
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
304 305
            if (type != HeaderFile || !baseName.endsWith(privateHeaderSuffix))
                m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
306
            return candidateFi.absoluteFilePath();
307
        }
308 309 310
    }

    // Find files in the project
311
    ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
312
    if (project) {
313 314 315 316 317
        QString bestFileName;
        int compareValue = 0;
        foreach (const QString &candidateFileName, candidateFileNames) {
            const QStringList projectFiles = findFilesInProject(candidateFileName, project);
            // Find the file having the most common path with fileName
318
            foreach (const QString &projectFile, projectFiles) {
319 320 321 322 323 324 325 326 327
                int value = commonStringLength(fileName, projectFile);
                if (value > compareValue) {
                    compareValue = value;
                    bestFileName = projectFile;
                }
            }
        }
        if (!bestFileName.isEmpty()) {
            const QFileInfo candidateFi(bestFileName);
328
            QTC_ASSERT(candidateFi.isFile(), return QString());
329 330
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
            m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
331
            return candidateFi.absoluteFilePath();
con's avatar
con committed
332 333
        }
    }
334

con's avatar
con committed
335 336 337
    return QString();
}

338
} // namespace CppTools
con's avatar
con committed
339

340
Q_EXPORT_PLUGIN(CppTools::Internal::CppToolsPlugin)