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;
Roberto Raggi's avatar
Roberto Raggi committed
88 89
using namespace CppEditor::Internal;

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);
97
    setDuplicateSupported(true);
98
    setCompletionAssistProvider([this] () -> TextEditor::CompletionAssistProvider * {
99
        if (CppEditorDocument *document = qobject_cast<CppEditorDocument *>(textDocument()))
100 101
            return document->completionAssistProvider();
        return 0;
102
    });
con's avatar
con committed
103 104
}

105 106
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

107
class CppEditorWidgetPrivate
108 109
{
public:
110
    CppEditorWidgetPrivate(CppEditorWidget *q);
111 112 113 114

public:
    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

115
    CppEditorDocument *m_cppEditorDocument;
116 117
    CppEditorOutline *m_cppEditorOutline;

118 119
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

120
    QTimer m_updateFunctionDeclDefLinkTimer;
121

122
    CppLocalRenaming m_localRenaming;
123 124 125 126

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

127
    CppUseSelectionsUpdater m_useSelectionsUpdater;
128 129 130 131 132 133 134 135

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

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

136
CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q)
137
    : m_modelManager(CppModelManagerInterface::instance())
138
    , m_cppEditorDocument(qobject_cast<CppEditorDocument *>(q->textDocument()))
139
    , m_cppEditorOutline(new CppEditorOutline(q))
140
    , m_cppDocumentationCommentHelper(q)
141
    , m_localRenaming(q)
142
    , m_useSelectionsUpdater(q)
143 144 145 146 147 148
    , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
    , m_followSymbolUnderCursor(new FollowSymbolUnderCursor(q))
    , m_preprocessorButton(0)
{
}

149 150
CppEditorWidget::CppEditorWidget()
   : d(new CppEditorWidgetPrivate(this))
151
{
152
    qRegisterMetaType<SemanticInfo>("CppTools::SemanticInfo");
153
}
154

155 156 157
void CppEditorWidget::finalizeInitialization()
{
    d->m_cppEditorDocument = qobject_cast<CppEditorDocument *>(textDocument());
158

159
    setLanguageSettingsId(CppTools::Constants::CPP_SETTINGS_ID);
160
    setCodeFoldingSupported(true);
161 162
    setMarksVisible(true);
    setParenthesesMatchingEnabled(true);
163
    setRevisionsVisible(true);
dt's avatar
dt committed
164

165 166 167 168
    // function combo box sorting
    connect(CppEditorPlugin::instance(), &CppEditorPlugin::outlineSortingChanged,
            outline(), &CppEditorOutline::setSorted);

169
    connect(d->m_cppEditorDocument, &CppEditorDocument::codeWarningsUpdated,
170
            this, &CppEditorWidget::onCodeWarningsUpdated);
171
    connect(d->m_cppEditorDocument, &CppEditorDocument::ifdefedOutBlocksUpdated,
172 173 174 175 176
            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)));
177

178
    connect(d->m_declDefLinkFinder, SIGNAL(foundLink(QSharedPointer<FunctionDeclDefLink>)),
179
            this, SLOT(onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink>)));
180

181
    connect(textDocument(), SIGNAL(filePathChanged(QString,QString)),
182
            this, SLOT(onFilePathChanged()));
183

184 185 186 187
    connect(&d->m_useSelectionsUpdater,
            SIGNAL(selectionsForVariableUnderCursorUpdated(QList<QTextEdit::ExtraSelection>)),
            &d->m_localRenaming,
            SLOT(updateSelectionsForVariableUnderCursor(QList<QTextEdit::ExtraSelection>)));
188

189 190 191 192 193 194
    connect(&d->m_useSelectionsUpdater, &CppUseSelectionsUpdater::finished,
            [this] (CppTools::SemanticInfo::LocalUseMap localUses) {
                QTC_CHECK(isSemanticInfoValidExceptLocalUses());
                d->m_lastSemanticInfo.localUsesUpdated = true;
                d->m_lastSemanticInfo.localUses = localUses;
    });
195

196 197 198 199 200
    connect(&d->m_localRenaming, &CppLocalRenaming::finished, [this] {
        cppEditorDocument()->semanticRehighlight();
    });
    connect(&d->m_localRenaming, &CppLocalRenaming::processKeyPressNormally,
            this, &CppEditorWidget::processKeyNormally);
201

202 203
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
204

205
    // set up function declaration - definition link
