qmljseditor.cpp 27.2 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 "qmlhighlighter.h"
33
#include "qmljseditorplugin.h"
34
#include "qmlmodelmanager.h"
35

36
37
#include "qmlexpressionundercursor.h"
#include "qmllookupcontext.h"
38
#include "qmlresolveexpression.h"
39

40
#include <qmljs/qmljsindenter.h>
41

42
#include <qmljs/qmljstypesystem.h>
43
44
45
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>
46
47
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljsidcollector.h>
48

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

60
#include <utils/changeset.h>
61
62
#include <utils/uncommentselection.h>

63
#include <QtCore/QFileInfo>
64
65
66
67
#include <QtCore/QTimer>

#include <QtGui/QMenu>
#include <QtGui/QComboBox>
Roberto Raggi's avatar
Roberto Raggi committed
68
#include <QtGui/QInputDialog>
69
#include <QtGui/QMainWindow>
con's avatar
con committed
70
#include <QtGui/QToolBar>
71
72

enum {
73
74
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 250,
    UPDATE_USES_DEFAULT_INTERVAL = 150
75
76
};

77
78
using namespace QmlJS;
using namespace QmlJS::AST;
79
using namespace QmlJSEditor::Internal;
80

81
namespace {
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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;
}
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

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
125
class FindIdDeclarations: protected Visitor
126
127
{
public:
128
    typedef QHash<QString, QList<AST::SourceLocation> > Result;
129

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

protected:
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
    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;
    }
196
197

private:
198
199
    Result _ids;
    Result _maybeIds;
200
201
};

202
203
class FindDeclarations: protected Visitor
{
204
205
    QList<Declaration> _declarations;
    int _depth;
206
207

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

protected:
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    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('.');
        }
232

233
234
        return text;
    }
Roberto Raggi's avatar
Roberto Raggi committed
235

236
237
238
239
240
241
242
243
244
245
246
247
    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
248

249
250
251
252
253
254
255
256
257
258
    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;
    }

259
260
261
    virtual bool visit(AST::UiObjectDefinition *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
262

263
264
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
265

266
267
268
269
270
        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
271

272
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
273

274
275
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
276

277
278
279
280
    virtual void endVisit(AST::UiObjectDefinition *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
281

282
283
284
    virtual bool visit(AST::UiObjectBinding *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
285

286
287
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
288

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

291
292
        decl.text.append(asString(node->qualifiedId));
        decl.text.append(QLatin1String(": "));
Roberto Raggi's avatar
Roberto Raggi committed
293

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

299
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
300

301
302
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
303

304
305
306
307
    virtual void endVisit(AST::UiObjectBinding *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
308

309
    virtual bool visit(AST::UiScriptBinding *)
310
311
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
312

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

317
318
        decl.text.fill(QLatin1Char(' '), _depth);
        decl.text.append(asString(node->qualifiedId));
Roberto Raggi's avatar
Roberto Raggi committed
319

320
        _declarations.append(decl);
321
#endif
Roberto Raggi's avatar
Roberto Raggi committed
322

323
324
        return false; // more more bindings in this subtree.
    }
Roberto Raggi's avatar
Roberto Raggi committed
325

326
327
328
329
    virtual void endVisit(AST::UiScriptBinding *)
    {
        --_depth;
    }
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
379
380
381

    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;
    }
382
383
};

384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CreateRanges: protected AST::Visitor
{
    QTextDocument *_textDocument;
    QList<Range> _ranges;

public:
    QList<Range> operator()(QTextDocument *textDocument, Document::Ptr doc)
    {
        _textDocument = textDocument;
        _ranges.clear();
        if (doc && doc->qmlProgram() != 0)
            doc->qmlProgram()->accept(this);
        return _ranges;
    }

protected:
    using AST::Visitor::visit;

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

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

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

        range.ast = ast;

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

        range.end = QTextCursor(_textDocument);
        range.end.setPosition(ast->lastSourceLocation().end());
        return range;
    }
};

} // end of anonymous namespace


432
433
434
435
436
437
438
439
int SemanticInfo::revision() const
{
    if (document)
        return document->documentRevision();

    return 0;
}

440
QmlJSEditorEditable::QmlJSEditorEditable(QmlJSTextEditor *editor)
mae's avatar
mae committed
441
    : BaseTextEditorEditable(editor)
