cppeditor.cpp 40.2 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"
33 34
#include "cppcanonicalsymbol.h"
#include "cppdocumentationcommenthelper.h"
con's avatar
con committed
35
#include "cppeditorconstants.h"
36
#include "cppeditoroutline.h"
37
#include "cppeditorplugin.h"
38
#include "cppfollowsymbolundercursor.h"
con's avatar
con committed
39
#include "cpphighlighter.h"
40
#include "cpplocalrenaming.h"
41
#include "cpppreprocessordialog.h"
Leandro Melo's avatar
Leandro Melo committed
42
#include "cppquickfixassistant.h"
Roberto Raggi's avatar
Roberto Raggi committed
43

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

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

#include <projectexplorer/session.h>

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

#include <utils/qtcassert.h>

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

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

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

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

con's avatar
con committed
94 95
namespace {

96 97 98 99 100 101 102 103
QTimer *newSingleShotTimer(QObject *parent, int msecInterval)
{
    QTimer *timer = new QTimer(parent);
    timer->setSingleShot(true);
    timer->setInterval(msecInterval);
    return timer;
}

con's avatar
con committed
104 105
} // end of anonymous namespace

106 107 108
namespace CppEditor {
namespace Internal {

109 110
CPPEditor::CPPEditor(CPPEditorWidget *editor)
    : BaseTextEditor(editor)
con's avatar
con committed
111
{
112 113 114
    m_context.add(CppEditor::Constants::C_CPPEDITOR);
    m_context.add(ProjectExplorer::Constants::LANG_CXX);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
115
    setDuplicateSupported(true);
116
    setCommentStyle(Utils::CommentDefinition::CppStyle);
con's avatar
con committed
117 118
}

119 120
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

121 122 123 124 125 126 127 128 129 130 131
class CPPEditorWidgetPrivate
{
public:
    CPPEditorWidgetPrivate(CPPEditorWidget *q);

public:
    CPPEditorWidget *q;

    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

    CPPEditorDocument *m_cppEditorDocument;
132 133
    CppEditorOutline *m_cppEditorOutline;

134 135
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

136 137 138 139
    QTimer *m_updateUsesTimer;
    QTimer *m_updateFunctionDeclDefLinkTimer;
    QHash<int, QTextCharFormat> m_semanticHighlightFormatMap;

140
    CppLocalRenaming m_localRenaming;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

    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()))
163
    , m_cppEditorOutline(new CppEditorOutline(q))
164
    , m_cppDocumentationCommentHelper(q)
165
    , m_localRenaming(q)
166 167 168 169 170 171 172 173 174
    , m_highlightRevision(0)
    , m_referencesRevision(0)
    , m_referencesCursorPosition(0)
    , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
    , m_followSymbolUnderCursor(new FollowSymbolUnderCursor(q))
    , m_preprocessorButton(0)
{
}

175
CPPEditorWidget::CPPEditorWidget(QWidget *parent)
176
    : TextEditor::BaseTextEditorWidget(new CPPEditorDocument(), parent)
con's avatar
con committed
177
{
178
    baseTextDocument()->setIndenter(new CppTools::CppQtStyleIndenter);
179 180 181 182 183 184 185 186 187 188 189
    ctor();
}

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

void CPPEditorWidget::ctor()
{
190
    d.reset(new CPPEditorWidgetPrivate(this));
191

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

con's avatar
con committed
194 195
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
196
    setCodeFoldingSupported(true);
197
    setAutoCompleter(new CppAutoCompleter);
dt's avatar
dt committed
198

199 200
    if (d->m_modelManager) {
        CppEditorSupport *editorSupport = d->m_modelManager->cppEditorSupport(editor());
201 202 203 204
        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
205 206
        connect(editorSupport, SIGNAL(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)),
                this, SLOT(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)));
con's avatar
con committed
207
    }
208

209 210 211
    connect(this, SIGNAL(refactorMarkerClicked(TextEditor::RefactorMarker)),
            this, SLOT(onRefactorMarkerClicked(TextEditor::RefactorMarker)));

212
    connect(d->m_declDefLinkFinder, SIGNAL(foundLink(QSharedPointer<FunctionDeclDefLink>)),
213
            this, SLOT(onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink>)));
