cppeditor.cpp 28.3 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
    m_context.add(Constants::C_CPPEDITOR);
96 97
    m_context.add(ProjectExplorer::Constants::LANG_CXX);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
98
    setDuplicateSupported(true);
99
    setCommentStyle(Utils::CommentDefinition::CppStyle);
100
    setCompletionAssistProvider([this] () -> TextEditor::CompletionAssistProvider * {
101
        if (CppEditorDocument *document = qobject_cast<CppEditorDocument *>(textDocument()))
102 103
            return document->completionAssistProvider();
        return 0;
104
    });
con's avatar
con committed
105 106
}

107 108
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

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

public:
    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

117
    CppEditorDocument *m_cppEditorDocument;
118 119
    CppEditorOutline *m_cppEditorOutline;

120 121
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

122
    QTimer m_updateFunctionDeclDefLinkTimer;
123

124
    CppLocalRenaming m_localRenaming;
125 126 127 128

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

129
    CppUseSelectionsUpdater m_useSelectionsUpdater;
130 131 132 133 134 135 136 137

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

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

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

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

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

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

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

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

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

183
    connect(textDocument(), SIGNAL(filePathChanged(QString,QString)),
184
            this, SLOT(onFilePathChanged()));
185

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

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

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

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

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

215 216 217 218 219
    // 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
220

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

//    updateSemanticInfo(semanticInfo());
//    updateFunctionDeclDefLink();
//    d->m_cppEditorOutline->update();
//    const ExtraSelectionKind selectionKind = CodeWarningsSelection;
//    setExtraSelections(selectionKind, extraSelections(selectionKind));
con's avatar
con committed
236 237
}

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

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

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

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

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

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

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

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

274
    BaseTextEditorWidget::selectAll();
275 276
}

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

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

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

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

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

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

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

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

336
void CppEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
337
{
338
    updateSemanticInfo(d->m_cppEditorDocument->recalculateSemanticInfo());
339

340
    d->m_useSelectionsUpdater.abortSchedule();
341

342 343 344 345 346 347 348 349 350
    // Trigger once the use selections updater is finished and thus has updated
    // the use selections for the local renaming
    QSharedPointer<QMetaObject::Connection> connection(new QMetaObject::Connection);
    *connection.data() = connect(&d->m_useSelectionsUpdater, &CppUseSelectionsUpdater::finished,
        [this, connection] () {
            QObject::disconnect(*connection);
            if (!d->m_localRenaming.start()) // Rename local symbol
                renameUsages(); // Rename non-local symbol or macro
        });
351

352
    d->m_useSelectionsUpdater.update();
353 354
}

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

363
void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
364
{
365
    if (!d->m_modelManager)
con's avatar
con committed
366 367
        return;

368
    if (!d->m_lastSemanticInfo.doc)
369
        return;
con's avatar
con committed
370

371 372 373 374
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

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

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

421 422 423
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
424
    }
425 426 427 428

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

431
CppEditorWidget::Link CppEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
432
                                                  bool inNextSplit)
con's avatar
con committed
433
{
434
    if (!d->m_modelManager)
435
        return Link();
436

437 438 439 440 441
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
442 443
}

444
unsigned CppEditorWidget::documentRevision() const
445 446 447 448
{
    return document()->revision();
}

449
bool CppEditorWidget::isSemanticInfoValidExceptLocalUses() const
450
{
451 452
    return d->m_lastSemanticInfo.doc && d->m_lastSemanticInfo.revision == documentRevision();
}
453

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

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

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

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

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

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

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

497
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
498

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

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

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

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

539 540
    appendStandardContextMenuActions(menu);

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

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

553 554 555 556
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

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

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

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

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

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

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

587 588
    unsigned line = symbol->line();
    unsigned column = symbol->column();
589

590 591
    if (column)
        --column;
592

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

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

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

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

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

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

621 622
    if (!d->m_localRenaming.isActive())
        d->m_useSelectionsUpdater.update();
623 624 625

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

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

652
QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const
653
{
654
    return d->m_declDefLink;
655 656
}

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

663
void CppEditorWidget::updateFunctionDeclDefLink()
664 665 666
{
    const int pos = textCursor().selectionStart();

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

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

686
    d->m_updateFunctionDeclDefLinkTimer.start();
687 688
}

689
void CppEditorWidget::updateFunctionDeclDefLinkNow()
690
{
hjk's avatar
hjk committed
691
    if (Core::EditorManager::currentEditor() != editor())
692
        return;
693

694 695
    const Snapshot semanticSnapshot = d->m_lastSemanticInfo.snapshot;
    const Document::Ptr semanticDoc = d->m_lastSemanticInfo.doc;
696

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

    if (!isSemanticInfoValidExceptLocalUses())
708 709 710
        return;

    Snapshot snapshot = CppModelManagerInterface::instance()->snapshot();
711
    snapshot.insert(semanticDoc);
712

713
    d->m_declDefLinkFinder->startFindLinkAt(textCursor(), semanticDoc, snapshot);
714 715
}

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

728 729
}

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

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

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

759
FollowSymbolUnderCursor *CppEditorWidget::followSymbolUnderCursorDelegate()
760
{
761
    return d->m_followSymbolUnderCursor.data();
762 763
}

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

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

777 778
    d->m_declDefLink->hideMarker(this);
    d->m_declDefLink.clear();
779 780
}

781
void CppEditorWidget::showPreProcessorWidget()