442
{
mae's avatar
mae committed
443
444

    Core::UniqueIDManager *uidm = Core::UniqueIDManager::instance();
445
    m_context << uidm->uniqueIdentifier(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
mae's avatar
mae committed
446
    m_context << uidm->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
447
448
}

449
QmlJSTextEditor::QmlJSTextEditor(QWidget *parent) :
450
    TextEditor::BaseTextEditor(parent),
451
    m_methodCombo(0),
452
453
    m_modelManager(0),
    m_typeSystem(0)
454
{
455
456
457
458
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);
    setCodeFoldingVisible(true);
459

460
461
462
463
    m_updateDocumentTimer = new QTimer(this);
    m_updateDocumentTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer->setSingleShot(true);
    connect(m_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));
464

465
466
467
468
469
    m_updateUsesTimer = new QTimer(this);
    m_updateUsesTimer->setInterval(UPDATE_USES_DEFAULT_INTERVAL);
    m_updateUsesTimer->setSingleShot(true);
    connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

470
    connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));
471
    connect(this, SIGNAL(textChanged()), this, SLOT(updateUses()));
472

473
    baseTextDocument()->setSyntaxHighlighter(new QmlHighlighter);
474

475
    m_modelManager = ExtensionSystem::PluginManager::instance()->getObject<QmlModelManagerInterface>();
476
    m_typeSystem = ExtensionSystem::PluginManager::instance()->getObject<QmlJS::TypeSystem>();
477
478

    if (m_modelManager) {
479
480
        connect(m_modelManager, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
                this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
481
    }
482
483
}

484
QmlJSTextEditor::~QmlJSTextEditor()
485
486
487
{
}

488
QList<Declaration> QmlJSTextEditor::declarations() const
489
490
{ return m_declarations; }

491
Core::IEditor *QmlJSEditorEditable::duplicate(QWidget *parent)
492
{
493
    QmlJSTextEditor *newEditor = new QmlJSTextEditor(parent);
494
    newEditor->duplicateFrom(editor());
495
    QmlJSEditorPlugin::instance()->initializeEditor(newEditor);
496
    return newEditor->editableInterface();
497
498
}

499
QString QmlJSEditorEditable::id() const
500
{
501
    return QLatin1String(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
502
503
}

504
505
506
507
508
509
510
bool QmlJSEditorEditable::open(const QString &fileName)
{
    bool b = TextEditor::BaseTextEditorEditable::open(fileName);
    editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type());
    return b;
}

511
QmlJSTextEditor::Context QmlJSEditorEditable::context() const
512
{
513
    return m_context;
514
515
}

