qmljseditor.cpp 35.5 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
**
** Commercial Usage
**
** 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.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
27
28
29
**
**************************************************************************/

30
31
#include "qmljseditor.h"
#include "qmljseditorconstants.h"
32
#include "qmljshighlighter.h"
33
#include "qmljseditorplugin.h"
Roberto Raggi's avatar
Roberto Raggi committed
34
#include "qmljsmodelmanager.h"
35

36
#include <qmljs/qmljsindenter.h>
37
38
#include <qmljs/qmljsinterpreter.h>
#include <qmljs/qmljsbind.h>
Christian Kamm's avatar
Christian Kamm committed
39
#include <qmljs/qmljscheck.h>
40
#include <qmljs/qmljsevaluate.h>
41
#include <qmljs/qmljsdocument.h>
42
43
44
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>
45

46
#include <coreplugin/actionmanager/actionmanager.h>
47
48
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
mae's avatar
mae committed
49
#include <coreplugin/uniqueidmanager.h>
50
#include <extensionsystem/pluginmanager.h>
51
52
53
54
55
56
#include <texteditor/basetextdocument.h>
#include <texteditor/fontsettings.h>
#include <texteditor/textblockiterator.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>

57
#include <utils/changeset.h>
58
59
#include <utils/uncommentselection.h>

60
#include <QtCore/QFileInfo>
61
62
63
64
#include <QtCore/QTimer>

#include <QtGui/QMenu>
#include <QtGui/QComboBox>
Roberto Raggi's avatar
Roberto Raggi committed
65
#include <QtGui/QInputDialog>
66
#include <QtGui/QMainWindow>
con's avatar
con committed
67
#include <QtGui/QToolBar>
68
69

enum {
70
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 50,
71
    UPDATE_USES_DEFAULT_INTERVAL = 150
72
73
};

74
75
using namespace QmlJS;
using namespace QmlJS::AST;
76
using namespace QmlJSEditor::Internal;
77

78
namespace {
79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
int blockBraceDepth(const QTextBlock &block)
{
    int state = block.userState();
    if (state == -1)
        return 0;

    return (state >> 8) & 0xFF;
}

int blockStartState(const QTextBlock &block)
{
    int state = block.userState();

    if (state == -1)
        return 0;
    else
        return state & 0xff;
}
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

bool shouldInsertMatchingText(const QChar &lookAhead)
{
    switch (lookAhead.unicode()) {
    case '{': case '}':
    case ']': case ')':
    case ';': case ',':
    case '"': case '\'':
        return true;

    default:
        if (lookAhead.isSpace())
            return true;

        return false;
    } // switch
}

bool shouldInsertMatchingText(const QTextCursor &tc)
{
    QTextDocument *doc = tc.document();
    return shouldInsertMatchingText(doc->characterAt(tc.selectionEnd()));
}

Roberto Raggi's avatar
Roberto Raggi committed
122
class FindIdDeclarations: protected Visitor
123
124
{
public:
125
    typedef QHash<QString, QList<AST::SourceLocation> > Result;
126

127
    Result operator()(Document::Ptr doc)
128
129
130
    {
        _ids.clear();
        _maybeIds.clear();
131
132
        if (doc && doc->qmlProgram())
            doc->qmlProgram()->accept(this);
133
134
        return _ids;
    }
135
136

protected:
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
    QString asString(AST::UiQualifiedId *id)
    {
        QString text;
        for (; id; id = id->next) {
            if (id->name)
                text += id->name->asString();
            else
                text += QLatin1Char('?');

            if (id->next)
                text += QLatin1Char('.');
        }

        return text;
    }

    void accept(AST::Node *node)
    { AST::Node::acceptChild(node, this); }

    using Visitor::visit;
    using Visitor::endVisit;

    virtual bool visit(AST::UiScriptBinding *node)
    {
        if (asString(node->qualifiedId) == QLatin1String("id")) {
            if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement*>(node->statement)) {
                if (AST::IdentifierExpression *idExpr = AST::cast<AST::IdentifierExpression *>(stmt->expression)) {
                    if (idExpr->name) {
                        const QString id = idExpr->name->asString();
                        QList<AST::SourceLocation> *locs = &_ids[id];
                        locs->append(idExpr->firstSourceLocation());
                        locs->append(_maybeIds.value(id));
                        _maybeIds.remove(id);
                        return false;
                    }
                }
            }
        }

        accept(node->statement);

        return false;
    }

