cpptoolsplugin.cpp 19.3 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
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
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
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
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"
con's avatar
con committed
36
37
38
39
#include "cppmodelmanager.h"
#include "cpptoolsconstants.h"
#include "cppquickopenfilter.h"

40
41
#include <extensionsystem/pluginmanager.h>

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

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <QtCore/QtConcurrentRun>
#include <QtCore/QFutureSynchronizer>
#include <qtconcurrent/runextensions.h>

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

#include <Control.h>
#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>

#include <cplusplus/PreprocessorEnvironment.h>
#include <cplusplus/pp.h>

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

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
82
83

enum { debug = 0 };

CppToolsPlugin *CppToolsPlugin::m_instance = 0;

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
namespace {

class SimpleClient: public Client
{
    Environment _env;
    QPointer<CppModelManager> _modelManager;
    Snapshot _snapshot;
    Preprocessor _preproc;
    QSet<QString> _merged;

public:
    SimpleClient(QPointer<CppModelManager> modelManager)
        : _modelManager(modelManager),
          _snapshot(_modelManager->snapshot()),
          _preproc(this, &_env)
    { }

    QByteArray run(QString fileName, const QByteArray &source)
    {
        const QByteArray preprocessed = _preproc(fileName, source);
        return preprocessed;
    }

    virtual void sourceNeeded(QString &fileName, IncludeType, unsigned)
    { mergeEnvironment(fileName); }

    virtual void macroAdded(const Macro &) {}

    virtual void startExpandingMacro(unsigned,
                                     const Macro &,
                                     const QByteArray &,
                                     const QVector<MacroArgumentReference> &) {}

    virtual void stopExpandingMacro(unsigned, const Macro &) {}

    virtual void startSkippingBlocks(unsigned) {}
    virtual void stopSkippingBlocks(unsigned) {}

    void mergeEnvironment(const QString &fileName)
    {
        if (! _merged.contains(fileName)) {
            _merged.insert(fileName);

            if (Document::Ptr doc = _snapshot.value(fileName)) {
                foreach (const Document::Include &i, doc->includes())
                    mergeEnvironment(i.fileName());

                _env.addMacros(doc->definedMacros());
            }
        }
    }
};

class FindClass: protected ASTVisitor
{
    QFutureInterface<Core::Utils::FileSearchResult> &_future;
    Document::Ptr _doc;
    Snapshot _snapshot;
142
    Document::Ptr _thisDocument;
143
144
145
146
147
148
149
150
151
152
153
154

    QByteArray _source;
    QString _text;
    QTextDocument::FindFlags _findFlags;

public:
    FindClass(QFutureInterface<Core::Utils::FileSearchResult> &future, Document::Ptr doc, Snapshot snapshot)
        : ASTVisitor(doc->control()),
          _future(future),
          _doc(doc),
          _snapshot(snapshot)
    {
155
        _thisDocument = _snapshot.value(_doc->fileName());
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    }

    void operator()(AST *ast, const QByteArray &source, const QString &text,
                    QTextDocument::FindFlags findFlags)
    {
        _source = source;
        _text = text;
        _findFlags = findFlags;
        accept(ast);
    }

protected:
    using ASTVisitor::visit;

