cppeditor.cpp 39 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "cppeditor.h"
31

32
#include "cppautocompleter.h"
33 34
#include "cppcanonicalsymbol.h"
#include "cppdocumentationcommenthelper.h"
con's avatar
con committed
35
#include "cppeditorconstants.h"
36
#include "cppeditoroutline.h"
37
#include "cppeditorplugin.h"
38
#include "cppfollowsymbolundercursor.h"
con's avatar
con committed
39
#include "cpphighlighter.h"
40
#include "cpplocalrenaming.h"
41
#include "cpppreprocessordialog.h"
Leandro Melo's avatar
Leandro Melo committed
42
#include "cppquickfixassistant.h"
Roberto Raggi's avatar
Roberto Raggi committed
43

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

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

#include <projectexplorer/session.h>

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

#include <utils/qtcassert.h>

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

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

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

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

con's avatar
con committed
95 96
namespace {

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

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

107 108 109
namespace CppEditor {
namespace Internal {

110
CPPEditor::CPPEditor()
con's avatar
con committed
111
{
112 113 114
    m_context.add(CppEditor::Constants::C_CPPEDITOR);
    m_context.add(ProjectExplorer::Constants::LANG_CXX);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
115
    setDuplicateSupported(true);
116
    setCommentStyle(Utils::CommentDefinition::CppStyle);
117 118 119
    setCompletionAssistProvider([this] () -> TextEditor::CompletionAssistProvider * {
        return CppModelManagerInterface::instance()->cppEditorSupport(this)->completionAssistProvider();
    });
con's avatar
con committed
120 121
}

122 123
Q_GLOBAL_STATIC(CppTools::SymbolFinder, symbolFinder)

124
class CppEditorWidgetPrivate
125 126
{
public:
127
    CppEditorWidgetPrivate(CppEditorWidget *q);
128 129 130 131 132

public:
    QPointer<CppTools::CppModelManagerInterface> m_modelManager;

    CPPEditorDocument *m_cppEditorDocument;
133 134
    CppEditorOutline *m_cppEditorOutline;

135 136
    CppDocumentationCommentHelper m_cppDocumentationCommentHelper;

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

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

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

    QScopedPointer<QFutureWatcher<TextEditor::HighlightingResult> > m_highlightWatcher;
    unsigned m_highlightRevision; // the editor revision that requested the highlight

    QScopedPointer<QFutureWatcher<QList<int> > > m_referencesWatcher;
    unsigned m_referencesRevision;
    int m_referencesCursorPosition;

    FunctionDeclDefLinkFinder *m_declDefLinkFinder;
    QSharedPointer<FunctionDeclDefLink> m_declDefLink;

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

160
CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q)
161
    : m_modelManager(CppModelManagerInterface::instance())
162
    , m_cppEditorDocument(qobject_cast<CPPEditorDocument *>(q->textDocument()))
163
    , m_cppEditorOutline(new CppEditorOutline(q))
164
    , m_cppDocumentationCommentHelper(q)
165
    , m_localRenaming(q)
166 167 168 169 170 171 172 173 174
    , m_highlightRevision(0)
    , m_referencesRevision(0)
    , m_referencesCursorPosition(0)
    , m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
    , m_followSymbolUnderCursor(new FollowSymbolUnderCursor(q))
    , m_preprocessorButton(0)
{
}

175
CppEditorWidget::CppEditorWidget(TextEditor::BaseTextDocumentPtr doc, CPPEditor *editor)
176
{
177 178
    editor->setEditorWidget(this);

179
    setTextDocument(doc);
180
    d.reset(new CppEditorWidgetPrivate(this));
181
    setAutoCompleter(new CppAutoCompleter);
182

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

con's avatar
con committed
185 186
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
187
    setCodeFoldingSupported(true);
188
    setRevisionsVisible(true);
dt's avatar
dt committed
189

190
    if (d->m_modelManager) {
191
        CppEditorSupport *editorSupport = d->m_modelManager->cppEditorSupport(editor);
192 193 194 195
        connect(editorSupport, SIGNAL(documentUpdated()),
                this, SLOT(onDocumentUpdated()));
        connect(editorSupport, SIGNAL(semanticInfoUpdated(CppTools::SemanticInfo)),
                this, SLOT(updateSemanticInfo(CppTools::SemanticInfo)));
Eike Ziller's avatar
Eike Ziller committed
196 197
        connect(editorSupport, SIGNAL(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)),
                this, SLOT(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)));
con's avatar
con committed
198
    }
199

200
    connect(d->m_declDefLinkFinder, SIGNAL(foundLink(QSharedPointer<FunctionDeclDefLink>)),
201
            this, SLOT(onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefLink>)));
202

203
    connect(textDocument(), SIGNAL(filePathChanged(QString,QString)),
204
            this, SLOT(onFilePathChanged()));
205 206 207 208 209

