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 "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"
42
#include "cpptoolsreuse.h"
con's avatar
con committed
43

44
45
#include <extensionsystem/pluginmanager.h>

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

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

#include <find/ifindfilter.h>
#include <find/searchresultwindow.h>
#include <utils/filesearch.h>
67
#include <utils/qtcassert.h>
68

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

77
78
79
#include <sstream>

using namespace CPlusPlus;
con's avatar
con committed
80

81
82
83
namespace CppTools {
namespace Internal {

con's avatar
con committed
84
85
enum { debug = 0 };

86
static CppToolsPlugin *m_instance = 0;
87
static QHash<QString, QString> m_headerSourceMapping;
con's avatar
con committed
88

89
90
CppToolsPlugin::CppToolsPlugin() :
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
91
92
93
94
95
96
97
{
    m_instance = this;
}

CppToolsPlugin::~CppToolsPlugin()
{
    m_instance = 0;
98
    delete CppModelManager::instance();
con's avatar
con committed
99
100
}

101
102
103
104
105
CppToolsPlugin *CppToolsPlugin::instance()
{
    return m_instance;
}

106
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
107
{
108
109
    Q_UNUSED(arguments)
    Q_UNUSED(error)
110

111
112
    m_settings = new CppToolsSettings(this); // force registration of cpp tools settings

con's avatar
con committed
113
    // Objects
114
    CppModelManager *modelManager = CppModelManager::instance();
hjk's avatar
hjk committed
115
    Core::VcsManager *vcsManager = Core::ICore::vcsManager();
116
    connect(vcsManager, SIGNAL(repositoryChanged(QString)),
117
            modelManager, SLOT(updateModifiedSourceFiles()));
118
    connect(Core::DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
119
            modelManager, SLOT(updateSourceFiles(QStringList)));
Roberto Raggi's avatar
Roberto Raggi committed
120

121
122
123
124
    addAutoReleasedObject(new CppLocatorFilter(modelManager));
    addAutoReleasedObject(new CppClassesFilter(modelManager));
    addAutoReleasedObject(new CppFunctionsFilter(modelManager));
    addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, Core::ICore::editorManager()));
125
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
126
    addAutoReleasedObject(new SymbolsFindFilter(modelManager));
127
128
    addAutoReleasedObject(new CppCodeStyleSettingsPage);

con's avatar
con committed
129
    // Menus
Eike Ziller's avatar
Eike Ziller committed
130
131
    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
132
133
134
135
136
137
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
138
    Core::Context context(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
139
140

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

146
    QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
147
148
149
150
151
    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
152
153
154
155
156
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
157
158
    // The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
    // so, apply settings here
hjk's avatar
hjk committed
159
    m_fileSettings->fromSettings(Core::ICore::settings());
160
161
    if (!m_fileSettings->applySuffixesToMimeDB())
        qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
con's avatar
con committed
162
163
}

164
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
165
{
166
    return SynchronousShutdown;
167
168
}

con's avatar
con committed
169
170
void CppToolsPlugin::switchHeaderSource()
{
171
172
173
174
175
176
177
178
179
180
181
182
    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
183
184
}

185
static QStringList findFilesInProject(const QString &name,
186
                                   const ProjectExplorer::Project *project)
con's avatar
con committed
187
188
{
    if (debug)
189
190
191
        qDebug() << Q_FUNC_INFO << name << project;

    if (!project)
192
        return QStringList();
193
194
195
196
197

    QString pattern = QString(1, QLatin1Char('/'));
    pattern += name;
    const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
    const QStringList::const_iterator pcend = projectFiles.constEnd();
198
    QStringList candidateList;
199
200
    for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it) {
        if (it->endsWith(pattern))
201
            candidateList.append(*it);
con's avatar
con committed
202
    }
203
    return candidateList;
con's avatar
con committed
204
205
206
}

