cpptoolsplugin.cpp 12.7 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** 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.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

30
#include "cpptoolsplugin.h"
31
#include "completionsettingspage.h"
32
#include "cppfilesettingspage.h"
33
#include "cppclassesfilter.h"
con's avatar
con committed
34
#include "cppcodecompletion.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"
con's avatar
con committed
40

41 42
#include <extensionsystem/pluginmanager.h>

con's avatar
con committed
43 44 45 46
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
47
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
48
#include <coreplugin/editormanager/editormanager.h>
49
#include <coreplugin/progressmanager/progressmanager.h>
50
#include <coreplugin/vcsmanager.h>
con's avatar
con committed
51 52
#include <cppeditor/cppeditorconstants.h>

53 54 55 56 57 58 59 60
#include <QtCore/QtConcurrentRun>
#include <QtCore/QFutureSynchronizer>
#include <qtconcurrent/runextensions.h>

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

61
#include <QtCore/QtPlugin>
con's avatar
con committed
62 63 64
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QDebug>
65
#include <QtCore/QSettings>
con's avatar
con committed
66 67 68
#include <QtGui/QMenu>
#include <QtGui/QAction>

69 70
#include <sstream>

con's avatar
con committed
71
using namespace CppTools::Internal;
72
using namespace CPlusPlus;
con's avatar
con committed
73 74 75 76 77

enum { debug = 0 };

CppToolsPlugin *CppToolsPlugin::m_instance = 0;

78 79 80 81
CppToolsPlugin::CppToolsPlugin() :
    m_context(-1),
    m_modelManager(0),
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
82 83 84 85 86 87 88 89 90 91
{
    m_instance = this;
}

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

92
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
93
{
94 95
    Q_UNUSED(arguments)
    Q_UNUSED(error)
96 97
    Core::ICore *core = Core::ICore::instance();
    Core::ActionManager *am = core->actionManager();
con's avatar
con committed
98 99 100

    // Objects
    m_modelManager = new CppModelManager(this);
101 102 103 104 105
    Core::VCSManager *vcsManager = core->vcsManager();
    connect(vcsManager, SIGNAL(repositoryChanged(QString)),
            m_modelManager, SLOT(updateModifiedSourceFiles()));
    connect(vcsManager, SIGNAL(filesChanged(QStringList)),
            m_modelManager, SLOT(updateModifiedSourceFiles()));
con's avatar
con committed
106
    addAutoReleasedObject(m_modelManager);
Roberto Raggi's avatar
Roberto Raggi committed
107

108
    m_completion = new CppCodeCompletion(m_modelManager);
109
    addAutoReleasedObject(m_completion);
Roberto Raggi's avatar
Roberto Raggi committed
110

con's avatar
con committed
111
    CppLocatorFilter *locatorFilter = new CppLocatorFilter(m_modelManager,
112
                                                                 core->editorManager());
con's avatar
con committed
113
    addAutoReleasedObject(locatorFilter);
114 115
    addAutoReleasedObject(new CppClassesFilter(m_modelManager, core->editorManager()));
    addAutoReleasedObject(new CppFunctionsFilter(m_modelManager, core->editorManager()));
116
    addAutoReleasedObject(new CppCurrentDocumentFilter(m_modelManager, core->editorManager()));
117
    addAutoReleasedObject(new CompletionSettingsPage(m_completion));
118
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
con's avatar
con committed
119 120

    // Menus
121 122
    Core::ActionContainer *mtools = am->actionContainer(Core::Constants::M_TOOLS);
    Core::ActionContainer *mcpptools = am->createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
123 124 125 126 127 128
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
129
    m_context = core->uniqueIDManager()->uniqueIdentifier(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
130 131 132
    QList<int> context = QList<int>() << m_context;

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

138
    // Restore settings
139
    QSettings *settings = Core::ICore::instance()->settings();
140 141
    settings->beginGroup(QLatin1String("CppTools"));
    settings->beginGroup(QLatin1String("Completion"));
142 143
    const int caseSensitivity = settings->value(QLatin1String("CaseSensitivity"), m_completion->caseSensitivity()).toInt();
    m_completion->setCaseSensitivity((CppCodeCompletion::CaseSensitivity) caseSensitivity);
144
    m_completion->setAutoInsertBrackets(settings->value(QLatin1String("AutoInsertBraces"), true).toBool());
145
    m_completion->setPartialCompletionEnabled(settings->value(QLatin1String("PartiallyComplete"), true).toBool());
146 147 148
    settings->endGroup();
    settings->endGroup();

con's avatar
con committed
149 150 151 152 153
    return true;
}

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

    // Initialize header suffixes
    const Core::MimeDatabase *mimeDatabase = Core::ICore::instance()->mimeDatabase();
    const Core::MimeType mimeType = mimeDatabase->findByType(QLatin1String("text/x-c++hdr"));
    m_modelManager->setHeaderSuffixes(mimeType.suffixes());
con's avatar
con committed
164 165
}