    virtual bool visit(AST::IdentifierExpression *node)
    {
        if (node->name) {
            const QString name = node->name->asString();

            if (_ids.contains(name))
                _ids[name].append(node->identifierToken);
            else
                _maybeIds[name].append(node->identifierToken);
        }
        return false;
    }
193
194

private:
195
196
    Result _ids;
    Result _maybeIds;
197
198
};

199
200
class FindDeclarations: protected Visitor
{
201
202
    QList<Declaration> _declarations;
    int _depth;
203
204

public:
205
206
207
208
209
210
211
    QList<Declaration> operator()(AST::Node *node)
    {
        _depth = -1;
        _declarations.clear();
        accept(node);
        return _declarations;
    }
212
213

protected:
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    using Visitor::visit;
    using Visitor::endVisit;

    QString asString(AST::UiQualifiedId *id)
    {
        QString text;
        for (; id; id = id->next) {
            if (id->name)
                text += id->name->asString();
            else
                text += QLatin1Char('?');

            if (id->next)
                text += QLatin1Char('.');
        }
229

230
231
        return text;
    }
Roberto Raggi's avatar
Roberto Raggi committed
232

233
234
235
236
237
238
239
240
241
242
243
244
    void accept(AST::Node *node)
    { AST::Node::acceptChild(node, this); }