// Figure out file type
207
208
209
210
enum FileType {
    HeaderFile,
    C_SourceFile,
    CPP_SourceFile,
211
    ObjectiveCPP_SourceFile,
212
213
    UnknownType
};
con's avatar
con committed
214

215
static inline FileType fileType(const Core::MimeDatabase *mimeDatabase, const  QFileInfo & fi)
con's avatar
con committed
216
{
217
    const Core::MimeType mimeType = mimeDatabase->findByFile(fi);
con's avatar
con committed
218
219
220
221
222
223
224
    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;
225
226
    if (typeName == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
        return ObjectiveCPP_SourceFile;
con's avatar
con committed
227
228
229
230
231
232
233
234
    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
235
static QStringList matchingCandidateSuffixes(const Core::MimeDatabase *mimeDatabase, FileType type)
con's avatar
con committed
236
237
238
239
240
{
    switch (type) {
    case UnknownType:
        break;
    case HeaderFile: // Note that C/C++ headers are undistinguishable
241
242
243
        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
244
    case C_SourceFile:
245
        return mimeDatabase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
con's avatar
con committed
246
    case CPP_SourceFile:
247
    case ObjectiveCPP_SourceFile:
248
        return mimeDatabase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
con's avatar
con committed
249
250
251
252
    }
    return QStringList();
}

253
254
255
256
257
258
259
260
261
262
263
264
265
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;
}

266
267
268
269
270
271
272
273
274
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;
}

275
276
277
} // namespace Internal

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

281
    const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
282
283
284
    const QFileInfo fi(fileName);
    if (m_headerSourceMapping.contains(fi.absoluteFilePath())) {
        if (wasHeader)
285
            *wasHeader = fileType(mimeDatabase, fi) == HeaderFile;
286
287
        return m_headerSourceMapping.value(fi.absoluteFilePath());
    }
con's avatar
con committed
288

289
    FileType type = fileType(mimeDatabase, fi);
290
291
    if (wasHeader)
        *wasHeader = type == HeaderFile;
con's avatar
con committed
292
293
294
295
296
297
298

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

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

299
    const QString baseName = fi.completeBaseName();
300
    const QString privateHeaderSuffix = QLatin1String("_p");
301
    const QStringList suffixes = matchingCandidateSuffixes(mimeDatabase, type);
con's avatar
con committed
302

303
    QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
con's avatar
con committed
304
305
306
307
    if (type == HeaderFile) {
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
308
            candidateFileNames += baseNameWithAllSuffixes(sourceBaseName, suffixes);
con's avatar
con committed
309
310
        }
    } else {
311
312
313
314
315
316
317
318
        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
319
320
    foreach (const QString &candidateFileName, candidateFileNames) {
        const QFileInfo candidateFi(absoluteDir, candidateFileName);
321
322
        if (candidateFi.isFile()) {
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
323
324
            if (type != HeaderFile || !baseName.endsWith(privateHeaderSuffix))
                m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
325
            return candidateFi.absoluteFilePath();
326
        }
327
328
329
    }

    // Find files in the project
330
    ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
331
    if (project) {
332
333
334
335
336
        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
337
            foreach (const QString &projectFile, projectFiles) {
338
339
340
341
342
343
344
345
346
                int value = commonStringLength(fileName, projectFile);
                if (value > compareValue) {
                    compareValue = value;
                    bestFileName = projectFile;
                }
            }
        }
        if (!bestFileName.isEmpty()) {
            const QFileInfo candidateFi(bestFileName);
347
            QTC_ASSERT(candidateFi.isFile(), return QString());
348
349
            m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
            m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
350
            return candidateFi.absoluteFilePath();
con's avatar
con committed
351
352
        }
    }
353

con's avatar
con committed
354
355
356
    return QString();
}

357
} // namespace CppTools
con's avatar
con committed
358

359
Q_EXPORT_PLUGIN(CppTools::Internal::CppToolsPlugin)