214

215 216
    connect(baseTextDocument(), SIGNAL(filePathChanged(QString,QString)),
            this, SLOT(onFilePathChanged()));
217 218 219 220 221

    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
222 223
}

224
CPPEditorWidget::~CPPEditorWidget()
con's avatar
con committed
225
{
226 227
    if (d->m_modelManager)
        d->m_modelManager->deleteCppEditorSupport(editor());
con's avatar
con committed
228 229
}

230 231
CPPEditorDocument *CPPEditorWidget::cppEditorDocument() const
{
232
    return d->m_cppEditorDocument;
233 234
}

235 236 237 238 239
CppEditorOutline *CPPEditorWidget::outline() const
{
    return d->m_cppEditorOutline;
}

240
TextEditor::BaseTextEditor *CPPEditorWidget::createEditor()
con's avatar
con committed
241
{
242
    CPPEditor *editable = new CPPEditor(this);
con's avatar
con committed
243 244 245 246
    createToolBar(editable);
    return editable;
}

247
void CPPEditorWidget::createToolBar(CPPEditor *editor)
con's avatar
con committed
248
{
249
    d->m_updateUsesTimer = newSingleShotTimer(this, UPDATE_USES_INTERVAL);
250 251
    connect(d->m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

252
    d->m_updateFunctionDeclDefLinkTimer = newSingleShotTimer(this, UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL);
253
    connect(d->m_updateFunctionDeclDefLinkTimer, SIGNAL(timeout()),
Nikolai Kosjar's avatar
Nikolai Kosjar committed
254
            this, SLOT(updateFunctionDeclDefLinkNow()));
255

256 257
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
258

259
    // set up slots to document changes
260 261
    connect(document(), SIGNAL(contentsChange(int,int,int)),
            this, SLOT(onContentsChanged(int,int,int)));
con's avatar
con committed
262

263 264 265
    // 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
266 267 268 269 270

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

271 272
    d->m_preprocessorButton = new QToolButton(this);
    d->m_preprocessorButton->setText(QLatin1String("#"));
273 274 275
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePreprocessorButtonTooltip()));
    updatePreprocessorButtonTooltip();
276 277
    connect(d->m_preprocessorButton, SIGNAL(clicked()), this, SLOT(showPreProcessorWidget()));
    editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, d->m_preprocessorButton);
278
    editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, d->m_cppEditorOutline->widget());
con's avatar
con committed
279 280
}

281
void CPPEditorWidget::paste()
mae's avatar
mae committed
282
{
283
    if (d->m_localRenaming.handlePaste())
mae's avatar
mae committed
284 285
        return;

286
    BaseTextEditorWidget::paste();
mae's avatar
mae committed
287 288
}

289
void CPPEditorWidget::cut()
mae's avatar
mae committed
290
{
291
    if (d->m_localRenaming.handlePaste())
mae's avatar
mae committed
292 293
        return;

294
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
295 296
}

297 298
void CPPEditorWidget::selectAll()
{
299
    if (d->m_localRenaming.handleSelectAll())
mae's avatar
mae committed
300
        return;
301

302
    BaseTextEditorWidget::selectAll();
303 304
}

305 306 307
/// \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
308
{
309
    d->m_cppEditorOutline->update();
con's avatar
con committed
310 311
}

312
const Macro *CPPEditorWidget::findCanonicalMacro(const QTextCursor &cursor, Document::Ptr doc) const
Christian Kamm's avatar
Christian Kamm committed
313
{
314
    if (!doc)
Christian Kamm's avatar
Christian Kamm committed
315 316 317 318 319
        return 0;

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

320 321
    if (const Macro *macro = doc->findMacroDefinitionAt(line)) {
        QTextCursor macroCursor = cursor;
322
        const QByteArray name = identifierUnderCursor(&macroCursor).toUtf8();
323
        if (macro->name() == name)
324 325
            return macro;
    } else if (const Document::MacroUse *use = doc->findMacroUseAt(cursor.position())) {
326
        return &use->macro();
327
    }
Christian Kamm's avatar
Christian Kamm committed
328 329 330

    return 0;
}
331

