cppeditor.cpp 43.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 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

con's avatar
con committed
30
#include "cppeditor.h"
31

32
#include "cppautocompleter.h"
con's avatar
con committed
33
#include "cppeditorconstants.h"
34
#include "cppeditoroutline.h"
35
#include "cppeditorplugin.h"
36
#include "cppdocumentationcommenthelper.h"
37
#include "cppfollowsymbolundercursor.h"
con's avatar
con committed
38
#include "cpphighlighter.h"
39
#include "cpplocalrenaming.h"
40
#include "cpppreprocessordialog.h"
Leandro Melo's avatar
Leandro Melo committed
41
#include "cppquickfixassistant.h"
Roberto Raggi's avatar
Roberto Raggi committed
42

43 44
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
45

46
#include <cpptools/cppchecksymbols.h>
Christian Kamm's avatar
Christian Kamm committed
47
#include <cpptools/cppcodeformatter.h>
48
#include <cpptools/cppcompletionassistprovider.h>
49
#include <cpptools/cpphighlightingsupport.h>
Nikolai Kosjar's avatar
Nikolai Kosjar committed
50
#include <cpptools/cppmodelmanagerinterface.h>
51
#include <cpptools/cppqtstyleindenter.h>
52 53 54
#include <cpptools/cppsemanticinfo.h>
#include <cpptools/cpptoolseditorsupport.h>
#include <cpptools/cpptoolsplugin.h>
55
#include <cpptools/cpptoolsreuse.h>
56
#include <cpptools/symbolfinder.h>
57 58 59

#include <projectexplorer/session.h>

con's avatar
con committed
60
#include <texteditor/basetextdocument.h>
61
#include <texteditor/basetextdocumentlayout.h>
62 63 64
#include <texteditor/codeassist/basicproposalitem.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/genericproposal.h>
con's avatar
con committed
65
#include <texteditor/fontsettings.h>
66
#include <texteditor/refactoroverlay.h>
67 68 69 70

#include <utils/qtcassert.h>

#include <cplusplus/ASTPath.h>
71
#include <cplusplus/BackwardsScanner.h>
72 73
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/OverviewModel.h>
con's avatar
con committed
74

75
#include <QAction>
76
#include <QFutureWatcher>
77
#include <QMenu>
78 79 80 81
#include <QPointer>
#include <QSignalMapper>
#include <QTextEdit>
#include <QTimer>
82
#include <QToolButton>
con's avatar
con committed
83

Roberto Raggi's avatar
Roberto Raggi committed
84
enum {
85 86
    UPDATE_USES_INTERVAL = 500,
    UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL = 200
Roberto Raggi's avatar
Roberto Raggi committed
87 88
};

Roberto Raggi's avatar
Roberto Raggi committed
89
using namespace CPlusPlus;
90
using namespace CppTools;
Roberto Raggi's avatar
Roberto Raggi committed
91 92
using namespace CppEditor::Internal;

