cppeditor.cpp 28.1 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 "cppeditordocument.h"
37
#include "cppeditoroutline.h"
38
#include "cppeditorplugin.h"
39
#include "cppfollowsymbolundercursor.h"
con's avatar
con committed
40
#include "cpphighlighter.h"
41
#include "cpplocalrenaming.h"
42
#include "cpppreprocessordialog.h"
Leandro Melo's avatar
Leandro Melo committed
43
#include "cppquickfixassistant.h"
44
#include "cppuseselectionsupdater.h"
Roberto Raggi's avatar
Roberto Raggi committed
45

46 47
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
48

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

#include <projectexplorer/session.h>

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

#include <cplusplus/ASTPath.h>
72
#include <utils/qtcassert.h>
con's avatar
con committed
73

74
#include <QAction>
75
#include <QElapsedTimer>
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

84
enum { UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL = 200 };
Roberto Raggi's avatar
Roberto Raggi committed
85

Roberto Raggi's avatar
Roberto Raggi committed
86
using namespace CPlusPlus;
87
using namespace CppTools;
88
using namespace TextEditor;
Roberto Raggi's avatar
Roberto Raggi committed
89

90 91 92
namespace CppEditor {
namespace Internal {

93
CppEditor::CppEditor()
con's avatar
con committed
94
{
95
    addContext(ProjectExplorer::Constants::LANG_CXX);
con's avatar
con committed
96 97
}

98 99
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

100
class CppEditorWidgetPrivate
101 102
{
public:
103
    CppEditorWidgetPrivate(CppEditorWidget *q);
104 105 106 107

public:
    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

108
    CppEditorDocument *m_cppEditorDocument;
109 110
    CppEditorOutline *m_cppEditorOutline;

111 112
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

113
    QTimer m_updateFunctionDeclDefLinkTimer;
114

115
    CppLocalRenaming m_localRenaming;
116 117 118 119

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

120
    CppUseSelectionsUpdater m_useSelectionsUpdater;
121 122 123 124 125 126 127 128

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

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

129
CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q)
130
    : m_modelManager(CppModelManagerInterface::instance())
131
    , m_cppEditorDocument(qobject_cast<CppEditorDocument *>(q->textDocument()))
132
    , m_cppEditorOutline(new CppEditorOutline(q))
133
    , m_cppDocumentationCommentHelper(q)
134
    , m_localRenaming(q)
135
    , m_useSelectionsUpdater(q)
136 137 138 139 140 141
    , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
    , m_followSymbolUnderCursor(new FollowSymbolUnderCursor(q))
    , m_preprocessorButton(0)
{
}

142 143
CppEditorWidget::CppEditorWidget()
   : d(new CppEditorWidgetPrivate(this))
144
{
145
    qRegisterMetaType<SemanticInfo>("CppTools::SemanticInfo");
146
}
147

148 149 150
void CppEditorWidget::finalizeInitialization()
{
    d->m_cppEditorDocument = qobject_cast<CppEditorDocument *>(textDocument());
151

152
    setLanguageSettingsId(CppTools::Constants::CPP_SETTINGS_ID);
153
    setCodeFoldingSupported(true);
154 155
    setMarksVisible(true);
    setParenthesesMatchingEnabled(true);
156
    setRevisionsVisible(true);
dt's avatar
dt committed
157

158 159 160 161
    // function combo box sorting
    connect(CppEditorPlugin::instance(), &CppEditorPlugin::outlineSortingChanged,
            outline(), &CppEditorOutline::setSorted);

162
    connect(d->m_cppEditorDocument, &CppEditorDocument::codeWarningsUpdated,
163
            this, &CppEditorWidget::onCodeWarningsUpdated);
164
    connect(d->m_cppEditorDocument, &CppEditorDocument::ifdefedOutBlocksUpdated,
165 166 167 168 169
            this, &CppEditorWidget::onIfdefedOutBlocksUpdated);
    connect(d->m_cppEditorDocument, SIGNAL(cppDocumentUpdated(CPlusPlus::Document::Ptr)),
            this, SLOT(onCppDocumentUpdated()));
    connect(d->m_cppEditorDocument, SIGNAL(semanticInfoUpdated(CppTools::SemanticInfo)),
            this, SLOT(updateSemanticInfo(CppTools::SemanticInfo)));
170

171
    connect(d->m_declDefLinkFinder, SIGNAL(foundLink(QSharedPointer<FunctionDeclDefLink>)),
172
            this, SLOT(onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink>)));
173

174
    connect(textDocument(), SIGNAL(filePathChanged(QString,QString)),
175
            this, SLOT(onFilePathChanged()));
176

177 178 179 180
    connect(&d->m_useSelectionsUpdater,
            SIGNAL(selectionsForVariableUnderCursorUpdated(QList<QTextEdit::ExtraSelection>)),
            &d->m_localRenaming,
            SLOT(updateSelectionsForVariableUnderCursor(QList<QTextEdit::ExtraSelection>)));
181

182 183 184 185 186 187
    connect(&d->m_useSelectionsUpdater, &CppUseSelectionsUpdater::finished,
            [this] (CppTools::SemanticInfo::LocalUseMap localUses) {
                QTC_CHECK(isSemanticInfoValidExceptLocalUses());
                d->m_lastSemanticInfo.localUsesUpdated = true;
                d->m_lastSemanticInfo.localUses = localUses;
    });
188

189 190 191 192 193
    connect(&d->m_localRenaming, &CppLocalRenaming::finished, [this] {
        cppEditorDocument()->semanticRehighlight();
    });
    connect(&d->m_localRenaming, &CppLocalRenaming::processKeyPressNormally,
            this, &CppEditorWidget::processKeyNormally);
194 195
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
196

197
    // set up function declaration - definition link
198 199 200 201
    d->m_updateFunctionDeclDefLinkTimer.setSingleShot(true);
    d->m_updateFunctionDeclDefLinkTimer.setInterval(UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL);
    connect(&d->m_updateFunctionDeclDefLinkTimer, SIGNAL(timeout()),
            this, SLOT(updateFunctionDeclDefLinkNow()));
202 203
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateFunctionDeclDefLink()));
    connect(this, SIGNAL(textChanged()), this, SLOT(updateFunctionDeclDefLink()));