206 207 208 209
    d->m_updateFunctionDeclDefLinkTimer.setSingleShot(true);
    d->m_updateFunctionDeclDefLinkTimer.setInterval(UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL);
    connect(&d->m_updateFunctionDeclDefLinkTimer, SIGNAL(timeout()),
            this, SLOT(updateFunctionDeclDefLinkNow()));
210 211
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateFunctionDeclDefLink()));
    connect(this, SIGNAL(textChanged()), this, SLOT(updateFunctionDeclDefLink()));
Roberto Raggi's avatar
Roberto Raggi committed
212

213 214 215 216 217
    // 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
218

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

230 231 232 233 234 235 236 237 238 239 240
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
241 242
}

243 244
CppEditorWidget::~CppEditorWidget()
{
245 246 247
    // non-inline destructor, see section "Forward Declared Pointers" of QScopedPointer.
}

248
CppEditorDocument *CppEditorWidget::cppEditorDocument() const
249 250 251 252 253 254 255 256 257
{
    return d->m_cppEditorDocument;
}

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

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

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

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

271
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
272 273
}

274
void CppEditorWidget::selectAll()
275
{
276
    if (d->m_localRenaming.handleSelectAll())
mae's avatar
mae committed
277
        return;
278

279
    BaseTextEditorWidget::selectAll();
280 281
}

282
void CppEditorWidget::onCppDocumentUpdated()
con's avatar
con committed
283
{
284
    d->m_cppEditorOutline->update();
con's avatar
con committed
285 286
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
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);
}

303
void CppEditorWidget::findUsages()
304
{
305
    if (!d->m_modelManager)
306 307
        return;

308
    SemanticInfo info = d->m_lastSemanticInfo;
309
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
310
    info.snapshot.insert(info.doc);
311

312
    if (const Macro *macro = CppTools::findCanonicalMacro(textCursor(), info.doc)) {
313
        d->m_modelManager->findMacroUsages(*macro);
314
    } else {
315
        CanonicalSymbol cs(info.doc, info.snapshot);
316 317
        Symbol *canonicalSymbol = cs(textCursor());
        if (canonicalSymbol)
318
            d->m_modelManager->findUsages(canonicalSymbol, cs.context());
319
    }
320 321
}

322
void CppEditorWidget::renameUsages(const QString &replacement)
323
{
324
    if (!d->m_modelManager)
325 326
        return;

327
    SemanticInfo info = d->m_lastSemanticInfo;
328
    info.snapshot = CppModelManagerInterface::instance()->snapshot();
329 330
    info.snapshot.insert(info.doc);

331
    if (const Macro *macro = CppTools::findCanonicalMacro(textCursor(), info.doc)) {
332
        d->m_modelManager->renameMacroUsages(*macro, replacement);
333
    } else {
334
        CanonicalSymbol cs(info.doc, info.snapshot);
335 336
        if (Symbol *canonicalSymbol = cs(textCursor()))
            if (canonicalSymbol->identifier() != 0)
337
                d->m_modelManager->renameUsages(canonicalSymbol, cs.context(), replacement);
338
    }
339 340
}

341
void CppEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
342
{
343
    d->m_useSelectionsUpdater.abortSchedule();
344 345
    updateSemanticInfo(d->m_cppEditorDocument->recalculateSemanticInfo(),
                       /*updateUseSelectionSynchronously=*/ true);
346

347 348
    if (!d->m_localRenaming.start()) // Rename local symbol
        renameUsages(); // Rename non-local symbol or macro
349 350
}

351
void CppEditorWidget::updatePreprocessorButtonTooltip()
352
{
353
    QTC_ASSERT(d->m_preprocessorButton, return);
354 355
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    QTC_ASSERT(cmd, return);
356
    d->m_preprocessorButton->setToolTip(cmd->action()->toolTip());
357 358
}

359
void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
360
{
361
    if (!d->m_modelManager)
con's avatar
con committed
362 363
        return;

364
    if (!d->m_lastSemanticInfo.doc)
365
        return;
con's avatar
con committed
366

367 368 369 370
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

371
    ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    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
390

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

417 418 419
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
420
    }
421 422 423 424

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

427
CppEditorWidget::Link CppEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
428
                                                  bool inNextSplit)
con's avatar
con committed
429
{
430
    if (!d->m_modelManager)
431
        return Link();
432

433 434 435 436 437
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
438 439
}

440
unsigned CppEditorWidget::documentRevision() const
441 442 443 444
{
    return document()->revision();
}

445
bool CppEditorWidget::isSemanticInfoValidExceptLocalUses() const
446
{
447 448 449
    return d->m_lastSemanticInfo.doc
            && d->m_lastSemanticInfo.revision == documentRevision()
            && !d->m_lastSemanticInfo.snapshot.isEmpty();
450
}
451