    connect(&d->m_localRenaming, SIGNAL(finished()),
            this, SLOT(onLocalRenamingFinished()));
    connect(&d->m_localRenaming, SIGNAL(processKeyPressNormally(QKeyEvent*)),
            this, SLOT(onLocalRenamingProcessKeyPressNormally(QKeyEvent*)));
con's avatar
con committed
210

211
    // Tool bar creation
212
    d->m_updateUsesTimer = newSingleShotTimer(this, UPDATE_USES_INTERVAL);
213 214
    connect(d->m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

215
    d->m_updateFunctionDeclDefLinkTimer = newSingleShotTimer(this, UPDATE_FUNCTION_DECL_DEF_LINK_INTERVAL);
216
    connect(d->m_updateFunctionDeclDefLinkTimer, SIGNAL(timeout()),
Nikolai Kosjar's avatar
Nikolai Kosjar committed
217
            this, SLOT(updateFunctionDeclDefLinkNow()));
218

219 220
    connect(this, SIGNAL(cursorPositionChanged()),
            d->m_cppEditorOutline, SLOT(updateIndex()));
con's avatar
con committed
221

222
    // set up slots to document changes
223 224
    connect(document(), SIGNAL(contentsChange(int,int,int)),
            this, SLOT(onContentsChanged(int,int,int)));
con's avatar
con committed
225

226 227 228
    // set up function declaration - definition link
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateFunctionDeclDefLink()));
    connect(this, SIGNAL(textChanged()), this, SLOT(updateFunctionDeclDefLink()));
Roberto Raggi's avatar
Roberto Raggi committed
229 230 231 232 233

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

234 235
    d->m_preprocessorButton = new QToolButton(this);
    d->m_preprocessorButton->setText(QLatin1String("#"));
236 237 238
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePreprocessorButtonTooltip()));
    updatePreprocessorButtonTooltip();
239
    connect(d->m_preprocessorButton, SIGNAL(clicked()), this, SLOT(showPreProcessorWidget()));
240 241
    insertExtraToolBarWidget(TextEditor::BaseTextEditorWidget::Left, d->m_preprocessorButton);
    insertExtraToolBarWidget(TextEditor::BaseTextEditorWidget::Left, d->m_cppEditorOutline->widget());
242
    setLanguageSettingsId(CppTools::Constants::CPP_SETTINGS_ID);
con's avatar
con committed
243 244
}

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
CppEditorWidget::~CppEditorWidget()
{
    if (d->m_modelManager)
        d->m_modelManager->deleteCppEditorSupport(editor());
}

CPPEditorDocument *CppEditorWidget::cppEditorDocument() const
{
    return d->m_cppEditorDocument;
}

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

TextEditor::BaseTextEditor *CppEditorWidget::createEditor()
{
263
    QTC_ASSERT("should not happen anymore" && false, return 0);
264 265
}

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

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

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

279
    BaseTextEditorWidget::cut();
mae's avatar
mae committed
280 281
}

282
void CppEditorWidget::selectAll()
283
{
284
    if (d->m_localRenaming.handleSelectAll())
mae's avatar
mae committed
285
        return;
286

287
    BaseTextEditorWidget::selectAll();
288 289
}