Roberto Raggi's avatar
Roberto Raggi committed
204

205 206 207 208 209
    // set up the use highlighitng
    connect(this, &CppEditorWidget::cursorPositionChanged, [this]() {
        if (!d->m_localRenaming.isActive())
            d->m_useSelectionsUpdater.scheduleUpdate();
    });
Roberto Raggi's avatar
Roberto Raggi committed
210

211
    // Tool bar creation
212 213
    d->m_preprocessorButton = new QToolButton(this);
    d->m_preprocessorButton->setText(QLatin1String("#"));
214 215 216
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePreprocessorButtonTooltip()));
    updatePreprocessorButtonTooltip();
217
    connect(d->m_preprocessorButton, SIGNAL(clicked()), this, SLOT(showPreProcessorWidget()));
218 219
    insertExtraToolBarWidget(TextEditor::BaseTextEditorWidget::Left, d->m_preprocessorButton);
    insertExtraToolBarWidget(TextEditor::BaseTextEditorWidget::Left, d->m_cppEditorOutline->widget());
220
}
221

222 223 224 225 226 227 228 229 230 231 232
void CppEditorWidget::finalizeInitializationAfterDuplication(BaseTextEditorWidget *other)
{
    QTC_ASSERT(other, return);
    CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(other);
    QTC_ASSERT(cppEditorWidget, return);

    if (cppEditorWidget->isSemanticInfoValidExceptLocalUses())
        updateSemanticInfo(cppEditorWidget->semanticInfo());
    d->m_cppEditorOutline->update();
    const ExtraSelectionKind selectionKind = CodeWarningsSelection;
    setExtraSelections(selectionKind, cppEditorWidget->extraSelections(selectionKind));
con's avatar
con committed
233 234
}