con's avatar
con committed
93 94
namespace {

95
class CanonicalSymbol
96 97
{
public:
98
    CPPEditorWidget *editor;
99 100 101
    TypeOfExpression typeOfExpression;
    SemanticInfo info;

102
    CanonicalSymbol(CPPEditorWidget *editor, const SemanticInfo &info)
Erik Verbruggen's avatar
Erik Verbruggen committed
103
        : editor(editor), info(info)
104 105
    {
        typeOfExpression.init(info.doc, info.snapshot);
106
        typeOfExpression.setExpandTemplates(true);
107 108 109 110 111 112 113
    }

    const LookupContext &context() const
    {
        return typeOfExpression.context();
    }

114 115 116 117 118
    Scope *getScopeAndExpression(const QTextCursor &cursor, QString *code)
    {
        return getScopeAndExpression(editor, info, cursor, code);
    }

119
    static Scope *getScopeAndExpression(CPPEditorWidget *editor, const SemanticInfo &info,
120 121
                                        const QTextCursor &cursor,
                                        QString *code)
122
    {
123
        if (!info.doc)
124 125 126 127 128 129 130 131 132 133
            return 0;

        QTextCursor tc = cursor;
        int line, col;
        editor->convertPosition(tc.position(), &line, &col);
        ++col; // 1-based line and 1-based column

        QTextDocument *document = editor->document();

        int pos = tc.position();
134

135 136
        if (!isValidIdentifierChar(document->characterAt(pos)))
            if (!(pos > 0 && isValidIdentifierChar(document->characterAt(pos - 1))))
137 138
                return 0;

139
        while (isValidIdentifierChar(document->characterAt(pos)))
140 141 142
            ++pos;
        tc.setPosition(pos);

143 144 145 146 147 148 149 150 151 152 153
        ExpressionUnderCursor expressionUnderCursor;
        *code = expressionUnderCursor(tc);
        return info.doc->scopeAt(line, col);
    }

    Symbol *operator()(const QTextCursor &cursor)
    {
        QString code;

        if (Scope *scope = getScopeAndExpression(cursor, &code))
            return operator()(scope, code);
154

155 156 157 158 159 160 161 162
        return 0;
    }

    Symbol *operator()(Scope *scope, const QString &code)
    {
        return canonicalSymbol(scope, code, typeOfExpression);
    }

Nikolai Kosjar's avatar
Nikolai Kosjar committed
163 164
    static Symbol *canonicalSymbol(Scope *scope, const QString &code,
                                   TypeOfExpression &typeOfExpression)
165
    {
166 167
        const QList<LookupItem> results =
                typeOfExpression(code.toUtf8(), scope, TypeOfExpression::Preprocess);
168

Roberto Raggi's avatar
Roberto Raggi committed
169 170
        for (int i = results.size() - 1; i != -1; --i) {
            const LookupItem &r = results.at(i);
171
            Symbol *decl = r.declaration();
Roberto Raggi's avatar
Roberto Raggi committed
172

173
            if (!(decl && decl->enclosingScope()))
Roberto Raggi's avatar
Roberto Raggi committed
174 175
                break;

176
            if (Class *classScope = r.declaration()->enclosingScope()->asClass()) {
177 178 179
                const Identifier *declId = decl->identifier();
                const Identifier *classId = classScope->identifier();

180
                if (classId && classId->match(declId))
181 182
                    continue; // skip it, it's a ctor or a dtor.

183
                if (Function *funTy = r.declaration()->type()->asFunctionType()) {
184 185 186 187
                    if (funTy->isVirtual())
                        return r.declaration();
                }
            }
Roberto Raggi's avatar
Roberto Raggi committed
188 189 190
        }

        for (int i = 0; i < results.size(); ++i) {
191 192 193 194 195 196 197 198
            const LookupItem &r = results.at(i);

            if (r.declaration())
                return r.declaration();
        }

        return 0;
    }
199

200 201
};

202 203 204 205 206 207 208 209
QTimer *newSingleShotTimer(QObject *parent, int msecInterval)
{
    QTimer *timer = new QTimer(parent);
    timer->setSingleShot(true);
    timer->setInterval(msecInterval);
    return timer;
}

con's avatar
con committed
210 211
} // end of anonymous namespace

212 213 214
namespace CppEditor {
namespace Internal {

215 216
CPPEditor::CPPEditor(CPPEditorWidget *editor)
    : BaseTextEditor(editor)
con's avatar
con committed
217
{
218 219 220
    m_context.add(CppEditor::Constants::C_CPPEDITOR);
    m_context.add(ProjectExplorer::Constants::LANG_CXX);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
221
    setDuplicateSupported(true);
con's avatar
con committed
222 223
}

224 225
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

226 227 228 229 230 231 232 233 234 235 236
class CPPEditorWidgetPrivate
{
public:
    CPPEditorWidgetPrivate(CPPEditorWidget *q);

public:
    CPPEditorWidget *q;

    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