332
void CPPEditorWidget::findUsages()
333
{
334
    if (!d->m_modelManager)
335 336
        return;

337
    SemanticInfo info = d->m_lastSemanticInfo;
338
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
339
    info.snapshot.insert(info.doc);
340

341
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
342
        d->m_modelManager->findMacroUsages(*macro);
343
    } else {
344
        CanonicalSymbol cs(this, info.doc, info.snapshot);
345 346
        Symbol *canonicalSymbol = cs(textCursor());
        if (canonicalSymbol)
347
            d->m_modelManager->findUsages(canonicalSymbol, cs.context());
348
    }
349 350
}

Nikolai Kosjar's avatar
Nikolai Kosjar committed
351
void CPPEditorWidget::renameUsages(const QString &replacement)
352
{
353
    if (!d->m_modelManager)
354 355
        return;

356
    SemanticInfo info = d->m_lastSemanticInfo;
357
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
358 359
    info.snapshot.insert(info.doc);

360
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
361
        d->m_modelManager->renameMacroUsages(*macro, replacement);
362
    } else {
363
        CanonicalSymbol cs(this, info.doc, info.snapshot);
364 365
        if (Symbol *canonicalSymbol = cs(textCursor()))
            if (canonicalSymbol->identifier() != 0)
366
                d->m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement);
367
    }
368 369
}

370
void CPPEditorWidget::markSymbolsNow()
371
{
372 373 374 375 376
    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
377
        TranslationUnit *unit = info.doc->translationUnit();
378
        const QList<int> result = d->m_referencesWatcher->result();
379

Erik Verbruggen's avatar
Erik Verbruggen committed
380
        QList<QTextEdit::ExtraSelection> selections;
381

Erik Verbruggen's avatar
Erik Verbruggen committed
382 383 384
        foreach (int index, result) {
            unsigned line, column;
            unit->getTokenPosition(index, &line, &column);
385

Erik Verbruggen's avatar
Erik Verbruggen committed
386 387
            if (column)
                --column;  // adjust the column position.
388

389
            const int len = unit->tokenAt(index).utf16chars();
390

Erik Verbruggen's avatar
Erik Verbruggen committed
391 392 393
            QTextCursor cursor(document()->findBlockByNumber(line - 1));
            cursor.setPosition(cursor.position() + column);
            cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor);
394

Erik Verbruggen's avatar
Erik Verbruggen committed
395
            QTextEdit::ExtraSelection sel;
396
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Erik Verbruggen's avatar
Erik Verbruggen committed
397 398 399
            sel.cursor = cursor;
            selections.append(sel);
        }
400

Erik Verbruggen's avatar
Erik Verbruggen committed
401
        setExtraSelections(CodeSemanticsSelection, selections);
Roberto Raggi's avatar
Roberto Raggi committed
402
    }
403
    d->m_referencesWatcher.reset();
Roberto Raggi's avatar
Roberto Raggi committed
404 405
}

Nikolai Kosjar's avatar
Nikolai Kosjar committed
406 407
static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr doc,
                                     Snapshot snapshot)
408 409
{
    TypeOfExpression typeOfExpression;
410 411
    snapshot.insert(doc);
    typeOfExpression.init(doc, snapshot);
412 413
    // make possible to instantiate templates
    typeOfExpression.setExpandTemplates(true);
414
    if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
415 416
        return CppModelManagerInterface::instance()->references(canonicalSymbol,
                                                                typeOfExpression.context());
417 418 419
    return QList<int>();
}

420
void CPPEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &info)
421
{
422
    d->m_localRenaming.stop();
423

424
    if (!info.doc)
425
        return;
426
    const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES);
427 428 429 430 431 432
    if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
        QList<QTextEdit::ExtraSelection> selections;

        //Macro definition
        if (macro->fileName() == info.doc->fileName()) {
            QTextCursor cursor(document());
433
            cursor.setPosition(macro->utf16CharOffset());
Nikolai Kosjar's avatar
Nikolai Kosjar committed
434
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
435
                                macro->nameToQString().size());
436 437

            QTextEdit::ExtraSelection sel;
438
            sel.format = occurrencesFormat;