516
void QmlJSTextEditor::updateDocument()
517
{
518
    m_updateDocumentTimer->start(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
519
520
}

521
void QmlJSTextEditor::updateDocumentNow()
522
{
523
    // ### move in the parser thread.
524

525
    m_updateDocumentTimer->stop();
526

527
    const QString fileName = file()->fileName();
528

529
530
531
    m_modelManager->updateSourceFiles(QStringList() << fileName);
}

532
void QmlJSTextEditor::onDocumentUpdated(QmlJS::Document::Ptr doc)
533
534
535
536
{
    if (file()->fileName() != doc->fileName())
        return;

537
538
539
540
    if (doc->documentRevision() != document()->revision()) {
        // got an outdated document.
        return;
    }
541

542
543
544
545
    if (doc->ast()) {
        // got a correctly parsed (or recovered) file.

        // create the ranges and update the semantic info.
546
547
548
549
        CreateRanges createRanges;
        SemanticInfo sem;
        sem.document = doc;
        sem.ranges = createRanges(document(), doc);
550
551
552
553
554

        // Refresh the ids
        FindIdDeclarations updateIds;
        sem.idLocations = updateIds(doc);

555
556
        m_semanticInfo = sem;

557
558
559
        if (doc->isParsedCorrectly()) {
            FindDeclarations findDeclarations;
            m_declarations = findDeclarations(doc->ast());
Roberto Raggi's avatar
Roberto Raggi committed
560

561
562
            QStringList items;
            items.append(tr("<Select Symbol>"));
563

564
565
            foreach (Declaration decl, m_declarations)
                items.append(decl.text);
566

567
568
569
570
            m_methodCombo->clear();
            m_methodCombo->addItems(items);
            updateMethodBoxIndex();
        }
571
    }
572

573
    QList<QTextEdit::ExtraSelection> selections;
574

575
    QTextEdit::ExtraSelection sel;
576

577
    const QList<DiagnosticMessage> diagnosticMessages = doc->diagnosticMessages();
578

579
580
581
    foreach (const DiagnosticMessage &d, diagnosticMessages) {
        if (d.isWarning())
            continue;
582

583
584
        const int line = d.loc.startLine;
        const int column = qMax(1U, d.loc.startColumn);
585

586
587
        QTextCursor c(document()->findBlockByNumber(line - 1));
        sel.cursor = c;
588

589
590
591
592
593
        sel.cursor.setPosition(c.position() + column - 1);
        if (sel.cursor.atBlockEnd())
            sel.cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
        else
            sel.cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
594

595
596
597
        sel.format.setUnderlineColor(Qt::red);
        sel.format.setUnderlineStyle(QTextCharFormat::WaveUnderline);
        sel.format.setToolTip(d.message);
598

599
600
        selections.append(sel);
    }
601

602
    setExtraSelections(CodeWarningsSelection, selections);
603
604
}

605
void QmlJSTextEditor::jumpToMethod(int index)
606
{
607
608
609
610
611
    if (index) {
        Declaration d = m_declarations.at(index - 1);
        gotoLine(d.startLine, d.startColumn - 1);
        setFocus();
    }
612
613
}

614
void QmlJSTextEditor::updateMethodBoxIndex()
615
{
616
617
    int line = 0, column = 0;
    convertPosition(position(), &line, &column);
618

619
    int currentSymbolIndex = 0;
620

621
622
623
    int index = 0;
    while (index < m_declarations.size()) {
        const Declaration &d = m_declarations.at(index++);
624

625
626
627
628
629
        if (line < d.startLine)
            break;
        else
            currentSymbolIndex = index;
    }
630

631
    m_methodCombo->setCurrentIndex(currentSymbolIndex);
632
633
634
    updateUses();
}

635
void QmlJSTextEditor::updateUses()
636
637
638
639
{
    m_updateUsesTimer->start();
}

640
void QmlJSTextEditor::updateUsesNow()
641
{
642
    if (document()->revision() != m_semanticInfo.revision()) {
643
644
645
646
647
        updateUses();
        return;
    }

    m_updateUsesTimer->stop();
648

649
    QList<QTextEdit::ExtraSelection> selections;
650
    foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(wordUnderCursor())) {
651
652
        if (! loc.isValid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
653

654
        QTextEdit::ExtraSelection sel;
655
        sel.format = m_occurrencesFormat;
656
657
658
659
660
        sel.cursor = textCursor();
        sel.cursor.setPosition(loc.begin());
        sel.cursor.setPosition(loc.end(), QTextCursor::KeepAnchor);
        selections.append(sel);
    }
661

662
    setExtraSelections(CodeSemanticsSelection, selections);
663
664
}

665
void QmlJSTextEditor::updateMethodBoxToolTip()
666
667
668
{
}

669
void QmlJSTextEditor::updateFileName()
670
671
672
{
}

673
void QmlJSTextEditor::renameIdUnderCursor()
Roberto Raggi's avatar
Roberto Raggi committed
674
{
675
676
677
678
679
680
681
682
    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) {
683
        Utils::ChangeSet changeSet;
684

685
        foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(id)) {
686
            changeSet.replace(loc.offset, loc.length, newId);
687
688
689
        }

        QTextCursor tc = textCursor();
690
        changeSet.apply(&tc);
691
    }
Roberto Raggi's avatar
Roberto Raggi committed
692
693
}

694
QStringList QmlJSTextEditor::keywords() const
695
{
696
    QStringList words;
697

698
    if (QmlHighlighter *highlighter = qobject_cast<QmlHighlighter*>(baseTextDocument()->syntaxHighlighter()))
699
        words = highlighter->keywords().toList();
700

701
    return words;
702
703
}

