cpptoolseditorsupport.cpp 10.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6 7 8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** 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.
24
**
25 26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
con's avatar
con committed
29 30 31 32 33

#include "cpptoolseditorsupport.h"
#include "cppmodelmanager.h"

#include <texteditor/itexteditor.h>
Roberto Raggi's avatar
Roberto Raggi committed
34
#include <texteditor/basetexteditor.h>
hjk's avatar
hjk committed
35

Roberto Raggi's avatar
Roberto Raggi committed
36 37 38 39 40
#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>

#include <QtCore/QTimer>
con's avatar
con committed
41 42

using namespace CppTools::Internal;
Roberto Raggi's avatar
Roberto Raggi committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
using namespace CPlusPlus;

namespace {

enum {
    DEFAULT_QUICKFIX_INTERVAL = 500
};

class QuickFixMark: public TextEditor::ITextMark
{
    QIcon _icon;

public:
    QuickFixMark(QObject *parent)
        : TextEditor::ITextMark(parent),
          _icon(QLatin1String(":/core/images/redo.png")) // ### FIXME
    { }

    virtual ~QuickFixMark()
    { }

    virtual QIcon icon() const
    { return _icon; }

    virtual void updateLineNumber(int)
    { }

    virtual void updateBlock(const QTextBlock &)
    { }

    virtual void removedFromEditor()
    { }

    virtual void documentClosing()
    { }
};

class ReplaceCast: public QuickFixOperation
{
    CastExpressionAST *_castExpression;

public:
    ReplaceCast(CastExpressionAST *node, Document::Ptr doc, const Snapshot &snapshot)
        : QuickFixOperation(doc, snapshot),
          _castExpression(node)
    { }

    virtual QString description() const
    { return QLatin1String("Rewrite old C-style cast"); }

    virtual void apply(QTextCursor tc)
    {
        setTextCursor(tc);

        tc.beginEditBlock();

        QTextCursor beginOfCast = cursor(_castExpression->lparen_token);
        QTextCursor endOfCast = cursor(_castExpression->rparen_token);
        QTextCursor beginOfExpr = moveAtStartOfToken(_castExpression->expression->firstToken());
        QTextCursor endOfExpr = moveAtEndOfToken(_castExpression->expression->lastToken() - 1);

        beginOfCast.insertText(QLatin1String("reinterpret_cast<"));
        endOfCast.insertText(QLatin1String(">"));

        beginOfExpr.insertText(QLatin1String("("));
        endOfExpr.insertText(QLatin1String(")"));

        tc.endEditBlock();
    }
};

class CheckDocument: protected ASTVisitor
{
    QTextCursor _textCursor;
    Document::Ptr _doc;
    Snapshot _snapshot;
    unsigned _line;
    unsigned _column;
    QList<QuickFixOperationPtr> _quickFixes;

public:
    CheckDocument(Document::Ptr doc, Snapshot snapshot)
        : ASTVisitor(doc->control()), _doc(doc), _snapshot(snapshot)
    { }

    QList<QuickFixOperationPtr> operator()(QTextCursor tc)
    {
        _quickFixes.clear();
        _textCursor = tc;
        _line = tc.blockNumber() + 1;
        _column = tc.columnNumber() + 1;
        accept(_doc->translationUnit()->ast());
        return _quickFixes;
    }

protected:
    using ASTVisitor::visit;

    bool checkPosition(AST *ast) const
    {
        unsigned startLine, startColumn;
        unsigned endLine, endColumn;

        getTokenStartPosition(ast->firstToken(), &startLine, &startColumn);
        getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn);

        if (_line < startLine || (_line == startLine && _column < startColumn))
            return false;
        else if (_line > endLine || (_line == endLine && _column >= endColumn))
            return false;

        return true;
    }