    void init(Declaration *decl, AST::UiObjectMember *member)
    {
        const SourceLocation first = member->firstSourceLocation();
        const SourceLocation last = member->lastSourceLocation();
        decl->startLine = first.startLine;
        decl->startColumn = first.startColumn;
        decl->endLine = last.startLine;
        decl->endColumn = last.startColumn + last.length;
    }
Roberto Raggi's avatar
Roberto Raggi committed
245

246
247
248
249
250
251
252
253
254
255
    void init(Declaration *decl, AST::ExpressionNode *expressionNode)
    {
        const SourceLocation first = expressionNode->firstSourceLocation();
        const SourceLocation last = expressionNode->lastSourceLocation();
        decl->startLine = first.startLine;
        decl->startColumn = first.startColumn;
        decl->endLine = last.startLine;
        decl->endColumn = last.startColumn + last.length;
    }

256
257
258
    virtual bool visit(AST::UiObjectDefinition *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
259

260
261
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
262

263
264
265
266
267
        decl.text.fill(QLatin1Char(' '), _depth);
        if (node->qualifiedTypeNameId)
            decl.text.append(asString(node->qualifiedTypeNameId));
        else
            decl.text.append(QLatin1Char('?'));
Roberto Raggi's avatar
Roberto Raggi committed
268

269
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
270

271
272
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
273

274
275
276
277
    virtual void endVisit(AST::UiObjectDefinition *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
278

279
280
281
    virtual bool visit(AST::UiObjectBinding *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
282

283
284
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
285

286
        decl.text.fill(QLatin1Char(' '), _depth);
Roberto Raggi's avatar
Roberto Raggi committed
287

288
289
        decl.text.append(asString(node->qualifiedId));
        decl.text.append(QLatin1String(": "));
Roberto Raggi's avatar
Roberto Raggi committed
290

291
292
293
294
        if (node->qualifiedTypeNameId)
            decl.text.append(asString(node->qualifiedTypeNameId));
        else
            decl.text.append(QLatin1Char('?'));
Roberto Raggi's avatar
Roberto Raggi committed
295

296
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
297

298
299
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
300

301
302
303
304
    virtual void endVisit(AST::UiObjectBinding *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
305

306
    virtual bool visit(AST::UiScriptBinding *)
307
308
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
309

310
#if 0 // ### ignore script bindings for now.
311
312
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
313

314
315
        decl.text.fill(QLatin1Char(' '), _depth);
        decl.text.append(asString(node->qualifiedId));
Roberto Raggi's avatar
Roberto Raggi committed
316

317
        _declarations.append(decl);
318
#endif
Roberto Raggi's avatar
Roberto Raggi committed
319

320
321
        return false; // more more bindings in this subtree.
    }
Roberto Raggi's avatar
Roberto Raggi committed
322

323
324
325
326
    virtual void endVisit(AST::UiScriptBinding *)
    {
        --_depth;
    }
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378

    virtual bool visit(AST::FunctionExpression *)
    {
        return false;
    }

    virtual bool visit(AST::FunctionDeclaration *ast)
    {
        if (! ast->name)
            return false;

        Declaration decl;
        init(&decl, ast);

        decl.text.fill(QLatin1Char(' '), _depth);
        decl.text += ast->name->asString();

        decl.text += QLatin1Char('(');
        for (FormalParameterList *it = ast->formals; it; it = it->next) {
            if (it->name)
                decl.text += it->name->asString();

            if (it->next)
                decl.text += QLatin1String(", ");
        }

        decl.text += QLatin1Char(')');

        _declarations.append(decl);

        return false;
    }

    virtual bool visit(AST::VariableDeclaration *ast)
    {
        if (! ast->name)
            return false;

        Declaration decl;
        decl.text.fill(QLatin1Char(' '), _depth);
        decl.text += ast->name->asString();

        const SourceLocation first = ast->identifierToken;
        decl.startLine = first.startLine;
        decl.startColumn = first.startColumn;
        decl.endLine = first.startLine;
        decl.endColumn = first.startColumn + first.length;

        _declarations.append(decl);

        return false;
    }
379
380
};

381
382
383
384
385
386
387
388
389
390
class CreateRanges: protected AST::Visitor
{
    QTextDocument *_textDocument;
    QList<Range> _ranges;

public:
    QList<Range> operator()(QTextDocument *textDocument, Document::Ptr doc)
    {
        _textDocument = textDocument;
        _ranges.clear();
391
392
        if (doc && doc->ast() != 0)
            doc->ast()->accept(this);
393
394
395
396
397
398
399
400
        return _ranges;
    }

protected:
    using AST::Visitor::visit;

    virtual bool visit(AST::UiObjectBinding *ast)
    {
401
402
        if (ast->initializer)
            _ranges.append(createRange(ast, ast->initializer));
403
404
405
406
407
        return true;
    }

    virtual bool visit(AST::UiObjectDefinition *ast)
    {
408
409
        if (ast->initializer)
            _ranges.append(createRange(ast, ast->initializer));
410
411
412
        return true;
    }

413
414
415
416
417
418
419
420
421
422
423
424
    virtual bool visit(AST::FunctionExpression *ast)
    {
        _ranges.append(createRange(ast));
        return true;
    }

    virtual bool visit(AST::FunctionDeclaration *ast)
    {
        _ranges.append(createRange(ast));
        return true;
    }

425
    Range createRange(AST::UiObjectMember *member, AST::UiObjectInitializer *ast)
426
427
428
    {
        Range range;

429
        range.ast = member;
430
431

        range.begin = QTextCursor(_textDocument);
432
        range.begin.setPosition(ast->lbraceToken.begin());
433
434

        range.end = QTextCursor(_textDocument);
435
        range.end.setPosition(ast->rbraceToken.end());
436
437
        return range;
    }
438
439
440
441
442
443
444
445
446
447
448
449

    Range createRange(AST::FunctionExpression *ast)
    {
        Range range;

        range.ast = ast;

        range.begin = QTextCursor(_textDocument);
        range.begin.setPosition(ast->lbraceToken.begin());

        range.end = QTextCursor(_textDocument);
        range.end.setPosition(ast->rbraceToken.end());
450

451
452
453
        return range;
    }

454
455
};

456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

class CollectASTNodes: protected AST::Visitor
{
public:
    QList<AST::UiQualifiedId *> qualifiedIds;
    QList<AST::IdentifierExpression *> identifiers;
    QList<AST::FieldMemberExpression *> fieldMembers;

    void accept(AST::Node *node)
    {
        if (node)
            node->accept(this);
    }

protected:
    using AST::Visitor::visit;

    virtual bool visit(AST::UiQualifiedId *ast)
    {
        qualifiedIds.append(ast);
        return false;
    }

    virtual bool visit(AST::IdentifierExpression *ast)
    {
        identifiers.append(ast);
        return false;
    }

    virtual bool visit(AST::FieldMemberExpression *ast)
    {
        fieldMembers.append(ast);
        return true;
    }
};

492
493
494
} // end of anonymous namespace


495
AST::Node *SemanticInfo::declaringMember(int cursorPosition) const
496
{
497
    AST::Node *declaringMember = 0;
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512

    for (int i = ranges.size() - 1; i != -1; --i) {
        const Range &range = ranges.at(i);

        if (range.begin.isNull() || range.end.isNull()) {
            continue;
        } else if (cursorPosition >= range.begin.position() && cursorPosition <= range.end.position()) {
            declaringMember = range.ast;
            break;
        }
    }

    return declaringMember;
}

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
QList<AST::Node *> SemanticInfo::astPath(int cursorPosition) const
{
    QList<AST::Node *> path;

    foreach (const Range &range, ranges) {
        if (range.begin.isNull() || range.end.isNull()) {
            continue;
        } else if (cursorPosition >= range.begin.position() && cursorPosition <= range.end.position()) {
            path += range.ast;
        }
    }

    return path;
}

528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
AST::Node *SemanticInfo::nodeUnderCursor(int pos) const
{
    if (! document)
        return 0;

    const unsigned cursorPosition = pos;

    CollectASTNodes nodes;
    nodes.accept(document->ast());

    foreach (AST::UiQualifiedId *q, nodes.qualifiedIds) {
        if (cursorPosition >= q->identifierToken.begin()) {
            for (AST::UiQualifiedId *tail = q; tail; tail = tail->next) {
                if (! tail->next && cursorPosition <= tail->identifierToken.end())
                    return q;
            }
        }
    }

    foreach (AST::IdentifierExpression *id, nodes.identifiers) {
        if (cursorPosition >= id->identifierToken.begin() && cursorPosition <= id->identifierToken.end())
            return id;
    }

    foreach (AST::FieldMemberExpression *mem, nodes.fieldMembers) {
        if (mem->name && cursorPosition >= mem->identifierToken.begin() && cursorPosition <= mem->identifierToken.end())
            return mem;
    }

    return 0;
}

560
561
562
563
564
565
566
567
int SemanticInfo::revision() const
{
    if (document)
        return document->documentRevision();

    return 0;
}

568
QmlJSEditorEditable::QmlJSEditorEditable(QmlJSTextEditor *editor)
mae's avatar
mae committed
569
    : BaseTextEditorEditable(editor)
570
{
mae's avatar
mae committed
571
572

    Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance();
573
    m_context << uidm->uniqueIdentifier(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
mae's avatar
mae committed
574
    m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
575
576
}

577
QmlJSTextEditor::QmlJSTextEditor(QWidget *parent) :
578
    TextEditor::BaseTextEditor(parent),
579
    m_methodCombo(0),
Roberto Raggi's avatar
Roberto Raggi committed
580
    m_modelManager(0)
581
{
582
    qRegisterMetaType<QmlJSEditor::Internal::SemanticInfo>("QmlJSEditor::Internal::SemanticInfo");
Christian Kamm's avatar
Christian Kamm committed
583
584
585
586

    m_semanticHighlighter = new SemanticHighlighter(this);
    m_semanticHighlighter->start();

587
588
589
590
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);
    setCodeFoldingVisible(true);
591

592
593
594
595
    m_updateDocumentTimer = new QTimer(this);
    m_updateDocumentTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer->setSingleShot(true);
    connect(m_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));
596

597
598
599
600
601
    m_updateUsesTimer = new QTimer(this);
    m_updateUsesTimer->setInterval(UPDATE_USES_DEFAULT_INTERVAL);
    m_updateUsesTimer->setSingleShot(true);
    connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

602
    connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));