    CPPEditorDocument *m_cppEditorDocument;
237 238
    CppEditorOutline *m_cppEditorOutline;

239 240
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

241 242 243 244
    QTimer *m_updateUsesTimer;
    QTimer *m_updateFunctionDeclDefLinkTimer;
    QHash<int, QTextCharFormat> m_semanticHighlightFormatMap;

245
    CppLocalRenaming m_localRenaming;
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

    CppTools::SemanticInfo m_lastSemanticInfo;
    QList<TextEditor::QuickFixOperation::Ptr> m_quickFixes;

    QScopedPointer<QFutureWatcher<TextEditor::HighlightingResult> > m_highlightWatcher;
    unsigned m_highlightRevision; // the editor revision that requested the highlight

    QScopedPointer<QFutureWatcher<QList<int> > > m_referencesWatcher;
    unsigned m_referencesRevision;
    int m_referencesCursorPosition;

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

    QScopedPointer<FollowSymbolUnderCursor> m_followSymbolUnderCursor;
    QToolButton *m_preprocessorButton;
};

CPPEditorWidgetPrivate::CPPEditorWidgetPrivate(CPPEditorWidget *q)
    : q(q)
    , m_modelManager(CppModelManagerInterface::instance())
    , m_cppEditorDocument(qobject_cast<CPPEditorDocument *>(q->baseTextDocument()))
268
    , m_cppEditorOutline(new CppEditorOutline(q))
269
    , m_cppDocumentationCommentHelper(q)
270
    , m_localRenaming(q)
271 272 273 274 275 276 277 278 279
    , m_highlightRevision(0)
    , m_referencesRevision(0)
    , m_referencesCursorPosition(0)
    , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
    , m_followSymbolUnderCursor(new FollowSymbolUnderCursor(q))
    , m_preprocessorButton(0)
{
}

280
CPPEditorWidget::CPPEditorWidget(QWidget *parent)
281
    : TextEditor::BaseTextEditorWidget(new CPPEditorDocument(), parent)
con's avatar
con committed
282
{
283
    baseTextDocument()->setIndenter(new CppTools::CppQtStyleIndenter);
284 285 286 287 288 289 290 291 292 293 294
    ctor();
}

CPPEditorWidget::CPPEditorWidget(CPPEditorWidget *other)
    : TextEditor::BaseTextEditorWidget(other)
{
    ctor();
}

void CPPEditorWidget::ctor()
{
295
    d.reset(new CPPEditorWidgetPrivate(this));
296

297
    qRegisterMetaType<SemanticInfo>("CppTools::SemanticInfo");
Roberto Raggi's avatar
Roberto Raggi committed
298

con's avatar
con committed
299 300
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
301
    setCodeFoldingSupported(true);
302
    setAutoCompleter(new CppAutoCompleter);
dt's avatar
dt committed
303

304 305
    if (d->m_modelManager) {
        CppEditorSupport *editorSupport = d->m_modelManager->cppEditorSupport(editor());
306 307 308 309
        connect(editorSupport, SIGNAL(documentUpdated()),
                this, SLOT(onDocumentUpdated()));
        connect(editorSupport, SIGNAL(semanticInfoUpdated(CppTools::SemanticInfo)),
                this, SLOT(updateSemanticInfo(CppTools::SemanticInfo)));
Eike Ziller's avatar
Eike Ziller committed
310 311
        connect(editorSupport, SIGNAL(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)),
                this, SLOT(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)));
con's avatar
con committed
312
    }
313

314 315 316
    connect(this, SIGNAL(refactorMarkerClicked(TextEditor::RefactorMarker)),
            this, SLOT(onRefactorMarkerClicked(TextEditor::RefactorMarker)));

317
    connect(d->m_declDefLinkFinder, SIGNAL(foundLink(QSharedPointer<FunctionDeclDefLink>)),
318
            this, SLOT(onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink>)));
319