290 291
/// \brief Called by \c CppEditorSupport when the document corresponding to the
///        file in this editor is updated.
292
void CppEditorWidget::onDocumentUpdated()
con's avatar
con committed
293
{
294
    d->m_cppEditorOutline->update();
con's avatar
con committed
295 296
}

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::markSymbolsNow()
336
{
337 338 339 340 341
    QTC_ASSERT(d->m_referencesWatcher, return);
    if (!d->m_referencesWatcher->isCanceled()
            && d->m_referencesCursorPosition == position()
            && d->m_referencesRevision == editorRevision()) {
        const SemanticInfo info = d->m_lastSemanticInfo;
Erik Verbruggen's avatar
Erik Verbruggen committed
342
        TranslationUnit *unit = info.doc->translationUnit();
343
        const QList<int> result = d->m_referencesWatcher->result();
344

Erik Verbruggen's avatar
Erik Verbruggen committed
345
        QList<QTextEdit::ExtraSelection> selections;
346

Erik Verbruggen's avatar
Erik Verbruggen committed
347 348 349
        foreach (int index, result) {
            unsigned line, column;
            unit->getTokenPosition(index, &line, &column);
350

Erik Verbruggen's avatar
Erik Verbruggen committed
351 352
            if (column)
                --column;  // adjust the column position.
353

354
            const int len = unit->tokenAt(index).utf16chars();
355

Erik Verbruggen's avatar
Erik Verbruggen committed
356 357 358
            QTextCursor cursor(document()->findBlockByNumber(line - 1));
            cursor.setPosition(cursor.position() + column);
            cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor);
359

Erik Verbruggen's avatar
Erik Verbruggen committed
360
            QTextEdit::ExtraSelection sel;
361
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Erik Verbruggen's avatar
Erik Verbruggen committed
362 363 364
            sel.cursor = cursor;
            selections.append(sel);
        }
365

Erik Verbruggen's avatar
Erik Verbruggen committed
366
        setExtraSelections(CodeSemanticsSelection, selections);
Roberto Raggi's avatar
Roberto Raggi committed
367
    }
368
    d->m_referencesWatcher.reset();
Roberto Raggi's avatar
Roberto Raggi committed
369 370
}

Nikolai Kosjar's avatar
Nikolai Kosjar committed
371 372
static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr doc,
                                     Snapshot snapshot)
373 374
{
    TypeOfExpression typeOfExpression;
375 376
    snapshot.insert(doc);
    typeOfExpression.init(doc, snapshot);
377 378
    // make possible to instantiate templates
    typeOfExpression.setExpandTemplates(true);
379
    if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression))
Nikolai Kosjar's avatar
Nikolai Kosjar committed
380 381
        return CppModelManagerInterface::instance()->references(canonicalSymbol,
                                                                typeOfExpression.context());
382 383 384
    return QList<int>();
}

385
void CppEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &info)
386
{
387
    d->m_localRenaming.stop();
388

389
    if (!info.doc)
390
        return;
391
    const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES);
392
    if (const Macro *macro = CppTools::findCanonicalMacro(textCursor(), info.doc)) {
393 394 395 396 397
        QList<QTextEdit::ExtraSelection> selections;

        //Macro definition
        if (macro->fileName() == info.doc->fileName()) {
            QTextCursor cursor(document());
398
            cursor.setPosition(macro->utf16CharOffset());
Nikolai Kosjar's avatar
Nikolai Kosjar committed
399
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
400
                                macro->nameToQString().size());
401 402

            QTextEdit::ExtraSelection sel;
403
            sel.format = occurrencesFormat;
404 405 406 407 408
            sel.cursor = cursor;
            selections.append(sel);
        }

        //Other macro uses
409
        foreach (const Document::MacroUse &use, info.doc->macroUses()) {
410 411
            const Macro &useMacro = use.macro();
            if (useMacro.line() != macro->line()
412
                    || useMacro.utf16CharOffset() != macro->utf16CharOffset()
413 414
                    || useMacro.length() != macro->length()
                    || useMacro.fileName() != macro->fileName())
415 416 417
                continue;

            QTextCursor cursor(document());
418 419
            cursor.setPosition(use.utf16charsBegin());
            cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor);
420 421

            QTextEdit::ExtraSelection sel;
422
            sel.format = occurrencesFormat;
423 424 425
            sel.cursor = cursor;
            selections.append(sel);
        }
426

427 428
        setExtraSelections(CodeSemanticsSelection, selections);
    } else {
429
        CanonicalSymbol cs(info.doc, info.snapshot);
430
        QString expression;
431
        if (Scope *scope = cs.getScopeAndExpression(tc, &expression)) {
432 433 434 435 436 437 438 439 440
            if (d->m_referencesWatcher)
                d->m_referencesWatcher->cancel();
            d->m_referencesWatcher.reset(new QFutureWatcher<QList<int> >);
            connect(d->m_referencesWatcher.data(), SIGNAL(finished()), SLOT(markSymbolsNow()));

            d->m_referencesRevision = info.revision;
            d->m_referencesCursorPosition = position();
            d->m_referencesWatcher->setFuture(
                QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot));
441 442 443
        } else {
            const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);