    virtual bool visit(ClassSpecifierAST *ast)
    {
        if (ast->name) {
            Qt::CaseSensitivity cs = Qt::CaseInsensitive;
            if (_findFlags & QTextDocument::FindCaseSensitively)
                cs = Qt::CaseSensitive;

            Token start = tokenAt(ast->name->firstToken());
            Token end = tokenAt(ast->name->lastToken() - 1);
            const QString className = QString::fromUtf8(_source.constData() + start.begin(),
                                                        end.end() - start.begin());

182
            int idx = className.indexOf(_text, 0, cs);
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
273
274
275
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
            if (idx != -1) {
                const char *beg = _source.constData();
                const char *cp = beg + start.offset;
                for (; cp != beg - 1; --cp) {
                    if (*cp == '\n')
                        break;
                }

                ++cp;

                const char *lineEnd = cp + 1;
                for (; *lineEnd; ++lineEnd) {
                    if (*lineEnd == '\n')
                        break;
                }

                const QString matchingLine = QString::fromUtf8(cp, lineEnd - cp);

                unsigned line, col;
                getTokenStartPosition(ast->name->firstToken(), &line, &col);

                _future.reportResult(Core::Utils::FileSearchResult(QDir::toNativeSeparators(_doc->fileName()),
                                                                   line, matchingLine,
                                                                   col + idx - 1, _text.length()));
            }
        }

        return true;
    }
};

static void searchClassDeclarations(QFutureInterface<Core::Utils::FileSearchResult> &future,
                                    QPointer<CppModelManager> modelManager,
                                    QString text,
                                    QTextDocument::FindFlags findFlags)
{
    const Snapshot snapshot = modelManager->snapshot();

    future.setProgressRange(0, snapshot.size());
    future.setProgressValue(0);

    int progress = 0;
    foreach (Document::Ptr doc, snapshot) {
        const QString fileName = doc->fileName();

        QFile file(fileName);
        if (! file.open(QFile::ReadOnly))
            continue;

        const QString contents = QTextStream(&file).readAll();

        SimpleClient r(modelManager);
        const QByteArray source = r.run(fileName, contents.toUtf8());

        Document::Ptr newDoc = Document::create(fileName);
        newDoc->setSource(source);
        newDoc->parse();

        FindClass findClass(future, newDoc, snapshot);
        findClass(newDoc->translationUnit()->ast(), source, text, findFlags);

        future.setProgressValue(++progress);
    }
}

} // end of anonymous namespace

FindClassDeclarations::FindClassDeclarations(CppModelManager *modelManager)
    : _modelManager(modelManager),
      _resultWindow(ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>())
{
    m_watcher.setPendingResultsLimit(1);
    connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int)));
    connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
}

void FindClassDeclarations::findAll(const QString &txt, QTextDocument::FindFlags findFlags)
{
    _resultWindow->clearContents();
    _resultWindow->popup(true);

    Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();

    QFuture<Core::Utils::FileSearchResult> result =
            QtConcurrent::run(&searchClassDeclarations, _modelManager, txt, findFlags);

    m_watcher.setFuture(result);

    Core::FutureProgress *progress = progressManager->addTask(result, tr("Search class"),
                                                              CppTools::Constants::TASK_INDEX,
                                                              Core::ProgressManager::CloseOnSuccess);

    connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup()));
}

void FindClassDeclarations::displayResult(int index)
{
    Core::Utils::FileSearchResult result = m_watcher.future().resultAt(index);
    Find::ResultWindowItem *item = _resultWindow->addResult(result.fileName,
                                                            result.lineNumber,
                                                            result.matchingLine,
                                                            result.matchStart,
                                                            result.matchLength);
    if (item)
        connect(item, SIGNAL(activated(const QString&,int,int)),
                this, SLOT(openEditor(const QString&,int,int)));
}

void FindClassDeclarations::searchFinished()
{
    emit changed();
}

void FindClassDeclarations::openEditor(const QString &fileName, int line, int column)
{
    TextEditor::BaseTextEditor::openEditorAt(fileName, line, column);
}

301
302
303
304
CppToolsPlugin::CppToolsPlugin() :
    m_context(-1),
    m_modelManager(0),
    m_fileSettings(new CppFileSettings)
con's avatar
con committed
305
306
307
308
309
310
311
312
313
314
{
    m_instance = this;
}

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