320 321
    connect(baseTextDocument(), SIGNAL(filePathChanged(QString,QString)),
            this, SLOT(onFilePathChanged()));
322 323 324 325 326

    connect(&d->m_localRenaming, SIGNAL(finished()),
            this, SLOT(onLocalRenamingFinished()));
    connect(&d->m_localRenaming, SIGNAL(processKeyPressNormally(QKeyEvent*)),
            this, SLOT(onLocalRenamingProcessKeyPressNormally(QKeyEvent*)));
con's avatar
con committed
327 328
}

329
CPPEditorWidget::~CPPEditorWidget()
con's avatar
con committed
330
{
331 332
    if (d->m_modelManager)
        d->m_modelManager->deleteCppEditorSupport(editor());
con's avatar
con committed
333 334
}

335 336
CPPEditorDocument *CPPEditorWidget::cppEditorDocument() const
{
337
    return d->m_cppEditorDocument;
338 339
}

340 341 342 343 344
CppEditorOutline *CPPEditorWidget::outline() const
{
    return d->m_cppEditorOutline;
}

345
TextEditor::BaseTextEditor *CPPEditorWidget::createEditor()
con's avatar
con committed
346
{
347
    CPPEditor *editable = new CPPEditor(this);
con's avatar
con committed
348 349 350 351
    createToolBar(editable);
    return editable;
}

352
void CPPEditorWidget::createToolBar(CPPEditor *editor)
con's avatar
con committed
353
{
354
    d->m_updateUsesTimer = newSingleShotTimer(this, UPDATE_USES_INTERVAL);
355 356
    connect(d->m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

357
    d->m_updateFunctionDeclDefLinkTimer = newSingleShotTimer(this, UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL);
358
    connect(d->m_updateFunctionDeclDefLinkTimer, SIGNAL(timeout()),
Nikolai Kosjar's avatar
Nikolai Kosjar committed
359
            this, SLOT(updateFunctionDeclDefLinkNow()));
360

361 362
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
363

364
    // set up slots to document changes
365 366
    connect(document(), SIGNAL(contentsChange(int,int,int)),
            this, SLOT(onContentsChanged(int,int,int)));
con's avatar
con committed
367

368 369 370
    // set up function declaration - definition link
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateFunctionDeclDefLink()));
    connect(this, SIGNAL(textChanged()), this, SLOT(updateFunctionDeclDefLink()));
Roberto Raggi's avatar
Roberto Raggi committed
371 372 373 374 375

    // set up the semantic highlighter
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateUses()));
    connect(this, SIGNAL(textChanged()), this, SLOT(updateUses()));

376 377
    d->m_preprocessorButton = new QToolButton(this);
    d->m_preprocessorButton->setText(QLatin1String("#"));
378 379 380
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePreprocessorButtonTooltip()));
    updatePreprocessorButtonTooltip();
381 382
    connect(d->m_preprocessorButton, SIGNAL(clicked()), this, SLOT(showPreProcessorWidget()));
    editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, d->m_preprocessorButton);
383
    editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, d->m_cppEditorOutline->widget());
con's avatar
con committed
384 385
}

386
void CPPEditorWidget::paste()
mae's avatar
mae committed
387
{
388
    if (d->m_localRenaming.handlePaste())
mae's avatar
mae committed
389 390
        return;

391
    BaseTextEditorWidget::paste();
mae's avatar
mae committed
392 393
}

394
void CPPEditorWidget::cut()
mae's avatar
mae committed
395
{
396
    if (d->m_localRenaming.handlePaste())
mae's avatar
mae committed
397 398
        return;

399
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
400 401
}

402 403
void CPPEditorWidget::selectAll()
{
404
    if (d->m_localRenaming.handleSelectAll())
mae's avatar
mae committed
405
        return;
406

407
    BaseTextEditorWidget::selectAll();
408 409
}