235 236
CppEditorWidget::~CppEditorWidget()
{
237 238 239
    // non-inline destructor, see section "Forward Declared Pointers" of QScopedPointer.
}

240
CppEditorDocument *CppEditorWidget::cppEditorDocument() const
241 242 243 244 245 246 247 248 249
{
    return d->m_cppEditorDocument;
}

CppEditorOutline *CppEditorWidget::outline() const
{
    return d->m_cppEditorOutline;
}

250
void CppEditorWidget::paste()
mae's avatar
mae committed
251
{
252
    if (d->m_localRenaming.handlePaste())
mae's avatar
mae committed
253 254
        return;

255
    BaseTextEditorWidget::paste();
mae's avatar
mae committed
256 257
}

258
void CppEditorWidget::cut()
mae's avatar
mae committed
259
{
260
    if (d->m_localRenaming.handleCut())
mae's avatar
mae committed
261 262
        return;

263
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
264 265
}

266
void CppEditorWidget::selectAll()
267
{
268
    if (d->m_localRenaming.handleSelectAll())
mae's avatar
mae committed
269
        return;
270

271
    BaseTextEditorWidget::selectAll();
272 273
}

274
void CppEditorWidget::onCppDocumentUpdated()
con's avatar
con committed
275
{
276
    d->m_cppEditorOutline->update();
con's avatar
con committed
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
void CppEditorWidget::onCodeWarningsUpdated(unsigned revision,
                                            const QList<QTextEdit::ExtraSelection> selections)
{
    if (revision != documentRevision())
        return;
    setExtraSelections(BaseTextEditorWidget::CodeWarningsSelection, selections);
}

void CppEditorWidget::onIfdefedOutBlocksUpdated(unsigned revision,
    const QList<TextEditor::BlockRange> ifdefedOutBlocks)
{
    if (revision != documentRevision())
        return;
    setIfdefedOutBlocks(ifdefedOutBlocks);
}

295
void CppEditorWidget::findUsages()
296
{
297
    if (!d->m_modelManager)
298 299
        return;

300
    SemanticInfo info = d->m_lastSemanticInfo;
301
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
302
    info.snapshot.insert(info.doc);
303

304
    if (const Macro *macro = CppTools::findCanonicalMacro(textCursor(), info.doc)) {
305
        d->m_modelManager->findMacroUsages(*macro);
306
    } else {
307
        CanonicalSymbol cs(info.doc, info.snapshot);
308 309
        Symbol *canonicalSymbol = cs(textCursor());
        if (canonicalSymbol)
310
            d->m_modelManager->findUsages(canonicalSymbol, cs.context());
311
    }
312 313
}

314
void CppEditorWidget::renameUsages(const QString &replacement)
315
{
316
    if (!d->m_modelManager)
317 318
        return;

319
    SemanticInfo info = d->m_lastSemanticInfo;
320
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
321 322
    info.snapshot.insert(info.doc);

323
    if (const Macro *macro = CppTools::findCanonicalMacro(textCursor(), info.doc)) {
324
        d->m_modelManager->renameMacroUsages(*macro, replacement);
325
    } else {
326
        CanonicalSymbol cs(info.doc, info.snapshot);
327 328
        if (Symbol *canonicalSymbol = cs(textCursor()))
            if (canonicalSymbol->identifier() != 0)
329
                d->m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement);
330
    }
331 332
}

333
void CppEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
334
{
335
    d->m_useSelectionsUpdater.abortSchedule();
336 337
    updateSemanticInfo(d->m_cppEditorDocument->recalculateSemanticInfo(),
                       /*updateUseSelectionSynchronously=*/ true);
338

339 340
    if (!d->m_localRenaming.start()) // Rename local symbol
        renameUsages(); // Rename non-local symbol or macro
341 342
}