444
            if (!selections.isEmpty())
445 446
                setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
        }
447 448 449
    }
}

450
void CppEditorWidget::renameSymbolUnderCursor()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
451
{
452
    if (!d->m_modelManager)
453 454
        return;

455 456
    CppEditorSupport *ces = d->m_modelManager->cppEditorSupport(editor());
    updateSemanticInfo(ces->recalculateSemanticInfo());
457

458 459
    if (!d->m_localRenaming.start()) // Rename local symbol
        renameUsages(); // Rename non-local symbol or macro
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
460 461
}

462
void CppEditorWidget::onContentsChanged(int position, int charsRemoved, int charsAdded)
463
{
464 465
    Q_UNUSED(position)
    Q_UNUSED(charsAdded)
466 467 468 469 470

    if (charsRemoved > 0)
        updateUses();
}

471
void CppEditorWidget::updatePreprocessorButtonTooltip()
472
{
473
    QTC_ASSERT(d->m_preprocessorButton, return);
474 475
    Core::Command *cmd = Core::ActionManager::command(Constants::OPEN_PREPROCESSOR_DIALOG);
    QTC_ASSERT(cmd, return);
476
    d->m_preprocessorButton->setToolTip(cmd->action()->toolTip());
477 478
}

479
QList<QTextEdit::ExtraSelection> CppEditorWidget::createSelectionsFromUses(
480
        const QList<SemanticInfo::Use> &uses)
Roberto Raggi's avatar
Roberto Raggi committed
481
{
482 483
    QList<QTextEdit::ExtraSelection> result;
    const bool isUnused = uses.size() == 1;
Roberto Raggi's avatar
Roberto Raggi committed
484

Roberto Raggi's avatar
Roberto Raggi committed
485
    foreach (const SemanticInfo::Use &use, uses) {
486 487
        if (use.isInvalid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
488

489
        QTextEdit::ExtraSelection sel;
Roberto Raggi's avatar
Roberto Raggi committed
490
        if (isUnused)
491
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES_UNUSED);
Roberto Raggi's avatar
Roberto Raggi committed
492
        else
493
            sel.format = textCharFormat(TextEditor::C_OCCURRENCES);
Roberto Raggi's avatar
Roberto Raggi committed
494

495 496
        const int position = document()->findBlockByNumber(use.line - 1).position() + use.column - 1;
        const int anchor = position + use.length;
Roberto Raggi's avatar
Roberto Raggi committed
497

498
        sel.cursor = QTextCursor(document());
Roberto Raggi's avatar
Roberto Raggi committed
499 500
        sel.cursor.setPosition(anchor);
        sel.cursor.setPosition(position, QTextCursor::KeepAnchor);
Roberto Raggi's avatar
Roberto Raggi committed
501

502
        result.append(sel);
Roberto Raggi's avatar
Roberto Raggi committed
503
    }
504 505

    return result;
Roberto Raggi's avatar
Roberto Raggi committed
506 507
}

508
void CppEditorWidget::updateUses()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
509
{
510
    // Block premature semantic info calculation when editor is created.
511 512
    if (d->m_modelManager && d->m_modelManager->cppEditorSupport(editor())->initialized())
        d->m_updateUsesTimer->start();
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
513 514
}

515
void CppEditorWidget::updateUsesNow()
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
516
{
517
    if (d->m_localRenaming.isActive())
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
518 519
        return;

Roberto Raggi's avatar
Roberto Raggi committed
520
    semanticRehighlight();
con's avatar
con committed
521 522
}

523
void CppEditorWidget::highlightSymbolUsages(int from, int to)
524
{
525
    if (editorRevision() != d->m_highlightRevision)
526 527
        return; // outdated

528
    else if (!d->m_highlightWatcher || d->m_highlightWatcher->isCanceled())
529 530
        return; // aborted

531
    TextEditor::SyntaxHighlighter *highlighter = textDocument()->syntaxHighlighter();
532
    QTC_ASSERT(highlighter, return);
533

534
    TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
535
                highlighter, d->m_highlightWatcher->future(), from, to, d->m_semanticHighlightFormatMap);