410 411 412
/// \brief Called by \c CppEditorSupport when the document corresponding to the
///        file in this editor is updated.
void CPPEditorWidget::onDocumentUpdated()
con's avatar
con committed
413
{
414
    d->m_cppEditorOutline->update();
con's avatar
con committed
415 416
}

417
const Macro *CPPEditorWidget::findCanonicalMacro(const QTextCursor &cursor, Document::Ptr doc) const
Christian Kamm's avatar
Christian Kamm committed
418
{
419
    if (!doc)
Christian Kamm's avatar
Christian Kamm committed
420 421 422 423 424
        return 0;

    int line, col;
    convertPosition(cursor.position(), &line, &col);

425 426
    if (const Macro *macro = doc->findMacroDefinitionAt(line)) {
        QTextCursor macroCursor = cursor;
427
        const QByteArray name = identifierUnderCursor(&macroCursor).toUtf8();
428
        if (macro->name() == name)
429 430
            return macro;
    } else if (const Document::MacroUse *use = doc->findMacroUseAt(cursor.position())) {
431
        return &use->macro();
432
    }
Christian Kamm's avatar
Christian Kamm committed
433 434 435

    return 0;
}
436

437
void CPPEditorWidget::findUsages()
438
{
439
    if (!d->m_modelManager)
440 441
        return;

442
    SemanticInfo info = d->m_lastSemanticInfo;
443
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
444
    info.snapshot.insert(info.doc);
445

446
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
447
        d->m_modelManager->findMacroUsages(*macro);
448 449 450 451
    } else {
        CanonicalSymbol cs(this, info);
        Symbol *canonicalSymbol = cs(textCursor());
        if (canonicalSymbol)
452
            d->m_modelManager->findUsages(canonicalSymbol, cs.context());
453
    }
454 455
}

Nikolai Kosjar's avatar
Nikolai Kosjar committed
456
void CPPEditorWidget::renameUsages(const QString &replacement)
457
{
458
    if (!d->m_modelManager)
459 460
        return;

461
    SemanticInfo info = d->m_lastSemanticInfo;
462
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
463 464
    info.snapshot.insert(info.doc);

465
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
466
        d->m_modelManager->renameMacroUsages(*macro, replacement);
467 468 469 470
    } else {
        CanonicalSymbol cs(this, info);
        if (Symbol *canonicalSymbol = cs(textCursor()))
            if (canonicalSymbol->identifier() != 0)
471
                d->m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement);
472
    }
473 474
}

475
void CPPEditorWidget::markSymbolsNow()
476
{
477 478 479 480 481
    QTC_ASSERT(d->m_referencesWatcher, return);
    if (!d->m_referencesWatcher->isCanceled()
            && d->m_referencesCursorPosition == position()
            && d->m_referencesRevision == editorRevision()) {
        const SemanticInfo info = d->m_lastSemanticInfo;
Erik Verbruggen's avatar
Erik Verbruggen committed
482
        TranslationUnit *unit = info.doc->translationUnit();
483
        const QList<int> result = d->m_referencesWatcher->result();
484

Erik Verbruggen's avatar
Erik Verbruggen committed
485
        QList<QTextEdit::ExtraSelection> selections;
486

Erik Verbruggen's avatar
Erik Verbruggen committed
487 488 489
        foreach (int index, result) {
            unsigned line, column;
            unit->getTokenPosition(index, &line, &column);
490

Erik Verbruggen's avatar
Erik Verbruggen committed
491 492
            if (column)
                --column;  // adjust the column position.
493

494
            const int len = unit->tokenAt(index).utf16chars();
495

Erik Verbruggen's avatar
Erik Verbruggen committed
496 497 498
            QTextCursor cursor(document()->findBlockByNumber(line - 1));
            cursor.setPosition(cursor.position() + column);
            cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor);
499

Erik Verbruggen's avatar
Erik Verbruggen committed
500
            QTextEdit::ExtraSelection sel;
501
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Erik Verbruggen's avatar
Erik Verbruggen committed
502 503 504
            sel.cursor = cursor;
            selections.append(sel);
        }
505

Erik Verbruggen's avatar
Erik Verbruggen committed
506
        setExtraSelections(CodeSemanticsSelection, selections);
Roberto Raggi's avatar
Roberto Raggi committed
507
    }