343
void CppEditorWidget::updatePreprocessorButtonTooltip()
344
{
345
    QTC_ASSERT(d->m_preprocessorButton, return);
346 347
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    QTC_ASSERT(cmd, return);
348
    d->m_preprocessorButton->setToolTip(cmd->action()->toolTip());
349 350
}

351
void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
352
{
353
    if (!d->m_modelManager)
con's avatar
con committed
354 355
        return;

356
    if (!d->m_lastSemanticInfo.doc)
357
        return;
con's avatar
con committed
358

359 360 361 362
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

363
    ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    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
382

383
    // Link to function definition/declaration
384
    CppEditorWidget::Link symbolLink;
385 386
    if (functionDeclarationSymbol) {
        symbolLink = linkToSymbol(symbolFinder()
387
            ->findMatchingDefinition(functionDeclarationSymbol, d->m_modelManager->snapshot()));
388
    } else if (functionDefinitionSymbol) {
389 390
        const Snapshot snapshot = d->m_modelManager->snapshot();
        LookupContext context(d->m_lastSemanticInfo.doc, snapshot);
391 392 393 394 395 396 397 398
        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()) {
399
                    if (funTy->match(functionDefinitionSymbol)) {
400 401 402 403
                        if (decl != functionDefinitionSymbol && binding == r.binding())
                            best.prepend(decl);
                        else
                            best.append(decl);
404 405
                    }
                }
406 407
            }
        }
408

409 410 411
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
412
    }
413 414 415 416

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

419
CppEditorWidget::Link CppEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
420
                                                  bool inNextSplit)
con's avatar
con committed
421
{
422
    if (!d->m_modelManager)
423
        return Link();
424

425 426 427 428 429
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
430 431
}

432
unsigned CppEditorWidget::documentRevision() const
433 434 435 436
{
    return document()->revision();
}

437
bool CppEditorWidget::isSemanticInfoValidExceptLocalUses() const
438
{
439 440 441
    return d->m_lastSemanticInfo.doc
            && d->m_lastSemanticInfo.revision == documentRevision()
            && !d->m_lastSemanticInfo.snapshot.isEmpty();
442
}
443

444 445 446
bool CppEditorWidget::isSemanticInfoValid() const
{
    return isSemanticInfoValidExceptLocalUses() && d->m_lastSemanticInfo.localUsesUpdated;
447 448
}

449
SemanticInfo CppEditorWidget::semanticInfo() const
Roberto Raggi's avatar
Roberto Raggi committed
450
{
451
    return d->m_lastSemanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
452 453
}

454
bool CppEditorWidget::event(QEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
455 456 457
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
458
        // handle escape manually if a rename is active
459
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && d->m_localRenaming.isActive()) {
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
460 461 462 463 464 465 466 467
            e->accept();
            return true;
        }
        break;
    default:
        break;
    }

468
    return BaseTextEditorWidget::event(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
469 470
}

471
void CppEditorWidget::performQuickFix(int index)
472
{
473
    TextEditor::QuickFixOperation::Ptr op = d->m_quickFixes.at(index);
474
    op->perform();
475 476
}

477 478 479 480 481
void CppEditorWidget::processKeyNormally(QKeyEvent *e)
{
    BaseTextEditorWidget::keyPressEvent(e);
}

482
void CppEditorWidget::contextMenuEvent(QContextMenuEvent *e)
con's avatar
con committed
483
{
Roberto Raggi's avatar
Roberto Raggi committed
484 485 486
    // ### enable
    // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource()));

487
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
488

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

492
    QMenu *quickFixMenu = new QMenu(tr("&Refactor"), menu);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
493 494
    quickFixMenu->addAction(Core::ActionManager::command(
                                Constants::RENAME_SYMBOL_UNDER_CURSOR)->action());
495 496 497

    QSignalMapper mapper;
    connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int)));