    /*
    virtual bool visit(ForStatementAST *ast)
    {
        if (! checkPosition(ast))
            return true;

        if (ast->initializer && ast->initializer->asDeclarationStatement() != 0) {
            if (checkPosition(ast->initializer)) {
                // move initializer
                _nodes.append(ast);
            }
        }

        return true;
    }
    */


    virtual bool visit(CastExpressionAST *ast)
    {
        if (! checkPosition(ast))
            return true;

        if (ast->type_id && ast->lparen_token && ast->rparen_token && ast->expression) {
            QuickFixOperationPtr op(new ReplaceCast(ast, _doc, _snapshot));
            _quickFixes.append(op);
        }

        return true;
    }
};

} // end of anonymous namespace

QuickFixOperation::QuickFixOperation(CPlusPlus::Document::Ptr doc, const CPlusPlus::Snapshot &snapshot)
    : _doc(doc), _snapshot(snapshot)
{ }

QuickFixOperation::~QuickFixOperation()
{ }

QTextCursor QuickFixOperation::textCursor() const
{ return _textCursor; }

void QuickFixOperation::setTextCursor(const QTextCursor &tc)
{ _textCursor = tc; }

const CPlusPlus::Token &QuickFixOperation::tokenAt(unsigned index) const
{ return _doc->translationUnit()->tokenAt(index); }

void QuickFixOperation::getTokenStartPosition(unsigned index, unsigned *line, unsigned *column) const
{ _doc->translationUnit()->getPosition(tokenAt(index).begin(), line, column); }

void QuickFixOperation::getTokenEndPosition(unsigned index, unsigned *line, unsigned *column) const
{ _doc->translationUnit()->getPosition(tokenAt(index).end(), line, column); }

QTextCursor QuickFixOperation::cursor(unsigned index) const
{
    const Token &tk = tokenAt(index);

    unsigned line, col;
    getTokenStartPosition(index, &line, &col);
    QTextCursor tc = _textCursor;
    tc.setPosition(tc.document()->findBlockByNumber(line - 1).position() + col - 1);
    tc.setPosition(tc.position() + tk.length, QTextCursor::KeepAnchor);
    return tc;
}

QTextCursor QuickFixOperation::moveAtStartOfToken(unsigned index) const
{
    unsigned line, col;
    getTokenStartPosition(index, &line, &col);
    QTextCursor tc = _textCursor;
    tc.setPosition(tc.document()->findBlockByNumber(line - 1).position() + col - 1);
    return tc;
}

QTextCursor QuickFixOperation::moveAtEndOfToken(unsigned index) const
{
    const Token &tk = tokenAt(index);

    unsigned line, col;
    getTokenStartPosition(index, &line, &col);
    QTextCursor tc = _textCursor;
    tc.setPosition(tc.document()->findBlockByNumber(line - 1).position() + col + tk.length - 1);
    return tc;
}
con's avatar
con committed
244 245 246 247 248 249 250 251 252 253

CppEditorSupport::CppEditorSupport(CppModelManager *modelManager)
    : QObject(modelManager),
      _modelManager(modelManager),
      _updateDocumentInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL)
{
    _updateDocumentTimer = new QTimer(this);
    _updateDocumentTimer->setSingleShot(true);
    _updateDocumentTimer->setInterval(_updateDocumentInterval);
    connect(_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));
Roberto Raggi's avatar
Roberto Raggi committed
254 255 256 257 258 259 260

    _quickFixMark = new QuickFixMark(this);

    _quickFixTimer = new QTimer(this);
    _quickFixTimer->setSingleShot(true);
    _quickFixTimer->setInterval(DEFAULT_QUICKFIX_INTERVAL);
    connect(_quickFixTimer, SIGNAL(timeout()), this, SLOT(checkDocumentNow()));
con's avatar
con committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
}

CppEditorSupport::~CppEditorSupport()
{ }

TextEditor::ITextEditor *CppEditorSupport::textEditor() const
{ return _textEditor; }