536 537
}

538
void CppEditorWidget::finishHighlightSymbolUsages()
539
{
540 541 542 543
    QTC_ASSERT(d->m_highlightWatcher, return);
    if (!d->m_highlightWatcher->isCanceled()
            && editorRevision() == d->m_highlightRevision
            && !d->m_lastSemanticInfo.doc.isNull()) {
544
        TextEditor::SyntaxHighlighter *highlighter = textDocument()->syntaxHighlighter();
Erik Verbruggen's avatar
Erik Verbruggen committed
545 546 547
        QTC_CHECK(highlighter);
        if (highlighter)
            TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(highlighter,
548
                d->m_highlightWatcher->future());
Erik Verbruggen's avatar
Erik Verbruggen committed
549
    }
550
    d->m_highlightWatcher.reset();
551 552
}

553
void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
con's avatar
con committed
554
{
555
    if (!d->m_modelManager)
con's avatar
con committed
556 557
        return;

558
    if (!d->m_lastSemanticInfo.doc)
559
        return;
con's avatar
con committed
560

561 562 563 564
    // Find function declaration or definition under cursor
    Function *functionDefinitionSymbol = 0;
    Symbol *functionDeclarationSymbol = 0;

565
    ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    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
584

585
    // Link to function definition/declaration
586
    CppEditorWidget::Link symbolLink;
587 588
    if (functionDeclarationSymbol) {
        symbolLink = linkToSymbol(symbolFinder()
589
            ->findMatchingDefinition(functionDeclarationSymbol, d->m_modelManager->snapshot()));
590
    } else if (functionDefinitionSymbol) {
591 592
        const Snapshot snapshot = d->m_modelManager->snapshot();
        LookupContext context(d->m_lastSemanticInfo.doc, snapshot);
593 594 595 596 597 598 599 600
        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()) {
601
                    if (funTy->match(functionDefinitionSymbol)) {
602 603 604 605
                        if (decl != functionDefinitionSymbol && binding == r.binding())
                            best.prepend(decl);
                        else
                            best.append(decl);
606 607
                    }
                }
608 609
            }
        }
610

611 612 613
        if (best.isEmpty())
            return;
        symbolLink = linkToSymbol(best.first());
con's avatar
con committed
614
    }
615 616 617 618

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

621
CppEditorWidget::Link CppEditorWidget::findLinkAt(const QTextCursor &cursor, bool resolveTarget,
622
                                                  bool inNextSplit)
con's avatar
con committed
623
{
624
    if (!d->m_modelManager)
625
        return Link();
626

627 628 629 630 631
    return d->m_followSymbolUnderCursor->findLink(cursor, resolveTarget,
                                                  d->m_modelManager->snapshot(),
                                                  d->m_lastSemanticInfo.doc,
                                                  symbolFinder(),
                                                  inNextSplit);
con's avatar
con committed
632 633
}

634
unsigned CppEditorWidget::editorRevision() const
635 636 637 638
{
    return document()->revision();
}

639
bool CppEditorWidget::isOutdated() const
640
{
641
    if (d->m_lastSemanticInfo.revision != editorRevision())
642 643 644 645 646
        return true;

    return false;
}

647
SemanticInfo CppEditorWidget::semanticInfo() const
Roberto Raggi's avatar
Roberto Raggi committed
648
{
649
    return d->m_lastSemanticInfo;
Roberto Raggi's avatar
Roberto Raggi committed
650 651
}

652
bool CppEditorWidget::event(QEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
653 654 655
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
656
        // handle escape manually if a rename is active
657
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && d->m_localRenaming.isActive()) {
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
658 659 660 661 662 663 664 665
            e->accept();
            return true;
        }
        break;
    default:
        break;
    }

666
    return BaseTextEditorWidget::event(e);
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
667 668
}

669
void CppEditorWidget::performQuickFix(int index)
670
{
671
    TextEditor::QuickFixOperation::Ptr op = d->m_quickFixes.at(index);
672
    op->perform();
673 674
}