508
    d->m_referencesWatcher.reset();
Roberto Raggi's avatar
Roberto Raggi committed
509 510
}

Nikolai Kosjar's avatar
Nikolai Kosjar committed
511 512
static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr doc,
                                     Snapshot snapshot)
513 514
{
    TypeOfExpression typeOfExpression;
515 516
    snapshot.insert(doc);
    typeOfExpression.init(doc, snapshot);
517 518
    // make possible to instantiate templates
    typeOfExpression.setExpandTemplates(true);
519
    if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
520 521
        return CppModelManagerInterface::instance()->references(canonicalSymbol,
                                                                typeOfExpression.context());
522 523 524
    return QList<int>();
}

525
void CPPEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &info)
526
{
527
    d->m_localRenaming.stop();
528

529
    if (!info.doc)
530
        return;
531
    const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES);
532 533 534 535 536 537
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
        QList<QTextEdit::ExtraSelection> selections;

        //Macro definition
        if (macro->fileName() == info.doc->fileName()) {
            QTextCursor cursor(document());
538
            cursor.setPosition(macro->utf16CharOffset());
Nikolai Kosjar's avatar
Nikolai Kosjar committed
539
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
540
                                macro->nameToQString().size());
541 542

            QTextEdit::ExtraSelection sel;
543
            sel.format = occurrencesFormat;
544 545 546 547 548
            sel.cursor = cursor;
            selections.append(sel);
        }

        //Other macro uses
549
        foreach (const Document::MacroUse &use, info.doc->macroUses()) {
550 551
            const Macro &useMacro = use.macro();
            if (useMacro.line() != macro->line()
552
                    || useMacro.utf16CharOffset() != macro->utf16CharOffset()
553 554
                    || useMacro.length() != macro->length()
                    || useMacro.fileName() != macro->fileName())
555 556 557
                continue;

            QTextCursor cursor(document());
558 559
            cursor.setPosition(use.utf16charsBegin());
            cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor);
560 561

            QTextEdit::ExtraSelection sel;
562
            sel.format = occurrencesFormat;
563 564 565
            sel.cursor = cursor;
            selections.append(sel);
        }
566

567 568 569 570 571
        setExtraSelections(CodeSemanticsSelection, selections);
    } else {
        CanonicalSymbol cs(this, info);
        QString expression;
        if (Scope *scope = cs.getScopeAndExpression(this, info, tc, &expression)) {
572 573 574 575 576 577 578 579 580
            if (d->m_referencesWatcher)
                d->m_referencesWatcher->cancel();
            d->m_referencesWatcher.reset(new QFutureWatcher<QList<int> >);
            connect(d->m_referencesWatcher.data(), SIGNAL(finished()), SLOT(markSymbolsNow()));

            d->m_referencesRevision = info.revision;
            d->m_referencesCursorPosition = position();
            d->m_referencesWatcher->setFuture(
                QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot));
581 582 583
        } else {
            const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);

584
            if (!selections.isEmpty())
585 586
                setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
        }
587 588 589
    }
}

590
void CPPEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
591
{
592
    if (!d->m_modelManager)
593 594
        return;

595 596
    CppEditorSupport *ces = d->m_modelManager->cppEditorSupport(editor());
    updateSemanticInfo(ces->recalculateSemanticInfo());
597

598 599
    if (!d->m_localRenaming.start()) // Rename local symbol
        renameUsages(); // Rename non-local symbol or macro
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
600 601
}

602
void CPPEditorWidget::onContentsChanged(int position, int charsRemoved, int charsAdded)
603
{
604 605
    Q_UNUSED(position)
    Q_UNUSED(charsAdded)
606 607 608 609 610

    if (charsRemoved > 0)
        updateUses();
}

