cppeditor.cpp 28.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"
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 96
    m_context.add(ProjectExplorer::Constants::LANG_CXX);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
con's avatar
con committed
97 98
}

99 100
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

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

public:
    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

109
    CppEditorDocument *m_cppEditorDocument;
110 111
    CppEditorOutline *m_cppEditorOutline;

112 113
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

114
    QTimer m_updateFunctionDeclDefLinkTimer;
115

116
    CppLocalRenaming m_localRenaming;
117 118 119 120

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

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

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

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

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

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

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

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

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

163
    connect(d->m_cppEditorDocument, &CppEditorDocument::codeWarningsUpdated,
164
            this, &CppEditorWidget::onCodeWarningsUpdated);
165
    connect(d->m_cppEditorDocument, &CppEditorDocument::ifdefedOutBlocksUpdated,
166 167 168 169 170
            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)));
171

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

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

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

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

190 191 192 193 194
    connect(&d->m_localRenaming, &CppLocalRenaming::finished, [this] {
        cppEditorDocument()->semanticRehighlight();
    });
    connect(&d->m_localRenaming, &CppLocalRenaming::processKeyPressNormally,
            this, &CppEditorWidget::processKeyNormally);
195

196 197
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
198

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

207 208 209 210 211
    // 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
212

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

224 225 226 227 228 229 230 231 232 233 234
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
235 236
}

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

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

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

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

257
    BaseTextEditorWidget::paste();
mae's avatar
mae committed
258 259
}

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

265
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
266 267
}

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

273
    BaseTextEditorWidget::selectAll();
274 275
}

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

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
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);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

489
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
490

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

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

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

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

531 532
    appendStandardContextMenuActions(menu);

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

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

545 546 547 548
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

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

551
bool CppEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
dt's avatar
dt committed
552
{
553 554
    if (!TextEditor::BaseTextEditor::open(errorString, fileName, realFileName))
        return false;
555
    textDocument()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
556
    return true;
dt's avatar
dt committed
557 558
}

559
void CppEditorWidget::applyFontSettings()
con's avatar
con committed
560
{
561
    // This also makes the document apply font settings
562
    TextEditor::BaseTextEditorWidget::applyFontSettings();
con's avatar
con committed
563 564
}

565
void CppEditorWidget::slotCodeStyleSettingsChanged(const QVariant &)
566 567 568 569 570
{
    CppTools::QtStyleCodeFormatter formatter;
    formatter.invalidateCache(document());
}

571
CppEditorWidget::Link CppEditorWidget::linkToSymbol(CPlusPlus::Symbol *symbol)
572
{
573 574 575
    if (!symbol)
        return Link();

David Schulz's avatar
David Schulz committed
576
    const QString filename = QString::fromUtf8(symbol->fileName(),
577
                                               symbol->fileNameLength());
David Schulz's avatar
David Schulz committed
578

579 580
    unsigned line = symbol->line();
    unsigned column = symbol->column();
581

582 583
    if (column)
        --column;
584

585
    if (symbol->isGenerated())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
586
        column = 0;
587

David Schulz's avatar
David Schulz committed
588
    return Link(filename, line, column);
589 590
}

591
bool CppEditorWidget::openCppEditorAt(const Link &link, bool inNextSplit)
592
{
593
    if (!link.hasValidTarget())
594 595
        return false;

Eike Ziller's avatar
Eike Ziller committed
596
    Core::EditorManager::OpenEditorFlags flags;
597 598
    if (inNextSplit)
        flags |= Core::EditorManager::OpenInOtherSplit;
599 600 601
    return Core::EditorManager::openEditorAt(link.targetFileName,
                                             link.targetLine,
                                             link.targetColumn,
602 603
                                             Constants::CPPEDITOR_ID,
                                             flags);
con's avatar
con committed
604
}
Roberto Raggi's avatar
Roberto Raggi committed
605

606 607
void CppEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo,
                                         bool updateUseSelectionSynchronously)
Roberto Raggi's avatar
Roberto Raggi committed
608
{
609
    if (semanticInfo.revision != documentRevision())
Roberto Raggi's avatar
Roberto Raggi committed
610
        return;
Roberto Raggi's avatar
Roberto Raggi committed
611

612
    d->m_lastSemanticInfo = semanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
613

614 615 616 617 618 619
    if (!d->m_localRenaming.isActive()) {
        const CppUseSelectionsUpdater::CallType type = updateUseSelectionSynchronously
                ? CppUseSelectionsUpdater::Synchronous
                : CppUseSelectionsUpdater::Asynchronous;
        d->m_useSelectionsUpdater.update(type);
    }
620 621 622

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

625
TextEditor::IAssistInterface *CppEditorWidget::createAssistInterface(
Leandro Melo's avatar
Leandro Melo committed
626 627 628 629
    TextEditor::AssistKind kind,
    TextEditor::AssistReason reason) const
{
    if (kind == TextEditor::Completion) {
630
        if (CppCompletionAssistProvider *cap = cppEditorDocument()->completionAssistProvider()) {
631
            return cap->createAssistInterface(
632
                            ProjectExplorer::ProjectExplorerPlugin::currentProject(),
633 634 635 636
                            textDocument()->filePath(),
                            document(),
                            cppEditorDocument()->isObjCEnabled(),
                            position(),
637
                            reason);
638
        }
Leandro Melo's avatar
Leandro Melo committed
639
    } else if (kind == TextEditor::QuickFix) {
640
        if (!isSemanticInfoValid())
Leandro Melo's avatar
Leandro Melo committed
641
            return 0;
642
        return new CppQuickFixAssistInterface(const_cast<CppEditorWidget *>(this), reason);
643 644
    } else {
        return BaseTextEditorWidget::createAssistInterface(kind, reason);
Leandro Melo's avatar
Leandro Melo committed
645 646 647 648
    }
    return 0;
}

649
QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const
650
{
651
    return d->m_declDefLink;
652 653
}

654
void CppEditorWidget::onRefactorMarkerClicked(const TextEditor::RefactorMarker &marker)
655 656 657 658 659
{
    if (marker.data.canConvert<FunctionDeclDefLink::Marker>())
        applyDeclDefLinkChanges(true);
}

660
void CppEditorWidget::updateFunctionDeclDefLink()
661 662 663
{
    const int pos = textCursor().selectionStart();

664
    // if there's already a link, abort it if the cursor is outside or the name changed
665
    // (adding a prefix is an exception since the user might type a return type)
666 667 668 669 670
    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))) {
671 672 673 674 675
        abortDeclDefLink();
        return;
    }

    // don't start a new scan if there's one active and the cursor is already in the scanned area