603
    connect(this, SIGNAL(textChanged()), this, SLOT(updateUses()));
604

605
    baseTextDocument()->setSyntaxHighlighter(new Highlighter(document()));
606

Roberto Raggi's avatar
Roberto Raggi committed
607
    m_modelManager = ExtensionSystem::PluginManager::instance()->getObject<ModelManagerInterface>();
608
609

    if (m_modelManager) {
610
611
        connect(m_modelManager, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
                this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
612
    }
Christian Kamm's avatar
Christian Kamm committed
613

614
615
    connect(m_semanticHighlighter, SIGNAL(changed(QmlJSEditor::Internal::SemanticInfo)),
            this, SLOT(updateSemanticInfo(QmlJSEditor::Internal::SemanticInfo)));
616
617
}

618
QmlJSTextEditor::~QmlJSTextEditor()
619
{
Christian Kamm's avatar
Christian Kamm committed
620
621
    m_semanticHighlighter->abort();
    m_semanticHighlighter->wait();
622
623
}

624
625
626
627
628
629
630
631
632
633
SemanticInfo QmlJSTextEditor::semanticInfo() const
{
    return m_semanticInfo;
}

int QmlJSTextEditor::documentRevision() const
{
    return document()->revision();
}

634
Core::IEditor *QmlJSEditorEditable::duplicate(QWidget *parent)
635
{
636
    QmlJSTextEditor *newEditor = new QmlJSTextEditor(parent);
637
    newEditor->duplicateFrom(editor());
638
    QmlJSEditorPlugin::instance()->initializeEditor(newEditor);
639
    return newEditor->editableInterface();
640
641
}