void CppEditorSupport::setTextEditor(TextEditor::ITextEditor *textEditor)
{
    _textEditor = textEditor;

    if (! _textEditor)
        return;

276
    connect(_textEditor, SIGNAL(contentsChanged()), this, SIGNAL(contentsChanged()));
Roberto Raggi's avatar
Roberto Raggi committed
277 278 279
    connect(qobject_cast<TextEditor::BaseTextEditor *>(_textEditor->widget()), SIGNAL(cursorPositionChanged()),
            this, SLOT(checkDocument()));

280
    connect(this, SIGNAL(contentsChanged()), this, SLOT(updateDocument()));
Roberto Raggi's avatar
Roberto Raggi committed
281

con's avatar
con committed
282 283 284
    updateDocument();
}

285
QByteArray CppEditorSupport::contents()
con's avatar
con committed
286 287
{
    if (! _textEditor)
288
        return QByteArray();
Roberto Raggi's avatar
Roberto Raggi committed
289
    else if (! _cachedContents.isEmpty())
290
        _cachedContents = _textEditor->contents().toUtf8();
con's avatar
con committed
291

Roberto Raggi's avatar
Roberto Raggi committed
292
    return _cachedContents;
con's avatar
con committed
293 294 295 296 297 298 299 300 301
}

int CppEditorSupport::updateDocumentInterval() const
{ return _updateDocumentInterval; }

void CppEditorSupport::setUpdateDocumentInterval(int updateDocumentInterval)
{ _updateDocumentInterval = updateDocumentInterval; }

void CppEditorSupport::updateDocument()
Roberto Raggi's avatar
Roberto Raggi committed
302 303 304 305 306 307 308 309 310 311
{
    if (TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor*>(_textEditor->widget())) {
        const QList<QTextEdit::ExtraSelection> selections =
                edit->extraSelections(TextEditor::BaseTextEditor::CodeWarningsSelection);

        _modelManager->stopEditorSelectionsUpdate();
    }

    _updateDocumentTimer->start(_updateDocumentInterval);
}
con's avatar
con committed
312 313 314 315 316 317 318

void CppEditorSupport::updateDocumentNow()
{
    if (_documentParser.isRunning()) {
        _updateDocumentTimer->start(_updateDocumentInterval);
    } else {
        _updateDocumentTimer->stop();
Roberto Raggi's avatar
Roberto Raggi committed
319

con's avatar
con committed
320
        QStringList sourceFiles(_textEditor->file()->fileName());
321
        _cachedContents = _textEditor->contents().toUtf8();
con's avatar
con committed
322 323 324 325
        _documentParser = _modelManager->refreshSourceFiles(sourceFiles);
    }
}

Roberto Raggi's avatar
Roberto Raggi committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
void CppEditorSupport::checkDocument()
{
    _quickFixTimer->start(DEFAULT_QUICKFIX_INTERVAL);
}

void CppEditorSupport::checkDocumentNow()
{
    _textEditor->markableInterface()->removeMark(_quickFixMark);
    _quickFixes.clear();

    TextEditor::BaseTextEditor *ed =
            qobject_cast<TextEditor::BaseTextEditor *>(_textEditor->widget());

    Snapshot snapshot = _modelManager->snapshot();
    const QByteArray plainText = contents();
    const QString fileName = _textEditor->file()->fileName();
    const QByteArray preprocessedCode = snapshot.preprocessedCode(plainText, fileName);

    if (Document::Ptr doc = snapshot.documentFromSource(preprocessedCode, fileName)) {
        CheckDocument checkDocument(doc, snapshot);
        QList<QuickFixOperationPtr> quickFixes = checkDocument(ed->textCursor());
        if (! quickFixes.isEmpty()) {
            int line, col;
            ed->convertPosition(ed->position(), &line, &col);

            _textEditor->markableInterface()->addMark(_quickFixMark, line);
            _quickFixes = quickFixes;
        }
    }
}
356 357