498
    if (isSemanticInfoValid()) {
Leandro Melo's avatar
Leandro Melo committed
499 500 501 502
        TextEditor::IAssistInterface *interface =
            createAssistInterface(TextEditor::QuickFix, TextEditor::ExplicitlyInvoked);
        if (interface) {
            QScopedPointer<TextEditor::IAssistProcessor> processor(
503
                        CppEditorPlugin::instance()->quickFixProvider()->createProcessor());
Leandro Melo's avatar
Leandro Melo committed
504 505 506 507 508 509 510 511 512
            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>();
513
                    d->m_quickFixes.append(op);
Leandro Melo's avatar
Leandro Melo committed
514 515 516 517 518
                    QAction *action = quickFixMenu->addAction(op->description());
                    mapper.setMapping(action, index);
                    connect(action, SIGNAL(triggered()), &mapper, SLOT(map()));
                }
                delete model;
519 520 521 522
            }
        }
    }

523
    foreach (QAction *action, contextMenu->actions()) {
con's avatar
con committed
524
        menu->addAction(action);
525
        if (action->objectName() == QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT))
526 527
            menu->addMenu(quickFixMenu);
    }
con's avatar
con committed
528

529 530
    appendStandardContextMenuActions(menu);

con's avatar
con committed
531
    menu->exec(e->globalPos());
532 533
    if (!menu)
        return;
534
    d->m_quickFixes.clear();
con's avatar
con committed
535 536 537
    delete menu;
}