642
QString QmlJSEditorEditable::id() const
643
{
644
    return QLatin1String(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
645
646
}

647
648
649
650
651
652
653
bool QmlJSEditorEditable::open(const QString &fileName)
{
    bool b = TextEditor::BaseTextEditorEditable::open(fileName);
    editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type());
    return b;
}

654
QmlJSTextEditor::Context QmlJSEditorEditable::context() const
655
{
656
    return m_context;
657
658
}

659
void QmlJSTextEditor::updateDocument()
660
{
661
    m_updateDocumentTimer->start(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
662
663
}

664
void QmlJSTextEditor::updateDocumentNow()
665
{
666
    // ### move in the parser thread.
667

668
    m_updateDocumentTimer->stop();
669

670
    const QString fileName = file()->fileName();
671

672
673
674
    m_modelManager->updateSourceFiles(QStringList() << fileName);
}

675
void QmlJSTextEditor::onDocumentUpdated(QmlJS::Document::Ptr doc)
676
{
677
    if (file()->fileName() != doc->fileName()) {
678
        return;
679
    }
680

681
682
683
684
    if (doc->documentRevision() != document()->revision()) {
        // got an outdated document.
        return;
    }
685

686
687
688
    if (doc->ast()) {
        // got a correctly parsed (or recovered) file.

Christian Kamm's avatar
Christian Kamm committed
689
690
        const SemanticHighlighter::Source source = currentSource(/*force = */ true);
        m_semanticHighlighter->rehighlight(source);
691
    }
692
693
}

694
void QmlJSTextEditor::jumpToMethod(int index)
695
{
696
697
    if (index > 0 && index <= m_semanticInfo.declarations.size()) { // indexes are 1-based
        Declaration d = m_semanticInfo.declarations.at(index - 1);
698
699
700
        gotoLine(d.startLine, d.startColumn - 1);
        setFocus();
    }
701
702
}

703
void QmlJSTextEditor::updateMethodBoxIndex()
704
{
705
706
    int line = 0, column = 0;
    convertPosition(position(), &line, &column);
707

708
    int currentSymbolIndex = 0;
709

710
    int index = 0;
711
712
    while (index < m_semanticInfo.declarations.size()) {
        const Declaration &d = m_semanticInfo.declarations.at(index++);
713

714
715
716
717
718
        if (line < d.startLine)
            break;
        else
            currentSymbolIndex = index;
    }
719

720
    m_methodCombo->setCurrentIndex(currentSymbolIndex);
721
722
723
    updateUses();
}

724
void QmlJSTextEditor::updateUses()
725
726
727
728
{
    m_updateUsesTimer->start();
}

729
void QmlJSTextEditor::updateUsesNow()
730
{
731
    if (document()->revision() != m_semanticInfo.revision()) {
732
733
734
735
736
        updateUses();
        return;
    }

    m_updateUsesTimer->stop();
737

738
    QList<QTextEdit::ExtraSelection> selections;
739
    foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(wordUnderCursor())) {
740
741
        if (! loc.isValid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
742

743
        QTextEdit::ExtraSelection sel;
744
        sel.format = m_occurrencesFormat;
745
746
747
748
749
        sel.cursor = textCursor();
        sel.cursor.setPosition(loc.begin());
        sel.cursor.setPosition(loc.end(), QTextCursor::KeepAnchor);
        selections.append(sel);
    }
750

751
    setExtraSelections(CodeSemanticsSelection, selections);
752
753
}

754
void QmlJSTextEditor::updateMethodBoxToolTip()
755
756
757
{
}

758
void QmlJSTextEditor::updateFileName()
759
760
761
{
}

762
void QmlJSTextEditor::renameIdUnderCursor()
Roberto Raggi's avatar
Roberto Raggi committed
763
{
764
765
766
767
768
769
770
771
    const QString id = wordUnderCursor();
    bool ok = false;
    const QString newId = QInputDialog::getText(Core::ICore::instance()->mainWindow(),
                                                tr("Rename..."),
                                                tr("New id:"),
                                                QLineEdit::Normal,
                                                id, &ok);
    if (ok) {
772
        Utils::ChangeSet changeSet;
773

774
        foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(id)) {
775
            changeSet.replace(loc.offset, loc.length, newId);
776
777
778
        }

        QTextCursor tc = textCursor();
779
        changeSet.apply(&tc);
780
    }
Roberto Raggi's avatar
Roberto Raggi committed
781
782
}

