cpptoolsplugin.cpp 12.2 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
hjk's avatar
hjk committed
3 4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** 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
#include "completionsettingspage.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 38
#include "cppmodelmanager.h"
#include "cpptoolsconstants.h"
con's avatar
con committed
39
#include "cpplocatorfilter.h"
40
#include "symbolsfindfilter.h"
41
#include "cpptoolssettings.h"
con's avatar
con committed
42

43 44
#include <extensionsystem/pluginmanager.h>

con's avatar
con committed
45 46 47
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
48
#include <coreplugin/actionmanager/actionmanager.h>
49 50
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
51
#include <coreplugin/id.h>
con's avatar
con committed
52
#include <coreplugin/editormanager/editormanager.h>
53
#include <coreplugin/progressmanager/progressmanager.h>
54
#include <coreplugin/vcsmanager.h>
55
#include <coreplugin/documentmanager.h>
con's avatar
con committed
56 57
#include <cppeditor/cppeditorconstants.h>

58 59
#include <QtConcurrentRun>
#include <QFutureSynchronizer>
60
#include <utils/runextensions.h>
61 62 63 64

#include <find/ifindfilter.h>
#include <find/searchresultwindow.h>
#include <utils/filesearch.h>
65
#include <utils/qtcassert.h>
66

67 68 69 70 71 72 73
#include <QtPlugin>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QSettings>
#include <QMenu>
#include <QAction>
con's avatar
con committed
74

75 76
#include <sstream>

con's avatar
con committed
77
using namespace CppTools::Internal;
78
using namespace CPlusPlus;
con's avatar
con committed
79 80 81

enum { debug = 0 };

82
static CppToolsPlugin *m_instance = 0;
con's avatar
con committed
83

84 85 86
CppToolsPlugin::CppToolsPlugin() :
    m_modelManager(0),
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
87 88 89 90 91 92 93 94 95 96
{
    m_instance = this;
}

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
    m_modelManager = 0; // deleted automatically
}