452 453 454
bool CppEditorWidget::isSemanticInfoValid() const
{
    return isSemanticInfoValidExceptLocalUses() && d->m_lastSemanticInfo.localUsesUpdated;
455 456
}

457
SemanticInfo CppEditorWidget::semanticInfo() const
Roberto Raggi's avatar
Roberto Raggi committed
458
{
459
    return d->m_lastSemanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
460 461
}

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

476
    return BaseTextEditorWidget::event(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
477 478
}

479
void CppEditorWidget::performQuickFix(int index)
480
{
481
    TextEditor::QuickFixOperation::Ptr op = d->m_quickFixes.at(index);
482
    op->perform();
483 484
}

485 486 487 488 489
void CppEditorWidget::processKeyNormally(QKeyEvent *e)
{
    BaseTextEditorWidget::keyPressEvent(e);
}

490
void CppEditorWidget::contextMenuEvent(QContextMenuEvent *e)
con's avatar
con committed
491
{
Roberto Raggi's avatar
Roberto Raggi committed
492 493 494
    // ### enable
    // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource()));

495
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
496

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

500
    QMenu *quickFixMenu = new QMenu(tr("&Refactor"), menu);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
501 502
    quickFixMenu->addAction(Core::ActionManager::command(
                                Constants::RENAME_SYMBOL_UNDER_CURSOR)->action());
503 504 505

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

531
    foreach (QAction *action, contextMenu->actions()) {
con's avatar
con committed
532
        menu->addAction(action);
533
        if (action->objectName() == QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT))
534 535
            menu->addMenu(quickFixMenu);
    }
con's avatar
con committed
536

537 538
    appendStandardContextMenuActions(menu);

con's avatar
con committed
539
    menu->exec(e->globalPos());
540 541
    if (!menu)
        return;
542
    d->m_quickFixes.clear();
con's avatar
con committed
543 544 545
    delete menu;
}

546
void CppEditorWidget::keyPressEvent(QKeyEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
547
{
548
    if (d->m_localRenaming.handleKeyPressEvent(e))
549 550
        return;

551 552 553 554
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

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

557
bool CppEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
dt's avatar
dt committed
558
{
559 560
    if (!TextEditor::BaseTextEditor::open(errorString, fileName, realFileName))
        return false;
561
    textDocument()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
562
    return true;
dt's avatar
dt committed
563 564
}

565
void CppEditorWidget::applyFontSettings()
con's avatar
con committed
566
{
567
    // This also makes the document apply font settings
568
    TextEditor::BaseTextEditorWidget::applyFontSettings();
con's avatar
con committed
569 570
}

571
void CppEditorWidget::slotCodeStyleSettingsChanged(const QVariant &)
572 573 574 575 576
{
    CppTools::QtStyleCodeFormatter formatter;
    formatter.invalidateCache(document());
}

577
CppEditorWidget::Link CppEditorWidget::linkToSymbol(CPlusPlus::Symbol *symbol)
578
{
579 580 581
    if (!symbol)
        return Link();

David Schulz's avatar
David Schulz committed
582
    const QString filename = QString::fromUtf8(symbol->fileName(),
583
                                               symbol->fileNameLength());
David Schulz's avatar
David Schulz committed
584

585 586
    unsigned line = symbol->line();
    unsigned column = symbol->column();
587

588 589
    if (column)
        --column;
590

591
    if (symbol->isGenerated())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
592
        column = 0;
593

David Schulz's avatar
David Schulz committed
594
    return Link(filename, line, column);
595 596
}

597
bool CppEditorWidget::openCppEditorAt(const Link &link, bool inNextSplit)
598
{
599
    if (!link.hasValidTarget())
600 601
        return false;

Eike Ziller's avatar
Eike Ziller committed
602
    Core::EditorManager::OpenEditorFlags flags;
603 604
    if (inNextSplit)
        flags |= Core::EditorManager::OpenInOtherSplit;
605 606 607
    return Core::EditorManager::openEditorAt(link.targetFileName,
                                             link.targetLine,
                                             link.targetColumn,
608 609
                                             Constants::CPPEDITOR_ID,
                                             flags);
con's avatar
con committed
610
}
Roberto Raggi's avatar
Roberto Raggi committed
611

612 613
void CppEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo,
                                         bool updateUseSelectionSynchronously)
Roberto Raggi's avatar
Roberto Raggi committed
614
{
615
    if (semanticInfo.revision != documentRevision())
Roberto Raggi's avatar
Roberto Raggi committed
616
        return;
Roberto Raggi's avatar
Roberto Raggi committed
617

618
    d->m_lastSemanticInfo = semanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
619

620 621 622 623 624 625
    if (!d->m_localRenaming.isActive()) {
        const CppUseSelectionsUpdater::CallType type = updateUseSelectionSynchronously
                ? CppUseSelectionsUpdater::Synchronous
                : CppUseSelectionsUpdater::Asynchronous;
        d->m_useSelectionsUpdater.update(type);
    }
626 627 628

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

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

655
QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const
656
{
657
    return d->m_declDefLink;
658 659
}

660
void CppEditorWidget::onRefactorMarkerClicked(const TextEditor::RefactorMarker &marker)
661 662 663 664 665
{
    if (marker.data.canConvert<FunctionDeclDefLink::Marker>())
        applyDeclDefLinkChanges(true);
}

666
void CppEditorWidget::updateFunctionDeclDefLink()
667 668 669
{
    const int pos = textCursor().selectionStart();

670
    // if there's already a link, abort it if the cursor is outside or the name changed
671
    // (adding a prefix is an exception since the user might type a return type)
672 673 674 675 676
    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))) {
677 678 679 680 681
        abortDeclDefLink();
        return;
    }

    // don't start a new scan if there's one active and the cursor is already in the scanned area