611 612
void CPPEditorWidget::updatePreprocessorButtonTooltip()
{
613
    QTC_ASSERT(d->m_preprocessorButton, return);
614 615
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    QTC_ASSERT(cmd, return);
616
    d->m_preprocessorButton->setToolTip(cmd->action()->toolTip());
617 618
}

619 620
QList<QTextEdit::ExtraSelection> CPPEditorWidget::createSelectionsFromUses(
        const QList<SemanticInfo::Use> &uses)
Roberto Raggi's avatar
Roberto Raggi committed
621
{
622 623
    QList<QTextEdit::ExtraSelection> result;
    const bool isUnused = uses.size() == 1;
Roberto Raggi's avatar
Roberto Raggi committed
624

Roberto Raggi's avatar
Roberto Raggi committed
625
    foreach (const SemanticInfo::Use &use, uses) {
626 627
        if (use.isInvalid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
628

629
        QTextEdit::ExtraSelection sel;
Roberto Raggi's avatar
Roberto Raggi committed
630
        if (isUnused)
631
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES_UNUSED);
Roberto Raggi's avatar
Roberto Raggi committed
632
        else
633
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Roberto Raggi's avatar
Roberto Raggi committed
634

635 636
        const int position = document()->findBlockByNumber(use.line - 1).position() + use.column - 1;
        const int anchor = position + use.length;
Roberto Raggi's avatar
Roberto Raggi committed
637

638
        sel.cursor = QTextCursor(document());
Roberto Raggi's avatar
Roberto Raggi committed
639 640
        sel.cursor.setPosition(anchor);
        sel.cursor.setPosition(position, QTextCursor::KeepAnchor);
Roberto Raggi's avatar
Roberto Raggi committed
641

642
        result.append(sel);
Roberto Raggi's avatar
Roberto Raggi committed
643
    }
644 645

    return result;
Roberto Raggi's avatar
Roberto Raggi committed
646 647
}

648
void CPPEditorWidget::updateUses()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
649
{
650
    // Block premature semantic info calculation when editor is created.
651 652
    if (d->m_modelManager && d->m_modelManager->cppEditorSupport(editor())->initialized())
        d->m_updateUsesTimer->start();
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
653 654
}

655
void CPPEditorWidget::updateUsesNow()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
656
{
657
    if (d->m_localRenaming.isActive())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
658 659
        return;

Roberto Raggi's avatar
Roberto Raggi committed
660
    semanticRehighlight();
con's avatar
con committed
661 662
}

663
void CPPEditorWidget::highlightSymbolUsages(int from, int to)
664
{
665
    if (editorRevision() != d->m_highlightRevision)
666 667
        return; // outdated

668
    else if (!d->m_highlightWatcher || d->m_highlightWatcher->isCanceled())
669 670
        return; // aborted

671 672
    TextEditor::SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
    QTC_ASSERT(highlighter, return);
673

674
    TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
675
                highlighter, d->m_highlightWatcher->future(), from, to, d->m_semanticHighlightFormatMap);
676 677
}

678
void CPPEditorWidget::finishHighlightSymbolUsages()
679
{
680 681 682 683
    QTC_ASSERT(d->m_highlightWatcher, return);
    if (!d->m_highlightWatcher->isCanceled()
            && editorRevision() == d->m_highlightRevision
            && !d->m_lastSemanticInfo.doc.isNull()) {
Erik Verbruggen's avatar
Erik Verbruggen committed
684 685 686 687
        TextEditor::SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
        QTC_CHECK(highlighter);
        if (highlighter)
            TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(highlighter,
688
                d->m_highlightWatcher->future());
Erik Verbruggen's avatar
Erik Verbruggen committed
689
    }
690
    d->m_highlightWatcher.reset();
691 692
}