97
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
98
{
99 100
    Q_UNUSED(arguments)
    Q_UNUSED(error)
101

102 103
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

con's avatar
con committed
104 105
    // Objects
    m_modelManager = new CppModelManager(this);
hjk's avatar
hjk committed
106
    Core::VcsManager *vcsManager = Core::ICore::vcsManager();
107 108
    connect(vcsManager, SIGNAL(repositoryChanged(QString)),
            m_modelManager, SLOT(updateModifiedSourceFiles()));
109
    connect(Core::DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
110
            m_modelManager, SLOT(updateSourceFiles(QStringList)));
con's avatar
con committed
111
    addAutoReleasedObject(m_modelManager);
Roberto Raggi's avatar
Roberto Raggi committed
112

113 114 115
    addAutoReleasedObject(new CppLocatorFilter(m_modelManager));
    addAutoReleasedObject(new CppClassesFilter(m_modelManager));
    addAutoReleasedObject(new CppFunctionsFilter(m_modelManager));
hjk's avatar
hjk committed
116
    addAutoReleasedObject(new CppCurrentDocumentFilter(m_modelManager, Core::ICore::editorManager()));
117
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
118
    addAutoReleasedObject(new SymbolsFindFilter(m_modelManager));
119 120
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
121
    // Menus
Eike Ziller's avatar
Eike Ziller committed
122 123
    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
124 125 126 127 128 129
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
130
    Core::Context context(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
131 132

    QAction *switchAction = new QAction(tr("Switch Header/Source"), this);
Eike Ziller's avatar
Eike Ziller committed
133
    Core::Command *command = Core::ActionManager::registerAction(switchAction, Constants::SWITCH_HEADER_SOURCE, context, true);
con's avatar
con committed
134 135 136 137 138 139 140 141 142
    command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
    mcpptools->addAction(command);
    connect(switchAction, SIGNAL(triggered()), this, SLOT(switchHeaderSource()));

    return true;
}

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

150
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
151
{
152
    return SynchronousShutdown;
153 154
}

con's avatar
con committed
155 156
void CppToolsPlugin::switchHeaderSource()
{
hjk's avatar
hjk committed
157
    Core::IEditor *editor = Core::EditorManager::currentEditor();
158
    QString otherFile = correspondingHeaderOrSource(editor->document()->fileName());
159
    if (!otherFile.isEmpty())
hjk's avatar
hjk committed
160
        Core::EditorManager::openEditor(otherFile);
con's avatar
con committed
161 162
}

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

    if (!project)
170
        return QStringList();
171 172 173 174 175

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

// Figure out file type
185 186 187 188
enum FileType {
    HeaderFile,
    C_SourceFile,
    CPP_SourceFile,
189
    ObjectiveCPP_SourceFile,
190 191
    UnknownType
};
con's avatar
con committed
192 193 194 195 196 197 198 199 200 201 202

static inline FileType fileType(const Core::MimeDatabase *mimeDatase, const  QFileInfo & fi)
{
    const Core::MimeType mimeType = mimeDatase->findByFile(fi);
    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;
203 204
    if (typeName == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
        return ObjectiveCPP_SourceFile;
con's avatar
con committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218
    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
static QStringList matchingCandidateSuffixes(const Core::MimeDatabase *mimeDatase, FileType type)
{
    switch (type) {
    case UnknownType:
        break;
    case HeaderFile: // Note that C/C++ headers are undistinguishable
219 220 221
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)).suffixes()
               + mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes()
               + mimeDatase->findByType(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
con's avatar
con committed
222 223 224
    case C_SourceFile:
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
    case CPP_SourceFile:
225
    case ObjectiveCPP_SourceFile:
con's avatar
con committed
226 227 228 229 230
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
    }
    return QStringList();
}

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

244 245 246 247 248 249 250 251 252
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;
}

con's avatar
con committed
253 254
QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) const
{
255 256 257 258
    const QFileInfo fi(fileName);
    if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
        return m_headerSourceMapping.value(fi.absoluteFilePath());

hjk's avatar
hjk committed
259
    const Core::MimeDatabase *mimeDatase = Core::ICore::mimeDatabase();
260
    ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
con's avatar
con committed
261 262 263 264 265 266 267 268 269

    const FileType type = fileType(mimeDatase, fi);

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

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

270
    const QString baseName = fi.completeBaseName();
271
    const QString privateHeaderSuffix = QLatin1String("_p");
con's avatar
con committed
272 273
    const QStringList suffixes = matchingCandidateSuffixes(mimeDatase, type);

274
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
con's avatar
con committed
275 276 277 278
    if (type == HeaderFile) {
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
279
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
280 281
        }
    } else {
282 283 284 285 286 287 288 289
        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
290 291
    foreach (const QString &candidateFileName, candidateFileNames) {
        const QFileInfo candidateFi(absoluteDir, candidateFileName);
292 293
        if (candidateFi.isFile()) {
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
294 295
            if (type != HeaderFile || !baseName.endsWith(privateHeaderSuffix))
                m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
296
            return candidateFi.absoluteFilePath();
297
        }
298 299 300 301
    }

    // Find files in the project
    if (project) {
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        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
            foreach (const QString projectFile, projectFiles) {
                int value = commonStringLength(fileName, projectFile);
                if (value > compareValue) {
                    compareValue = value;
                    bestFileName = projectFile;
                }
            }
        }
        if (!bestFileName.isEmpty()) {
            const QFileInfo candidateFi(bestFileName);
317
            QTC_ASSERT(candidateFi.isFile(), return QString());
318 319
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
            m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
320
            return candidateFi.absoluteFilePath();
con's avatar
con committed
321 322
        }
    }
323

con's avatar
con committed
324 325 326
    return QString();
}

327
QString CppToolsPlugin::correspondingHeaderOrSource(const QString &fileName)
con's avatar
con committed
328
{
329
    const QString rc = m_instance->correspondingHeaderOrSourceI(fileName);
con's avatar
con committed
330 331 332 333 334 335
    if (debug)
        qDebug() << Q_FUNC_INFO << fileName << rc;
    return rc;
}

Q_EXPORT_PLUGIN(CppToolsPlugin)