783
void QmlJSTextEditor::setFontSettings(const TextEditor::FontSettings &fs)
784
{
785
    TextEditor::BaseTextEditor::setFontSettings(fs);
786
    Highlighter *highlighter = qobject_cast<Highlighter*>(baseTextDocument()->syntaxHighlighter());
787
788
789
    if (!highlighter)
        return;

790
791
792
793
794
795
796
797
798
    /*
        NumberFormat,
        StringFormat,
        TypeFormat,
        KeywordFormat,
        LabelFormat,
        CommentFormat,
        VisualWhitespace,
     */
799
800
801
802
803
804
805
    static QVector<QString> categories;
    if (categories.isEmpty()) {
        categories << QLatin1String(TextEditor::Constants::C_NUMBER)
                << QLatin1String(TextEditor::Constants::C_STRING)
                << QLatin1String(TextEditor::Constants::C_TYPE)
                << QLatin1String(TextEditor::Constants::C_KEYWORD)
                << QLatin1String(TextEditor::Constants::C_LABEL)
mae's avatar
mae committed
806
807
                << QLatin1String(TextEditor::Constants::C_COMMENT)
                << QLatin1String(TextEditor::Constants::C_VISUAL_WHITESPACE);
808
809
    }

810
811
812
813
    const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories);
    highlighter->setFormats(formats.constBegin(), formats.constEnd());
    highlighter->rehighlight();

814
    m_occurrencesFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES));
815
816
817
818
819
820
821
822
    m_occurrencesUnusedFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_UNUSED));
    m_occurrencesUnusedFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
    m_occurrencesUnusedFormat.setUnderlineColor(m_occurrencesUnusedFormat.foreground().color());
    m_occurrencesUnusedFormat.clearForeground();
    m_occurrencesUnusedFormat.setToolTip(tr("Unused variable"));
    m_occurrenceRenameFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_RENAME));

    // only set the background, we do not want to modify foreground properties set by the syntax highlighter or the link
823
    m_occurrencesFormat.clearForeground();
824
    m_occurrenceRenameFormat.clearForeground();
825
826
}

827

828
QString QmlJSTextEditor::wordUnderCursor() const
Roberto Raggi's avatar
Roberto Raggi committed
829
{
830
831
832
833
834
    QTextCursor tc = textCursor();
    tc.movePosition(QTextCursor::StartOfWord);
    tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    const QString word= tc.selectedText();
    return word;
Roberto Raggi's avatar
Roberto Raggi committed
835
836
}

837
bool QmlJSTextEditor::isElectricCharacter(const QChar &ch) const
838
{
839
840
    if (ch == QLatin1Char('}')
        || ch == QLatin1Char(']'))
841
842
        return true;
    return false;
843
844
}

845
bool QmlJSTextEditor::isClosingBrace(const QList<Token> &tokens) const
846
{
847

Erik Verbruggen's avatar
Erik Verbruggen committed
848
    if (tokens.size() == 1) {
849
        const Token firstToken = tokens.first();
850

851
        return firstToken.is(Token::RightBrace) || firstToken.is(Token::RightBracket);
Erik Verbruggen's avatar
Erik Verbruggen committed
852
    }
853

Erik Verbruggen's avatar
Erik Verbruggen committed
854
855
    return false;
}
856