704
void QmlJSTextEditor::setFontSettings(const TextEditor::FontSettings &fs)
705
{
706
    TextEditor::BaseTextEditor::setFontSettings(fs);
707
    QmlHighlighter *highlighter = qobject_cast<QmlHighlighter*>(baseTextDocument()->syntaxHighlighter());
708
709
710
711
712
713
714
715
716
717
718
    if (!highlighter)
        return;

    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_PREPROCESSOR)
                << QLatin1String(TextEditor::Constants::C_LABEL)
mae's avatar
mae committed
719
720
                << QLatin1String(TextEditor::Constants::C_COMMENT)
                << QLatin1String(TextEditor::Constants::C_VISUAL_WHITESPACE);
721
722
    }

723
724
725
    m_occurrencesFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES));
    m_occurrencesFormat.clearForeground();

726
727
    highlighter->setFormats(fs.toTextCharFormats(categories));
    highlighter->rehighlight();
728
729
}

730
QString QmlJSTextEditor::wordUnderCursor() const
Roberto Raggi's avatar
Roberto Raggi committed
731
{
732
733
734
735
736
    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
737
738
}

739
bool QmlJSTextEditor::isElectricCharacter(const QChar &ch) const
740
{
741
742
    if (ch == QLatin1Char('}')
        || ch == QLatin1Char(']'))
743
744
        return true;
    return false;
745
746
}

747
bool QmlJSTextEditor::isClosingBrace(const QList<Token> &tokens) const
748
{
749

Erik Verbruggen's avatar
Erik Verbruggen committed
750
    if (tokens.size() == 1) {
751
        const Token firstToken = tokens.first();
752

753
        return firstToken.is(Token::RightBrace) || firstToken.is(Token::RightBracket);
Erik Verbruggen's avatar
Erik Verbruggen committed
754
    }
755

Erik Verbruggen's avatar
Erik Verbruggen committed
756
757
    return false;
}
758

759
void QmlJSTextEditor::indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar)
Erik Verbruggen's avatar
Erik Verbruggen committed
760
761
{
    TextEditor::TabSettings ts = tabSettings();
762
    QmlJSIndenter indenter;
763
764
    indenter.setTabSize(ts.m_tabSize);
    indenter.setIndentSize(ts.m_indentSize);
Erik Verbruggen's avatar
Erik Verbruggen committed
765

766
    const int indent = indenter.indentForBottomLine(doc->begin(), block.next(), typedChar);
Erik Verbruggen's avatar
Erik Verbruggen committed
767
    ts.indentLine(block, indent);
768
769
}

770
TextEditor::BaseTextEditorEditable *QmlJSTextEditor::createEditableInterface()
771
{
772
    QmlJSEditorEditable *editable = new QmlJSEditorEditable(this);
773
774
    createToolBar(editable);
    return editable;
775
776
}

777
void QmlJSTextEditor::createToolBar(QmlJSEditorEditable *editable)
778
{
779
780
781
    m_methodCombo = new QComboBox;
    m_methodCombo->setMinimumContentsLength(22);
    //m_methodCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
782

783
784
785
786
    // Make the combo box prefer to expand
    QSizePolicy policy = m_methodCombo->sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_methodCombo->setSizePolicy(policy);
787

788
789
790
    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()));
791

792
    connect(file(), SIGNAL(changed()), this, SLOT(updateFileName()));
793

794
    QToolBar *toolBar = static_cast<QToolBar*>(editable->toolBar());
795

796
797
    QList<QAction*> actions = toolBar->actions();
    toolBar->insertWidget(actions.first(), m_methodCombo);
798
799
}

800
TextEditor::BaseTextEditor::Link QmlJSTextEditor::findLinkAt(const QTextCursor &cursor, bool /*resolveTarget*/)
801
802
803
804
805
806
807
{
    Link link;

    if (!m_modelManager)
        return link;

    const Snapshot snapshot = m_modelManager->snapshot();
808
    Document::Ptr doc = snapshot.document(file()->fileName());
809
810
811
    if (!doc)
        return link;

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
    QTextCursor expressionCursor(cursor);
    {
        // correct the position by moving to the end of an identifier (if we're hovering over one):
        int pos = cursor.position();
        forever {
            const QChar ch = characterAt(pos);

            if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
                ++pos;
            else
                break;
        }
        expressionCursor.setPosition(pos);
    }

827
    QmlExpressionUnderCursor expressionUnderCursor;
828
    expressionUnderCursor(expressionCursor, doc);
829

830
    QmlLookupContext context(expressionUnderCursor.expressionScopes(), doc, snapshot, m_typeSystem);
831
    QmlResolveExpression resolver(context);
832
    Symbol *symbol = resolver.typeOf(expressionUnderCursor.expressionNode());
833
834
835
836

    if (!symbol)
        return link;

837
    if (const SymbolFromFile *target = symbol->asSymbolFromFile()) {
838
839
840
841
842
        link.pos = expressionUnderCursor.expressionOffset();
        link.length = expressionUnderCursor.expressionLength();
        link.fileName = target->fileName();
        link.line = target->line();
        link.column = target->column();
843
844
        if (link.column > 0)
            --link.column;
845
    }
846

847
848
849
    return link;
}