315
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
con's avatar
con committed
316
{
317
318
319
320
    Q_UNUSED(arguments);
    Q_UNUSED(error);
    Core::ICore *core = Core::ICore::instance();
    Core::ActionManager *am = core->actionManager();
con's avatar
con committed
321
322
323
324

    // Objects
    m_modelManager = new CppModelManager(this);
    addAutoReleasedObject(m_modelManager);
325
    m_completion = new CppCodeCompletion(m_modelManager);
326
    addAutoReleasedObject(m_completion);
con's avatar
con committed
327
    CppQuickOpenFilter *quickOpenFilter = new CppQuickOpenFilter(m_modelManager,
328
                                                                 core->editorManager());
con's avatar
con committed
329
    addAutoReleasedObject(quickOpenFilter);
330
331
    addAutoReleasedObject(new CppClassesFilter(m_modelManager, core->editorManager()));
    addAutoReleasedObject(new CppFunctionsFilter(m_modelManager, core->editorManager()));
332
    addAutoReleasedObject(new CompletionSettingsPage(m_completion));
333
    addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
con's avatar
con committed
334

335
336
    addAutoReleasedObject(new FindClassDeclarations(m_modelManager));

con's avatar
con committed
337
    // Menus
338
339
    Core::ActionContainer *mtools = am->actionContainer(Core::Constants::M_TOOLS);
    Core::ActionContainer *mcpptools = am->createMenu(CppTools::Constants::M_TOOLS_CPP);
con's avatar
con committed
340
341
342
343
344
345
    QMenu *menu = mcpptools->menu();
    menu->setTitle(tr("&C++"));
    menu->setEnabled(true);
    mtools->addMenu(mcpptools);

    // Actions
346
    m_context = core->uniqueIDManager()->uniqueIdentifier(CppEditor::Constants::C_CPPEDITOR);
con's avatar
con committed
347
348
349
    QList<int> context = QList<int>() << m_context;

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

355
    // Restore settings
356
    QSettings *settings = Core::ICore::instance()->settings();
357
358
359
360
    settings->beginGroup(QLatin1String("CppTools"));
    settings->beginGroup(QLatin1String("Completion"));
    const bool caseSensitive = settings->value(QLatin1String("CaseSensitive"), true).toBool();
    m_completion->setCaseSensitivity(caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
361
    m_completion->setAutoInsertBrackets(settings->value(QLatin1String("AutoInsertBraces"), true).toBool());
362
    m_completion->setPartialCompletionEnabled(settings->value(QLatin1String("PartiallyComplete"), true).toBool());
363
364
365
    settings->endGroup();
    settings->endGroup();

con's avatar
con committed
366
367
368
369
370
    return true;
}

void CppToolsPlugin::extensionsInitialized()
{
371
372
373
374
375
    // 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");
con's avatar
con committed
376
377
}

378
379
380
void CppToolsPlugin::shutdown()
{
    // Save settings
381
    QSettings *settings = Core::ICore::instance()->settings();
382
383
384
    settings->beginGroup(QLatin1String("CppTools"));
    settings->beginGroup(QLatin1String("Completion"));
    settings->setValue(QLatin1String("CaseSensitive"), m_completion->caseSensitivity() == Qt::CaseSensitive);
385
    settings->setValue(QLatin1String("AutoInsertBraces"), m_completion->autoInsertBrackets());
386
    settings->setValue(QLatin1String("PartiallyComplete"), m_completion->isPartialCompletionEnabled());
387
388
389
390
    settings->endGroup();
    settings->endGroup();
}

con's avatar
con committed
391
392
void CppToolsPlugin::switchHeaderSource()
{
393
    Core::EditorManager *editorManager = Core::EditorManager::instance();
394
    Core::IEditor *editor = editorManager->currentEditor();
con's avatar
con committed
395
396
    QString otherFile = correspondingHeaderOrSource(editor->file()->fileName());
    if (!otherFile.isEmpty()) {
397
398
        editorManager->openEditor(otherFile);
        editorManager->ensureEditorManagerVisible();
con's avatar
con committed
399
400
401
402
403
404
405
406
407
    }
}

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

408
409
    QFileInfo fileInSameDir(dir, name);
    if (project && !fileInSameDir.isFile()) {
con's avatar
con committed
410
411
412
413
414
415
416
417
418
        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();
    }
419
    return fileInSameDir;
con's avatar
con committed
420
421
422
}

// Figure out file type
423
424
425
426
enum FileType {
    HeaderFile,
    C_SourceFile,
    CPP_SourceFile,
427
    ObjectiveCPP_SourceFile,
428
429
    UnknownType
};
con's avatar
con committed
430
431
432
433
434
435
436
437
438
439
440

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;
441
442
    if (typeName == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
        return ObjectiveCPP_SourceFile;
con's avatar
con committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    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
457
458
459
        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
460
461
462
    case C_SourceFile:
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
    case CPP_SourceFile:
463
    case ObjectiveCPP_SourceFile:
con's avatar
con committed
464
465
466
467
468
469
470
        return mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
    }
    return QStringList();
}

QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) const
{
471
    const Core::ICore *core = Core::ICore::instance();
con's avatar
con committed
472
473
    const Core::MimeDatabase *mimeDatase = core->mimeDatabase();
    ProjectExplorer::ProjectExplorerPlugin *explorer =
474
       ProjectExplorer::ProjectExplorerPlugin::instance();
con's avatar
con committed
475
476
477
478
479
480
481
482
483
484
485
486
    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();
487
    const QString baseName = fi.completeBaseName();
con's avatar
con committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
    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)