857
void QmlJSTextEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar)
Erik Verbruggen's avatar
Erik Verbruggen committed
858
859
{
    TextEditor::TabSettings ts = tabSettings();
860
    QmlJSIndenter indenter;
861
862
    indenter.setTabSize(ts.m_tabSize);
    indenter.setIndentSize(ts.m_indentSize);
Erik Verbruggen's avatar
Erik Verbruggen committed
863

864
    const int indent = indenter.indentForBottomLine(doc->begin(), block.next(), typedChar);
Erik Verbruggen's avatar
Erik Verbruggen committed
865
    ts.indentLine(block, indent);
866
867
}

868
TextEditor::BaseTextEditorEditable *QmlJSTextEditor::createEditableInterface()
869
{
870
    QmlJSEditorEditable *editable = new QmlJSEditorEditable(this);
871
872
    createToolBar(editable);
    return editable;
873
874
}

875
void QmlJSTextEditor::createToolBar(QmlJSEditorEditable *editable)
876
{
877
878
879
    m_methodCombo = new QComboBox;
    m_methodCombo->setMinimumContentsLength(22);
    //m_methodCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
880

881
882
883
884
    // Make the combo box prefer to expand
    QSizePolicy policy = m_methodCombo->sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_methodCombo->setSizePolicy(policy);
885

886
887
888
    connect(m_methodCombo, SIGNAL(activated(int)), this, SLOT(jumpToMethod(int)));
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateMethodBoxIndex()));
    connect(m_methodCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateMethodBoxToolTip()));
889

890
    connect(file(), SIGNAL(changed()), this, SLOT(updateFileName()));
891

892
    QToolBar *toolBar = static_cast<QToolBar*>(editable->toolBar());
893

894
895
    QList<QAction*> actions = toolBar->actions();
    toolBar->insertWidget(actions.first(), m_methodCombo);
896
897
}

898
TextEditor::BaseTextEditor::Link QmlJSTextEditor::findLinkAt(const QTextCursor &cursor, bool /*resolveTarget*/)
899
{
900
    const SemanticInfo semanticInfo = m_semanticInfo;
901
    const unsigned cursorPosition = cursor.position();
902

903
    AST::Node *node = semanticInfo.nodeUnderCursor(cursorPosition);
904

905
906
907
908
    Interpreter::Engine interp;
    Interpreter::Context context(&interp);
    context.build(semanticInfo.declaringMember(cursorPosition), semanticInfo.document, semanticInfo.snapshot);

909
    Evaluate check(&context);
910
911
912
913
914
915
916
917
918
919
920
921
    const Interpreter::Value *value = check.reference(node);
    QString fileName;
    int line = 0, column = 0;

    if (! (value && value->getSourceLocation(&fileName, &line, &column)))
        return Link();

    Link link;
    link.fileName = fileName;
    link.line = line;
    link.column = column - 1; // adjust the column

922
923
924
925
926
    if (AST::UiQualifiedId *q = AST::cast<AST::UiQualifiedId *>(node)) {
        for (AST::UiQualifiedId *tail = q; tail; tail = tail->next) {
            if (! tail->next && cursorPosition <= tail->identifierToken.end()) {
                link.begin = tail->identifierToken.begin();
                link.end = tail->identifierToken.end();
927
928
929
930
                return link;
            }
        }

931
932
933
934
    } else if (AST::IdentifierExpression *id = AST::cast<AST::IdentifierExpression *>(node)) {
        link.begin = id->firstSourceLocation().begin();
        link.end = id->lastSourceLocation().end();
        return link;
935

936
937
938
939
    } else if (AST::FieldMemberExpression *mem = AST::cast<AST::FieldMemberExpression *>(node)) {
        link.begin = mem->lastSourceLocation().begin();
        link.end = mem->lastSourceLocation().end();
        return link;
940
941
    }

942
    return Link();
943
944
}

945
946
947
948
949
void QmlJSTextEditor::followSymbolUnderCursor()
{
    openLink(findLinkAt(textCursor()));
}

950
void QmlJSTextEditor::contextMenuEvent(QContextMenuEvent *e)
951
{
952
    QMenu *menu = new QMenu();
953

954
    if (Core::ActionContainer *mcontext = Core::ICore::instance()->actionManager()->actionContainer(QmlJSEditor::Constants::M_CONTEXT)) {
955
956
957
958
959
960
        QMenu *contextMenu = mcontext->menu();
        foreach (QAction *action, contextMenu->actions())
            menu->addAction(action);
    }

    const QString id = wordUnderCursor();
961
    const QList<AST::SourceLocation> &locations = m_semanticInfo.idLocations.value(id);
962
963
964
965
966
967
    if (! locations.isEmpty()) {
        menu->addSeparator();
        QAction *a = menu->addAction(tr("Rename id '%1'...").arg(id));
        connect(a, SIGNAL(triggered()), this, SLOT(renameIdUnderCursor()));
    }

968
969
    appendStandardContextMenuActions(menu);

970
971
    menu->exec(e->globalPos());
    menu->deleteLater();
972
973
}