675
void CppEditorWidget::contextMenuEvent(QContextMenuEvent *e)
con's avatar
con committed
676
{
Roberto Raggi's avatar
Roberto Raggi committed
677 678 679
    // ### enable
    // updateSemanticInfo(m_semanticHighlighter->semanticInfo(currentSource()));

680
    QPointer<QMenu> menu(new QMenu(this));
con's avatar
con committed
681

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

685
    QMenu *quickFixMenu = new QMenu(tr("&Refactor"), menu);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
686 687
    quickFixMenu->addAction(Core::ActionManager::command(
                                Constants::RENAME_SYMBOL_UNDER_CURSOR)->action());
688 689 690

    QSignalMapper mapper;
    connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int)));
691
    if (!isOutdated()) {
Leandro Melo's avatar
Leandro Melo committed
692 693 694 695
        TextEditor::IAssistInterface *interface =
            createAssistInterface(TextEditor::QuickFix, TextEditor::ExplicitlyInvoked);
        if (interface) {
            QScopedPointer<TextEditor::IAssistProcessor> processor(
696
                        CppEditorPlugin::instance()->quickFixProvider()->createProcessor());
Leandro Melo's avatar
Leandro Melo committed
697 698 699 700 701 702 703 704 705
            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>();
706
                    d->m_quickFixes.append(op);
Leandro Melo's avatar
Leandro Melo committed
707 708 709 710 711
                    QAction *action = quickFixMenu->addAction(op->description());
                    mapper.setMapping(action, index);
                    connect(action, SIGNAL(triggered()), &mapper, SLOT(map()));
                }
                delete model;
712 713 714 715
            }
        }
    }

716
    foreach (QAction *action, contextMenu->actions()) {
con's avatar
con committed
717
        menu->addAction(action);
718
        if (action->objectName() == QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT))
719 720
            menu->addMenu(quickFixMenu);
    }
con's avatar
con committed
721

722 723
    appendStandardContextMenuActions(menu);

con's avatar
con committed
724
    menu->exec(e->globalPos());
725 726
    if (!menu)
        return;
727
    d->m_quickFixes.clear();
con's avatar
con committed
728 729 730
    delete menu;
}

731
void CppEditorWidget::keyPressEvent(QKeyEvent *e)
Thorbjørn Lindeijer's avatar
Thorbjørn Lindeijer committed
732
{
733
    if (d->m_localRenaming.handleKeyPressEvent(e))
734 735
        return;

736 737 738 739
    if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
        return;

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

742
Core::IEditor *CPPEditor::duplicate()
con's avatar
con committed
743
{
744 745 746 747 748
    CPPEditor *editor = new CPPEditor;
    CppEditorWidget *widget = new CppEditorWidget(editorWidget()->textDocumentPtr(), editor);
    CppEditorPlugin::instance()->initializeEditor(widget);
    editor->configureCodeAssistant();
    return editor;
con's avatar
con committed
749 750
}

751
bool CPPEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
dt's avatar
dt committed
752
{
753 754
    if (!TextEditor::BaseTextEditor::open(errorString, fileName, realFileName))
        return false;
755
    textDocument()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
756
    return true;
dt's avatar
dt committed
757 758
}

759
void CppEditorWidget::applyFontSettings()
con's avatar
con committed
760
{
761
    const TextEditor::FontSettings &fs = textDocument()->fontSettings();
Erik Verbruggen's avatar
Erik Verbruggen committed
762

763
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::TypeUse] =
764
            fs.toTextCharFormat(TextEditor::C_TYPE);
765
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::LocalUse] =
766
            fs.toTextCharFormat(TextEditor::C_LOCAL);
767
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::FieldUse] =
768
            fs.toTextCharFormat(TextEditor::C_FIELD);
769
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::EnumerationUse] =
770
            fs.toTextCharFormat(TextEditor::C_ENUMERATION);
771
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::VirtualMethodUse] =
772
            fs.toTextCharFormat(TextEditor::C_VIRTUAL_METHOD);
773
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::LabelUse] =
774
            fs.toTextCharFormat(TextEditor::C_LABEL);
775
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::MacroUse] =
776
            fs.toTextCharFormat(TextEditor::C_PREPROCESSOR);
777
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::FunctionUse] =
778
            fs.toTextCharFormat(TextEditor::C_FUNCTION);
779
    d->m_semanticHighlightFormatMap[CppHighlightingSupport::PseudoKeywordUse] =
780
            fs<