682
    const QTextCursor scannedSelection = d->m_declDefLinkFinder->scannedSelection();
683 684 685 686 687 688
    if (!scannedSelection.isNull()
            && scannedSelection.selectionStart() <= pos
            && scannedSelection.selectionEnd() >= pos) {
        return;
    }

689
    d->m_updateFunctionDeclDefLinkTimer.start();
690 691
}

692
void CppEditorWidget::updateFunctionDeclDefLinkNow()
693
{
694
    if (Core::EditorManager::currentEditor()->widget() != this)
695
        return;
696

697 698
    const Snapshot semanticSnapshot = d->m_lastSemanticInfo.snapshot;
    const Document::Ptr semanticDoc = d->m_lastSemanticInfo.doc;
699

700
    if (d->m_declDefLink) {
701
        // update the change marker
702
        const Utils::ChangeSet changes = d->m_declDefLink->changes(semanticSnapshot);
703
        if (changes.isEmpty())
704
            d->m_declDefLink->hideMarker(this);
705
        else
706
            d->m_declDefLink->showMarker(this);
707 708
        return;
    }
709 710

    if (!isSemanticInfoValidExceptLocalUses())
711 712 713
        return;

    Snapshot snapshot = CppModelManagerInterface::instance()->snapshot();
714
    snapshot.insert(semanticDoc);
715

716
    d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot);
717 718
}

719
void CppEditorWidget::onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink> link)
720 721
{
    abortDeclDefLink();
722 723 724
    d->m_declDefLink = link;
    Core::IDocument *targetDocument
            = Core::DocumentModel::documentForFilePath( d->m_declDefLink->targetFile->fileName());
725
    if (textDocument() != targetDocument) {
726 727
        if (auto textDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
            connect(textDocument, SIGNAL(contentsChanged()),
728
                    this, SLOT(abortDeclDefLink()));
729
    }
730

731 732
}

733
void CppEditorWidget::onFilePathChanged()
734
{
735
    QTC_ASSERT(d->m_modelManager, return);
736
    QByteArray additionalDirectives;
737
    const QString &filePath = textDocument()->filePath();
738 739 740 741 742 743
    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();

744 745
        BaseEditorDocumentParser *parser = BaseEditorDocumentParser::get(filePath);
        QTC_ASSERT(parser, return);
746 747
        parser->setProjectPart(d->m_modelManager->projectPartForProjectFile(projectFile));
        parser->setEditorDefines(additionalDirectives);
748
    }
749 750
    d->m_preprocessorButton->setProperty("highlightWidget", !additionalDirectives.trimmed().isEmpty());
    d->m_preprocessorButton->update();
751 752
}

753
void CppEditorWidget::applyDeclDefLinkChanges(bool jumpToMatch)
754
{
755
    if (!d->m_declDefLink)
756
        return;
757
    d->m_declDefLink->apply(this, jumpToMatch);
758
    abortDeclDefLink();
759 760 761
    updateFunctionDeclDefLink();
}

762
FollowSymbolUnderCursor *CppEditorWidget::followSymbolUnderCursorDelegate()
763
{
764
    return d->m_followSymbolUnderCursor.data();
765 766
}

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

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

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

784
void CppEditorWidget::showPreProcessorWidget()
785
{