676
    const QTextCursor scannedSelection = d->m_declDefLinkFinder->scannedSelection();
677 678 679 680 681 682
    if (!scannedSelection.isNull()
            && scannedSelection.selectionStart() <= pos
            && scannedSelection.selectionEnd() >= pos) {
        return;
    }

683
    d->m_updateFunctionDeclDefLinkTimer.start();
684 685
}

686
void CppEditorWidget::updateFunctionDeclDefLinkNow()
687
{
688
    if (Core::EditorManager::currentEditor()->widget() != this)
689
        return;
690

691 692
    const Snapshot semanticSnapshot = d->m_lastSemanticInfo.snapshot;
    const Document::Ptr semanticDoc = d->m_lastSemanticInfo.doc;
693

694
    if (d->m_declDefLink) {
695
        // update the change marker
696
        const Utils::ChangeSet changes = d->m_declDefLink->changes(semanticSnapshot);
697
        if (changes.isEmpty())
698
            d->m_declDefLink->hideMarker(this);
699
        else
700
            d->m_declDefLink->showMarker(this);
701 702
        return;
    }
703 704

    if (!isSemanticInfoValidExceptLocalUses())
705 706 707
        return;

    Snapshot snapshot = CppModelManagerInterface::instance()->snapshot();
708
    snapshot.insert(semanticDoc);
709

710
    d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot);
711 712
}

713
void CppEditorWidget::onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink> link)
714 715
{
    abortDeclDefLink();
716 717 718
    d->m_declDefLink = link;
    Core::IDocument *targetDocument
            = Core::DocumentModel::documentForFilePath( d->m_declDefLink->targetFile->fileName());
719
    if (textDocument() != targetDocument) {
720 721
        if (auto textDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
            connect(textDocument, SIGNAL(contentsChanged()),
722
                    this, SLOT(abortDeclDefLink()));
723
    }
724

725 726
}

727
void CppEditorWidget::onFilePathChanged()
728
{
729
    QTC_ASSERT(d->m_modelManager, return);
730
    QByteArray additionalDirectives;
731
    const QString &filePath = textDocument()->filePath();
732 733 734 735 736 737
    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();

738 739
        BaseEditorDocumentParser *parser = BaseEditorDocumentParser::get(filePath);
        QTC_ASSERT(parser, return);
740 741
        parser->setProjectPart(d->m_modelManager->projectPartForProjectFile(projectFile));
        parser->setEditorDefines(additionalDirectives);
742
    }
743 744
    d->m_preprocessorButton->setProperty("highlightWidget", !additionalDirectives.trimmed().isEmpty());
    d->m_preprocessorButton->update();
745 746
}

747
void CppEditorWidget::applyDeclDefLinkChanges(bool jumpToMatch)
748
{
749
    if (!d->m_declDefLink)
750
        return;
751
    d->m_declDefLink->apply(this, jumpToMatch);
752
    abortDeclDefLink();
753 754 755
    updateFunctionDeclDefLink();
}

756
FollowSymbolUnderCursor *CppEditorWidget::followSymbolUnderCursorDelegate()
757
{
758
    return d->m_followSymbolUnderCursor.data();
759 760
}

761 762 763 764 765 766 767
CompletionAssistProvider *CppEditorWidget::completionAssistProvider() const
{
    auto document = qobject_cast<CppEditorDocument *>(textDocument());
    QTC_ASSERT(document, return 0);
    return document->completionAssistProvider();
}

768
void CppEditorWidget::abortDeclDefLink()
769
{
770
    if (!d->m_declDefLink)
771
        return;
772

773 774
    Core::IDocument *targetDocument
            = Core::DocumentModel::documentForFilePath(d->m_declDefLink->targetFile->fileName());
775
    if (textDocument() != targetDocument) {
776 777
        if (auto textDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
            disconnect(textDocument, SIGNAL(contentsChanged()),
778
                    this, SLOT(abortDeclDefLink()));
779 780
    }

781 782
    d->m_declDefLink->hideMarker(this);
    d->m_declDefLink.clear();
783 784
}

785
void CppEditorWidget::showPreProcessorWidget()
786
{
787
    const QString &fileName = textDocument()->filePath();
788