439 440 441 442 443
            sel.cursor = cursor;
            selections.append(sel);
        }

        //Other macro uses
444
        foreach (const Document::MacroUse &use, info.doc->macroUses()) {
445 446
            const Macro &useMacro = use.macro();
            if (useMacro.line() != macro->line()
447
                    || useMacro.utf16CharOffset() != macro->utf16CharOffset()
448 449
                    || useMacro.length() != macro->length()
                    || useMacro.fileName() != macro->fileName())
450 451 452
                continue;

            QTextCursor cursor(document());
453 454
            cursor.setPosition(use.utf16charsBegin());
            cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor);
455 456

            QTextEdit::ExtraSelection sel;
457
            sel.format = occurrencesFormat;
458 459 460
            sel.cursor = cursor;
            selections.append(sel);
        }
461

462 463
        setExtraSelections(CodeSemanticsSelection, selections);
    } else {
464
        CanonicalSymbol cs(this, info.doc, info.snapshot);
465
        QString expression;
466
        if (Scope *scope = cs.getScopeAndExpression(tc, &expression)) {
467 468 469 470 471 472 473 474 475
            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));
476 477 478
        } else {
            const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);

479
            if (!selections.isEmpty())
480 481
                setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
        }
482 483 484
    }
}

485
void CPPEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
486
{
487
    if (!d->m_modelManager)
488 489
        return;

490 491
    CppEditorSupport *ces = d->m_modelManager->cppEditorSupport(editor());
    updateSemanticInfo(ces->recalculateSemanticInfo());
492

493 494
    if (!d->m_localRenaming.start()) // Rename local symbol
        renameUsages(); // Rename non-local symbol or macro
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
495 496
}

497
void CPPEditorWidget::onContentsChanged(int position, int charsRemoved, int charsAdded)
498
{
499 500
    Q_UNUSED(position)
    Q_UNUSED(charsAdded)
501 502 503 504 505

    if (charsRemoved > 0)
        updateUses();
}

506 507
void CPPEditorWidget::updatePreprocessorButtonTooltip()
{
508
    QTC_ASSERT(d->m_preprocessorButton, return);
509 510
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    QTC_ASSERT(cmd, return);
511
    d->m_preprocessorButton->setToolTip(cmd->action()->toolTip());
512 513
}

514 515
QList<QTextEdit::ExtraSelection> CPPEditorWidget::createSelectionsFromUses(
        const QList<SemanticInfo::Use> &uses)
Roberto Raggi's avatar
Roberto Raggi committed
516
{
517 518
    QList<QTextEdit::ExtraSelection> result;
    const bool isUnused = uses.size() == 1;
Roberto Raggi's avatar
Roberto Raggi committed
519

Roberto Raggi's avatar
Roberto Raggi committed
520
    foreach (const SemanticInfo::Use &use, uses) {
521 522
        if (use.isInvalid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
523

524
        QTextEdit::ExtraSelection sel;
Roberto Raggi's avatar
Roberto Raggi committed
525
        if (isUnused)
526
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES_UNUSED);
Roberto Raggi's avatar
Roberto Raggi committed
527
        else
528
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Roberto Raggi's avatar
Roberto Raggi committed
529

530 531
        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
532

533
        sel.cursor = QTextCursor(document());
Roberto Raggi's avatar
Roberto Raggi committed
534 535
        sel.cursor.setPosition(anchor);
        sel.cursor.setPosition(position, QTextCursor::KeepAnchor);
Roberto Raggi's avatar
Roberto Raggi committed
536

537
        result.append(sel);
Roberto Raggi's avatar
Roberto Raggi committed
538
    }
539 540

    return result;
Roberto Raggi's avatar
Roberto Raggi committed
541 542
}

543
void CPPEditorWidget::updateUses()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
544
{
545
    // Block premature semantic info calculation when editor is created.
546 547
    if (d->m_modelManager && d->m_modelManager->cppEditorSupport(editor())->initialized())
        d->m_updateUsesTimer->start();
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
548 549
}

550
void CPPEditorWidget::updateUsesNow()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
551
{
552
    if (d->m_localRenaming.isActive())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
553 554
        return;

Roberto Raggi's avatar
Roberto Raggi committed
555
    semanticRehighlight();
con's avatar
con committed
556 557
}