974
void QmlJSTextEditor::unCommentSelection()
975
{
976
    Utils::unCommentSelection(this);
977
978
}

979
980
981
982
983
984
985
986
987
988
989
990
991
static bool isCompleteStringLiteral(const QStringRef &text)
{
    if (text.length() < 2)
        return false;

    const QChar quote = text.at(0);

    if (text.at(text.length() - 1) == quote)
        return text.at(text.length() - 2) != QLatin1Char('\\'); // ### not exactly.

    return false;
}

992
bool QmlJSTextEditor::contextAllowsAutoParentheses(const QTextCursor &cursor, const QString &textToInsert) const
993
{
Roberto Raggi's avatar
Roberto Raggi committed
994
995
996
997
998
    QChar ch;

    if (! textToInsert.isEmpty())
        ch = textToInsert.at(0);

999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
    switch (ch.unicode()) {
    case '\'':
    case '"':

    case '(':
    case '[':
    case '{':

    case ')':
    case ']':
    case '}':

    case ';':
        break;

    default:
        if (ch.isNull())
            break;

        return false;
    } // end of switch

1021
1022
1023
    const QString blockText = cursor.block().text();
    const int blockState = blockStartState(cursor.block());

Roberto Raggi's avatar
Roberto Raggi committed
1024
    Scanner tokenize;
1025
    const QList<Token> tokens = tokenize(blockText, blockState);
1026
1027
    const int pos = cursor.columnNumber();

1028
1029
    int tokenIndex = 0;
    for (; tokenIndex < tokens.size(); ++tokenIndex) {
1030
        const Token &token = tokens.at(tokenIndex);
1031

1032
1033
1034
        if (pos >= token.begin()) {
            if (pos < token.end())
                break;
1035

1036
1037
            else if (pos == token.end() && (token.is(Token::Comment) ||
                                            token.is(Token::String)))
1038
1039
                break;
        }
1040
1041
    }

1042
    if (tokenIndex != tokens.size()) {
1043
        const Token &token = tokens.at(tokenIndex);
1044
1045

        switch (token.kind) {
1046
        case Token::Comment:
1047
1048
            return false;

1049
        case Token::String: {
1050
1051
1052
            const QStringRef tokenText = blockText.midRef(token.offset, token.length);
            const QChar quote = tokenText.at(0);

1053
            if (ch != quote || isCompleteStringLiteral(tokenText))
1054
1055
                break;

Roberto Raggi's avatar
Roberto Raggi committed
1056
1057
1058
            return false;
        }

1059
1060
1061
1062
        default:
            break;
        } // end of switch
    }
1063

1064
    return true;
1065
1066
}

1067
bool QmlJSTextEditor::isInComment(const QTextCursor &) const
1068
1069
1070
1071
1072
{
    // ### implement me
    return false;
}

1073
QString QmlJSTextEditor::insertMatchingBrace(const QTextCursor &tc, const QString &text, const QChar &, int *skippedChars) const
1074
1075
1076
1077
{
    if (text.length() != 1)
        return QString();

1078
1079
1080
    if (! shouldInsertMatchingText(tc))
        return QString();

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
    const QChar la = characterAt(tc.position());

    const QChar ch = text.at(0);
    switch (ch.unicode()) {
    case '\'':
        if (la != ch)
            return QString(ch);
        ++*skippedChars;
        break;

    case '"':
        if (la != ch)
            return QString(ch);
        ++*skippedChars;
        break;

    case '(':
        return QString(QLatin1Char(')'));

    case '[':
        return QString(QLatin1Char(']'));

    case '{':
        return QString(); // nothing to do.

    case ')':
    case ']':
    case '}':
    case ';':
        if (la == ch)
            ++*skippedChars;
        break;

    default:
        break;
    } // end of switch

    return QString();
}

1121
QString QmlJSTextEditor::insertParagraphSeparator(const QTextCursor &) const
Roberto Raggi's avatar