166 167 168
void CppToolsPlugin::shutdown()
{
    // Save settings
169
    QSettings *settings = Core::ICore::instance()->settings();
170 171
    settings->beginGroup(QLatin1String("CppTools"));
    settings->beginGroup(QLatin1String("Completion"));
172
    settings->setValue(QLatin1String("CaseSensitivity"), (int) m_completion->caseSensitivity());
173
    settings->setValue(QLatin1String("AutoInsertBraces"), m_completion->autoInsertBrackets());
174
    settings->setValue(QLatin1String("PartiallyComplete"), m_completion->isPartialCompletionEnabled());
175 176 177 178
    settings->endGroup();
    settings->endGroup();
}

con's avatar
con committed
179 180
void CppToolsPlugin::switchHeaderSource()
{
181
    Core::EditorManager *editorManager = Core::EditorManager::instance();
182
    Core::IEditor *editor = editorManager->currentEditor();
con's avatar
con committed
183 184
    QString otherFile = correspondingHeaderOrSource(editor->file()->fileName());
    if (!otherFile.isEmpty()) {
185 186
        editorManager->openEditor(otherFile);
        editorManager->ensureEditorManagerVisible();
con's avatar
con committed
187 188 189 190 191 192 193 194 195
    }
}

QFileInfo CppToolsPlugin::findFile(const QDir &dir, const QString &name,
                                   const ProjectExplorer::Project *project) const
{
    if (debug)
        qDebug() << Q_FUNC_INFO << dir << name;

196 197
    QFileInfo fileInSameDir(dir, name);
    if (project && !fileInSameDir.isFile()) {
con's avatar
con committed
198 199 200 201 202 203 204 205 206
        QString pattern = QString(1, QLatin1Char('/'));
        pattern += name;
        const QStringList projectFiles = project->files(ProjectExplorer::Project::AllFiles);
        const QStringList::const_iterator pcend = projectFiles.constEnd();
        for (QStringList::const_iterator it = projectFiles.constBegin(); it != pcend; ++it)
            if (it->endsWith(pattern))
                return QFileInfo(*it);
        return QFileInfo();
    }
207
    return fileInSameDir;
con's avatar
con committed
208 209 210
}

// Figure out file type
211 212 213 214
enum FileType {
    HeaderFile,
    C_SourceFile,
    CPP_SourceFile,
215
    ObjectiveCPP_SourceFile,
216 217
    UnknownType
};
con's avatar
con committed
218 219 220 221 222 223 224 225 226 227 228

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;
229 230
    if (typeName == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
        return ObjectiveCPP_SourceFile;
con's avatar
con committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244
    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
245 246 247
        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
248 249 250
    case C_SourceFile:
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
    case CPP_SourceFile:
251
    case ObjectiveCPP_SourceFile:
con's avatar
con committed
252 253 254 255 256 257 258
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
    }
    return QStringList();
}

QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) const
{
259
    const Core::ICore *core = Core::ICore::instance();
con's avatar
con committed
260 261
    const Core::MimeDatabase *mimeDatase = core->mimeDatabase();
    ProjectExplorer::ProjectExplorerPlugin *explorer =
262
       ProjectExplorer::ProjectExplorerPlugin::instance();
con's avatar
con committed
263 264 265 266 267 268 269 270 271 272 273 274
    ProjectExplorer::Project *project = (explorer ? explorer->currentProject() : 0);

    const QFileInfo fi(fileName);
    const FileType type = fileType(mimeDatase, fi);

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

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

    const QDir absoluteDir = fi.absoluteDir();
275
    const QString baseName = fi.completeBaseName();
con's avatar
con committed
276 277 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    const QStringList suffixes = matchingCandidateSuffixes(mimeDatase, type);

    const QString privateHeaderSuffix = QLatin1String("_p");
    const QChar dot = QLatin1Char('.');
    QStringList candidates;
    // Check base matches 'source.h'-> 'source.cpp' and vice versa
    const QStringList::const_iterator scend = suffixes.constEnd();
    for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) {
        QString candidate = baseName;
        candidate += dot;
        candidate += *it;
        const QFileInfo candidateFi = findFile(absoluteDir, candidate, project);
        if (candidateFi.isFile())
            return candidateFi.absoluteFilePath();
    }
    if (type == HeaderFile) {
        // 'source_p.h': try 'source.cpp'
        if (baseName.endsWith(privateHeaderSuffix)) {
            QString sourceBaseName = baseName;
            sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size());
            for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) {
                QString candidate = sourceBaseName;
                candidate += dot;
                candidate += *it;
                const QFileInfo candidateFi = findFile(absoluteDir, candidate, project);
                if (candidateFi.isFile())
                    return candidateFi.absoluteFilePath();
            }
        }
    } else {
        // 'source.cpp': try 'source_p.h'
        const QStringList::const_iterator scend = suffixes.constEnd();
        for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) {
            QString candidate = baseName;
            candidate += privateHeaderSuffix;
            candidate += dot;
            candidate += *it;
            const QFileInfo candidateFi = findFile(absoluteDir, candidate, project);
            if (candidateFi.isFile())
                return candidateFi.absoluteFilePath();
        }
    }
    return QString();
}

QString CppToolsPlugin::correspondingHeaderOrSource(const QString &fileName) const
{
    const QString rc = correspondingHeaderOrSourceI(fileName);
    if (debug)
        qDebug() << Q_FUNC_INFO << fileName << rc;
    return rc;
}

Q_EXPORT_PLUGIN(CppToolsPlugin)