558
void CPPEditorWidget::highlightSymbolUsages(int from, int to)
559
{
560
    if (editorRevision() != d->m_highlightRevision)
561 562
        return; // outdated

563
    else if (!d->m_highlightWatcher || d->m_highlightWatcher->isCanceled())
564 565
        return; // aborted

566 567
    TextEditor::SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
    QTC_ASSERT(highlighter, return);
568

569
    TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
570
                highlighter, d->m_highlightWatcher->future(), from, to, d->m_semanticHighlightFormatMap);
571 572
}

573
void CPPEditorWidget::finishHighlightSymbolUsages()
574
{
575 576 577 578
    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
579 580 581 582
        TextEditor::SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
        QTC_CHECK(highlighter);
        if (highlighter)
            TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(highlighter,
583
                d->m_highlightWatcher->future());
Erik Verbruggen's avatar
Erik Verbruggen committed
584
    }
585
    d->m_highlightWatcher.reset();
586 587
}

588
void CPPEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
589
{
590
    if (!d->m_modelManager)
con's avatar
con committed
591 592
        return;

593
    if (!d->m_lastSemanticInfo.doc)
594
        return;
con's avatar
con committed
595

596 597 598 599
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

600
    ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    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
619

620 621 622 623
    // Link to function definition/declaration
    CPPEditorWidget::Link symbolLink;
    if (functionDeclarationSymbol) {
        symbolLink = linkToSymbol(symbolFinder()
624
            ->findMatchingDefinition(functionDeclarationSymbol, d->m_modelManager->snapshot()));
625
    } else if (functionDefinitionSymbol) {
626 627
        const Snapshot snapshot = d->m_modelManager->snapshot();
        LookupContext context(d->m_lastSemanticInfo.doc, snapshot);
628 629 630 631 632 633 634 635
        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()) {
636
                    if (funTy->match(functionDefinitionSymbol)) {
637 638 639 640
                        if (decl != functionDefinitionSymbol && binding == r.binding())
                            best.prepend(decl);
                        else
                            best.append(decl);
641 642
                    }
                }
643 644
            }
        }
645

646 647 648
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
649
    }
650 651 652 653

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

656
QString CPPEditorWidget::identifierUnderCursor(QTextCursor *macroCursor)
657 658 659 660 661 662
{
    macroCursor->movePosition(QTextCursor::StartOfWord);
    macroCursor->movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    return macroCursor->selectedText();
}

663 664
CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
                                                  bool inNextSplit)
con's avatar
con committed
665
{
666
    if (!d->m_modelManager)
667
        return Link();
668

669 670 671 672 673
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
674 675
}

676
unsigned CPPEditorWidget::editorRevision() const
677 678 679 680
{
    return document()->revision();
}

681
bool CPPEditorWidget::isOutdated() const
682
{
683
    if (d->m_lastSemanticInfo.revision != editorRevision())
684 685 686 687 688
        return true;

    return false;
}

689
SemanticInfo CPPEditorWidget::semanticInfo() const
Roberto Raggi's avatar
Roberto Raggi committed
690
{
691
    return d->m_lastSemanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
692 693
}

694
bool CPPEditorWidget::event(QEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
695 696 697
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
698
        // handle escape manually if a rename is active
699
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && d->m_localRenaming.isActive()) {
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
700 701 702 703 704 705 706 707
            e->accept();
            return true;
        }
        break;
    default:
        break;
    }

708
    return BaseTextEditorWidget::event(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
709 710
}

711
void CPPEditorWidget::performQuickFix(int index)
712
{
713
    TextEditor::QuickFixOperation::Ptr op = d->m_quickFixes.at(index);
714
    op->perform();
715 716
}