850
void QmlJSTextEditor::contextMenuEvent(QContextMenuEvent *e)
851
{
852
    QMenu *menu = new QMenu();
853

854
    if (Core::ActionContainer *mcontext = Core::ICore::instance()->actionManager()->actionContainer(QmlJSEditor::Constants::M_CONTEXT)) {
855
856
857
858
859
860
        QMenu *contextMenu = mcontext->menu();
        foreach (QAction *action, contextMenu->actions())
            menu->addAction(action);
    }

    const QString id = wordUnderCursor();
861
    const QList<AST::SourceLocation> &locations = m_semanticInfo.idLocations.value(id);
862
863
864
865
866
867
    if (! locations.isEmpty()) {
        menu->addSeparator();
        QAction *a = menu->addAction(tr("Rename id '%1'...").arg(id));
        connect(a, SIGNAL(triggered()), this, SLOT(renameIdUnderCursor()));
    }

868
869
    appendStandardContextMenuActions(menu);

870
871
    menu->exec(e->globalPos());
    menu->deleteLater();
872
873
}

874
void QmlJSTextEditor::unCommentSelection()
875
{
876
    Utils::unCommentSelection(this);
877
878
}

879
880
881
882
883
884
885
886
887
888
889
890
891
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;
}

892
bool QmlJSTextEditor::contextAllowsAutoParentheses(const QTextCursor &cursor, const QString &textToInsert) const
893
{
Roberto Raggi's avatar
Roberto Raggi committed
894
895
896
897
898
    QChar ch;

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

899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
    switch (ch.unicode()) {
    case '\'':
    case '"':

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

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

    case ';':
        break;

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

        return false;
    } // end of switch

921
922
923
    const QString blockText = cursor.block().text();
    const int blockState = blockStartState(cursor.block());

924
    QmlJSScanner tokenize;
925
    const QList<Token> tokens = tokenize(blockText, blockState);
926
927
    const int pos = cursor.columnNumber();

928
929
    int tokenIndex = 0;
    for (; tokenIndex < tokens.size(); ++tokenIndex) {
930
        const Token &token = tokens.at(tokenIndex);
931

932
933
934
        if (pos >= token.begin()) {
            if (pos < token.end())
                break;
935

936
937
            else if (pos == token.end() && (token.is(Token::Comment) ||
                                            token.is(Token::String)))
938
939
                break;
        }
940
941
    }

942
    if (tokenIndex != tokens.size()) {
943
        const Token &token = tokens.at(tokenIndex);
944
945

        switch (token.kind) {
946
        case Token::Comment:
947
948
            return false;

949
        case Token::String: {
950
951
952
953
954
955
            const QStringRef tokenText = blockText.midRef(token.offset, token.length);
            const QChar quote = tokenText.at(0);

            if (ch == quote && isCompleteStringLiteral(tokenText))
                break;

Roberto Raggi's avatar
Roberto Raggi committed
956
957
958
            return false;
        }

959
960
961
962
        default:
            break;
        } // end of switch
    }
963

964
    return true;
965
966
}

967
bool QmlJSTextEditor::isInComment(const QTextCursor &) const
968
969
970
971
972
{
    // ### implement me
    return false;
}

973
QString QmlJSTextEditor::insertMatchingBrace(const QTextCursor &tc, const QString &text, const QChar &, int *skippedChars) const
974
975
976
977
{
    if (text.length() != 1)
        return QString();

978
979
980
    if (! shouldInsertMatchingText(tc))
        return QString();

981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    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 '[':