693
void CPPEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
694
{
695
    if (!d->m_modelManager)
con's avatar
con committed
696 697
        return;

698
    if (!d->m_lastSemanticInfo.doc)
699
        return;
con's avatar
con committed
700

701 702 703 704
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

705
    ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    const QList<AST *> astPath = astPathFinder(textCursor());

    for (int i = 0, size = astPath.size(); i < size; ++i) {
        AST *ast = astPath.at(i);
        if (FunctionDefinitionAST *functionDefinitionAST = ast->asFunctionDefinition()) {
            if ((functionDefinitionSymbol = functionDefinitionAST->symbol))
                break; // Function definition found!
        } else if (SimpleDeclarationAST *simpleDeclaration = ast->asSimpleDeclaration()) {
            if (List<Symbol *> *symbols = simpleDeclaration->symbols) {
                if (Symbol *symbol = symbols->value) {
                    if (symbol->isDeclaration() && symbol->type()->isFunctionType()) {
                        functionDeclarationSymbol = symbol;
                        break; // Function declaration found!
                    }
                }
            }
        }
    }
con's avatar
con committed
724

725 726 727 728
    // Link to function definition/declaration
    CPPEditorWidget::Link symbolLink;
    if (functionDeclarationSymbol) {
        symbolLink = linkToSymbol(symbolFinder()
729
            ->findMatchingDefinition(functionDeclarationSymbol, d->m_modelManager->snapshot()));
730
    } else if (functionDefinitionSymbol) {
731 732
        const Snapshot snapshot = d->m_modelManager->snapshot();
        LookupContext context(d->m_lastSemanticInfo.doc, snapshot);
733 734 735 736 737 738 739 740
        ClassOrNamespace *binding = context.lookupType(functionDefinitionSymbol);
        const QList<LookupItem> declarations = context.lookup(functionDefinitionSymbol->name(),
            functionDefinitionSymbol->enclosingScope());

        QList<Symbol *> best;
        foreach (const LookupItem &r, declarations) {
            if (Symbol *decl = r.declaration()) {
                if (Function *funTy = decl->type()->asFunctionType()) {
741
                    if (funTy->match(functionDefinitionSymbol)) {
742 743 744 745
                        if (decl != functionDefinitionSymbol && binding == r.binding())
                            best.prepend(decl);
                        else
                            best.append(decl);
746 747
                    }
                }
748 749
            }
        }
750

751 752 753
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
754
    }
755 756 757 758

    // Open Editor at link position
    if (symbolLink.hasValidTarget())
        openCppEditorAt(symbolLink, inNextSplit != alwaysOpenLinksInNextSplit());
con's avatar
con committed
759 760
}

761
QString CPPEditorWidget::identifierUnderCursor(QTextCursor *macroCursor)
762 763 764 765 766 767
{
    macroCursor->movePosition(QTextCursor::StartOfWord);
    macroCursor->movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    return macroCursor->selectedText();
}

768 769
CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
                                                  bool inNextSplit)
con's avatar
con committed
770
{
771
    if (!d->m_modelManager)
772
        return Link();
773

774 775 776 777 778
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
779 780
}

781
unsigned CPPEditorWidget::editorRevision() const
782 783 784 785
{
    return document()->revision();
}

786
bool CPPEditorWidget::isOutdated() const
787
{
788
    if (d->m_lastSemanticInfo.revision != editorRevision())
789 790 791 792 793
        return true;

    return false;
}

794
SemanticInfo CPPEditorWidget::semanticInfo() const
Roberto Raggi's avatar
Roberto Raggi committed
795
{
796
    return d->m_lastSemanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
797 798
}

799
bool CPPEditorWidget::event(QEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
800 801 802
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
803
        // handle escape manually if a rename is active
804
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && d->m_localRenaming.isActive()) {
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
805 806 807 808 809 810 811 812
            e->accept();
            return true;
        }
        break;
    default:
        break;
    }

813
    return BaseTextEditorWidget::event(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
814 815
}