538
void CppEditorWidget::keyPressEvent(QKeyEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
539
{
540
    if (d->m_localRenaming.handleKeyPressEvent(e))
541 542
        return;

543 544 545 546
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

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

549
void CppEditorWidget::applyFontSettings()
con's avatar
con committed
550
{
551
    // This also makes the document apply font settings
552
    TextEditor::BaseTextEditorWidget::applyFontSettings();
con's avatar
con committed
553 554
}

555
void CppEditorWidget::slotCodeStyleSettingsChanged(const QVariant &)
556 557 558 559 560
{
    CppTools::QtStyleCodeFormatter formatter;
    formatter.invalidateCache(document());
}

561
CppEditorWidget::Link CppEditorWidget::linkToSymbol(CPlusPlus::Symbol *symbol)
562
{
563 564 565
    if (!symbol)
        return Link();

David Schulz's avatar
David Schulz committed
566
    const QString filename = QString::fromUtf8(symbol->fileName(),
567
                                               symbol->fileNameLength());
David Schulz's avatar
David Schulz committed
568

569 570
    unsigned line = symbol->line();
    unsigned column = symbol->column();
571

572 573
    if (column)
        --column;
574

575
    if (symbol->isGenerated())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
576
        column = 0;
577

David Schulz's avatar
David Schulz committed
578
    return Link(filename, line, column);
579 580
}

581
bool CppEditorWidget::openCppEditorAt(const Link &link, bool inNextSplit)
582
{
583
    if (!link.hasValidTarget())
584 585
        return false;

Eike Ziller's avatar
Eike Ziller committed
586
    Core::EditorManager::OpenEditorFlags flags;
587 588
    if (inNextSplit)
        flags |= Core::EditorManager::OpenInOtherSplit;
589 590 591
    return Core::EditorManager::openEditorAt(link.targetFileName,
                                             link.targetLine,
                                             link.targetColumn,
592 593
                                             Constants::CPPEDITOR_ID,
                                             flags);
con's avatar
con committed
594
}
Roberto Raggi's avatar
Roberto Raggi committed
595

596 597
void CppEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo,
                                         bool updateUseSelectionSynchronously)
Roberto Raggi's avatar
Roberto Raggi committed
598
{
599
    if (semanticInfo.revision != documentRevision())
Roberto Raggi's avatar
Roberto Raggi committed
600
        return;
Roberto Raggi's avatar
Roberto Raggi committed
601

602
    d->m_lastSemanticInfo = semanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
603

604 605 606 607 608 609
    if (!d->m_localRenaming.isActive()) {
        const CppUseSelectionsUpdater::CallType type = updateUseSelectionSynchronously
                ? CppUseSelectionsUpdater::Synchronous
                : CppUseSelectionsUpdater::Asynchronous;
        d->m_useSelectionsUpdater.update(type);
    }
610 611 612

    // schedule a check for a decl/def link
    updateFunctionDeclDefLink();
Roberto Raggi's avatar
Roberto Raggi committed
613 614
}

615
TextEditor::IAssistInterface *CppEditorWidget::createAssistInterface(
Leandro Melo's avatar
Leandro Melo committed
616 617 618 619
    TextEditor::AssistKind kind,
    TextEditor::AssistReason reason) const
{
    if (kind == TextEditor::Completion) {
620
        if (CppCompletionAssistProvider *cap = cppEditorDocument()->completionAssistProvider()) {
621
            return cap->createAssistInterface(
622
                            ProjectExplorer::ProjectExplorerPlugin::currentProject(),
623 624 625 626
                            textDocument()->filePath(),
                            document(),
                            cppEditorDocument()->isObjCEnabled(),
                            position(),
627
                            reason);
628
        }
Leandro Melo's avatar
Leandro Melo committed
629
    } else if (kind == TextEditor::QuickFix) {
630
        if (!isSemanticInfoValid())
Leandro Melo's avatar
Leandro Melo committed
631
            return 0;
632
        return new CppQuickFixAssistInterface(const_cast<CppEditorWidget *>(this), reason);
633 634
    } else {
        return BaseTextEditorWidget::createAssistInterface(kind, reason);
Leandro Melo's avatar
Leandro Melo committed
635 636 637 638
    }
    return 0;
}

639
QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const
640
{
641
    return d->m_declDefLink;
642 643
}

644
void CppEditorWidget::onRefactorMarkerClicked(const TextEditor::RefactorMarker &marker)
645 646 647 648 649
{
    if (marker.data.canConvert<FunctionDeclDefLink::Marker>())
        applyDeclDefLinkChanges(true);
}

650
void CppEditorWidget::updateFunctionDeclDefLink()
651 652 653
{
    const int pos = textCursor().selectionStart();

654
    // if there's already a link, abort it if the cursor is outside or the name changed
655
    // (adding a prefix is an exception since the user might type a return type)
656 657 658 659 660
    if (d->m_declDefLink
            && (pos < d->m_declDefLink->linkSelection.selectionStart()
                || pos > d->m_declDefLink->linkSelection.selectionEnd()
                || !d->m_declDefLink->nameSelection.selectedText().trimmed()
                    .endsWith(d->m_declDefLink->nameInitial))) {
661 662 663 664 665
        abortDeclDefLink();
        return;
    }

    // don't start a new scan if there's one active and the cursor is already in the scanned area
666
    const QTextCursor scannedSelection = d->m_declDefLinkFinder->scannedSelection();
667 668 669 670 671 672
    if (!scannedSelection.isNull()
            && scannedSelection.selectionStart() <= pos
            && scannedSelection.selectionEnd() >= pos) {
        return;
    }

673
    d->m_updateFunctionDeclDefLinkTimer.start();
674 675
}

676
void CppEditorWidget::updateFunctionDeclDefLinkNow()
677
{
678 679 680 681
    static bool noTracking = qgetenv("QTC_NO_FUNCTION_DECL_DEF_LINK_TRACKING").trimmed() == "1";
    if (noTracking)
        return;

682
    if (Core::EditorManager::currentEditor()->widget() != this)
683
        return;
684

685 686
    const Snapshot semanticSnapshot = d->m_lastSemanticInfo.snapshot;
    const Document::Ptr semanticDoc = d->m_lastSemanticInfo.doc;
687

688
    if (d->m_declDefLink) {
689
        // update the change marker
690
        const Utils::ChangeSet changes = d->m_declDefLink->changes(semanticSnapshot);
691
        if (changes.isEmpty())
692
            d->m_declDefLink->hideMarker(this);
693
        else
694
            d->m_declDefLink->showMarker(this);
695 696
        return;
    }
697 698

    if (!isSemanticInfoValidExceptLocalUses())
699 700 701
        return;

    Snapshot snapshot = CppModelManagerInterface::instance()->snapshot();
702
    snapshot.insert(semanticDoc);
703

704
    d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot);
705 706
}