717
void CPPEditorWidget::contextMenuEvent(QContextMenuEvent *e)
con's avatar
con committed
718
{
Roberto Raggi's avatar
Roberto Raggi committed
719 720 721
    // ### enable
    // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource()));

722
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
723

Eike Ziller's avatar
Eike Ziller committed
724
    Core::ActionContainer *mcontext = Core::ActionManager::actionContainer(Constants::M_CONTEXT);
con's avatar
con committed
725 726
    QMenu *contextMenu = mcontext->menu();

727
    QMenu *quickFixMenu = new QMenu(tr("&Refactor"), menu);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
728 729
    quickFixMenu->addAction(Core::ActionManager::command(
                                Constants::RENAME_SYMBOL_UNDER_CURSOR)->action());
730 731 732

    QSignalMapper mapper;
    connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int)));
733
    if (!isOutdated()) {
Leandro Melo's avatar
Leandro Melo committed
734 735 736 737
        TextEditor::IAssistInterface *interface =
            createAssistInterface(TextEditor::QuickFix, TextEditor::ExplicitlyInvoked);
        if (interface) {
            QScopedPointer<TextEditor::IAssistProcessor> processor(
738
                        CppEditorPlugin::instance()->quickFixProvider()->createProcessor());
Leandro Melo's avatar
Leandro Melo committed
739 740 741 742 743 744 745 746 747
            QScopedPointer<TextEditor::IAssistProposal> proposal(processor->perform(interface));
            if (!proposal.isNull()) {
                TextEditor::BasicProposalItemListModel *model =
                        static_cast<TextEditor::BasicProposalItemListModel *>(proposal->model());
                for (int index = 0; index < model->size(); ++index) {
                    TextEditor::BasicProposalItem *item =
                            static_cast<TextEditor::BasicProposalItem *>(model->proposalItem(index));
                    TextEditor::QuickFixOperation::Ptr op =
                            item->data().value<TextEditor::QuickFixOperation::Ptr>();
748
                    d->m_quickFixes.append(op);
Leandro Melo's avatar
Leandro Melo committed
749 750 751 752 753
                    QAction *action = quickFixMenu->addAction(op->description());
                    mapper.setMapping(action, index);
                    connect(action, SIGNAL(triggered()), &mapper, SLOT(map()));
                }
                delete model;
754 755 756 757
            }
        }
    }

758
    foreach (QAction *action, contextMenu->actions()) {
con's avatar
con committed
759
        menu->addAction(action);
760
        if (action->objectName() == QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT))
761 762
            menu->addMenu(quickFixMenu);
    }
con's avatar
con committed
763

764 765
    appendStandardContextMenuActions(menu);

con's avatar
con committed
766
    menu->exec(e->globalPos());
767 768
    if (!menu)
        return;
769
    d->m_quickFixes.clear();
con's avatar
con committed
770 771 772
    delete menu;
}

773
void CPPEditorWidget::keyPressEvent(QKeyEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
774
{
775
    if (d->m_localRenaming.handleKeyPressEvent(e))
776 777
        return;

778 779 780 781
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

    TextEditor::BaseTextEditorWidget::keyPressEvent(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
782 783
}

784
Core::IEditor *CPPEditor::duplicate()
con's avatar
con committed
785
{
786 787
    CPPEditorWidget *newEditor = new CPPEditorWidget(
                qobject_cast<CPPEditorWidget *>(editorWidget()));
788
    CppEditorPlugin::instance()->initializeEditor(newEditor);
789
    return newEditor->editor();
con's avatar
con committed
790 791
}

792
bool CPPEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
dt's avatar
dt committed
793
{
794 795
    if (!TextEditor::BaseTextEditor::open(errorString, fileName, realFileName))
        return false;
796
    baseTextDocument()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
797
    return true;
dt's avatar
dt committed
798 799
}

800 801 802 803 804
TextEditor::CompletionAssistProvider *CPPEditor::completionAssistProvider()
{
    return CppModelManagerInterface::instance()->cppEditorSupport(this)->completionAssistProvider();
}

805
void CPPEditorWidget::applyFontSettings()
con's avatar
con committed
806
{
807
    const TextEditor::FontSettings &fs = baseTextDocument()->fontSettings();
Erik Verbruggen's avatar
Erik Verbruggen committed
808

809
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::TypeUse] =
810
            fs.toTextCharFormat(TextEditor::C_TYPE);
811
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::LocalUse] =
812
            fs.toTextCharFormat(TextEditor::C_LOCAL);
813
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::FieldUse] =