707
void CppEditorWidget::onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink> link)
708 709
{
    abortDeclDefLink();
710 711 712
    d->m_declDefLink = link;
    Core::IDocument *targetDocument
            = Core::DocumentModel::documentForFilePath( d->m_declDefLink->targetFile->fileName());
713
    if (textDocument() != targetDocument) {
714 715
        if (auto textDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
            connect(textDocument, SIGNAL(contentsChanged()),
716
                    this, SLOT(abortDeclDefLink()));
717
    }
718

719 720
}

721
void CppEditorWidget::onFilePathChanged()
722
{
723
    QTC_ASSERT(d->m_modelManager, return);
724
    QByteArray additionalDirectives;
725
    const QString &filePath = textDocument()->filePath();
726 727 728 729 730 731
    if (!filePath.isEmpty()) {
        const QString &projectFile = ProjectExplorer::SessionManager::value(
                    QLatin1String(Constants::CPP_PREPROCESSOR_PROJECT_PREFIX) + filePath).toString();
        additionalDirectives = ProjectExplorer::SessionManager::value(
                    projectFile + QLatin1Char(',') + filePath).toString().toUtf8();

732 733
        BaseEditorDocumentParser *parser = BaseEditorDocumentParser::get(filePath);
        QTC_ASSERT(parser, return);
734 735
        parser->setProjectPart(d->m_modelManager->projectPartForProjectFile(projectFile));
        parser->setEditorDefines(additionalDirectives);
736
    }
737 738
    d->m_preprocessorButton->setProperty("highlightWidget", !additionalDirectives.trimmed().isEmpty());
    d->m_preprocessorButton->update();
739 740
}

741
void CppEditorWidget::applyDeclDefLinkChanges(bool jumpToMatch)
742
{
743
    if (!d->m_declDefLink)
744
        return;
745
    d->m_declDefLink->apply(this, jumpToMatch);
746
    abortDeclDefLink();
747 748 749
    updateFunctionDeclDefLink();
}

750
FollowSymbolUnderCursor *CppEditorWidget::followSymbolUnderCursorDelegate()
751
{
752
    return d->m_followSymbolUnderCursor.data();
753 754
}

755 756 757 758 759 760 761
CompletionAssistProvider *CppEditorWidget::completionAssistProvider() const
{
    auto document = qobject_cast<CppEditorDocument *>(textDocument());
    QTC_ASSERT(document, return 0);
    return document->completionAssistProvider();
}

762
void CppEditorWidget::abortDeclDefLink()
763
{
764
    if (!d->m_declDefLink)
765
        return;
766

767 768
    Core::IDocument *targetDocument
            = Core::DocumentModel::documentForFilePath(d->m_declDefLink->targetFile->fileName());
769
    if (textDocument() != targetDocument) {
770 771
        if (auto textDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
            disconnect(textDocument, SIGNAL(contentsChanged()),
772
                    this, SLOT(abortDeclDefLink()));
773 774
    }

775 776
    d->m_declDefLink->hideMarker(this);
    d->m_declDefLink.clear();
777 778
}

779
void CppEditorWidget::showPreProcessorWidget()
780
{
781
    const QString &fileName = textDocument()->filePath();
782

783
    // Check if this editor belongs to a project
784
    QList<ProjectPart::Ptr> projectParts = d->m_modelManager->projectPart(fileName);
785
    if (projectParts.isEmpty())
786
        projectParts = d->m_modelManager->projectPartFromDependencies(fileName);
787
    if (projectParts.isEmpty())
788
        projectParts << d->m_modelManager->fallbackProjectPart();