qmljseditor.cpp 59.5 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
6
**
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
#include "qmljseditorcodeformatter.h"
36
37
#include "qmljsquickfix.h"
#include "qmloutlinemodel.h"
38
#include "qmljsfindreferences.h"
39

40
#include <qmljs/qmljsbind.h>
Christian Kamm's avatar
Christian Kamm committed
41
#include <qmljs/qmljscheck.h>
42
#include <qmljs/qmljsdocument.h>
43
#include <qmljs/qmljsicontextpane.h>
44
#include <qmljs/qmljslookupcontext.h>
45
#include <qmljs/qmljslink.h>
46
47
48
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsengine_p.h>
49

50
#include <coreplugin/actionmanager/actionmanager.h>
51
52
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
53
#include <coreplugin/editormanager/editormanager.h>
54
#include <coreplugin/icore.h>
55
56
57
#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/designmode.h>
58
#include <coreplugin/mimedatabase.h>
59
#include <extensionsystem/pluginmanager.h>
60
61
62
63
#include <texteditor/basetextdocument.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
64
#include <texteditor/syntaxhighlighter.h>
65
#include <texteditor/refactoroverlay.h>
66
#include <texteditor/tooltip/tooltip.h>
67
#include <qmldesigner/qmldesignerconstants.h>
68
#include <utils/changeset.h>
69
70
#include <utils/uncommentselection.h>

71
#include <QtCore/QFileInfo>
72
#include <QtCore/QSignalMapper>
73
74
75
76
#include <QtCore/QTimer>

#include <QtGui/QMenu>
#include <QtGui/QComboBox>
77
#include <QtGui/QHeaderView>
Roberto Raggi's avatar
Roberto Raggi committed
78
#include <QtGui/QInputDialog>
79
#include <QtGui/QMainWindow>
con's avatar
con committed
80
#include <QtGui/QToolBar>
81
#include <QtGui/QTreeView>
82
83

enum {
84
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 100,
85
    UPDATE_USES_DEFAULT_INTERVAL = 150,
86
87
    UPDATE_OUTLINE_INTERVAL = 500, // msecs after new semantic info has been arrived / cursor has moved
    TOOLTIP_TIMER_INTERVAL = 1000 // delay after we show the Quick ToolBar after a tooltip
88
89
};

90
91
using namespace QmlJS;
using namespace QmlJS::AST;
92
using namespace QmlJSEditor::Internal;
93

94
static int blockStartState(const QTextBlock &block)
95
96
97
98
99
100
101
102
{
    int state = block.userState();

    if (state == -1)
        return 0;
    else
        return state & 0xff;
}
103

104
static bool shouldInsertMatchingText(QChar lookAhead)
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
{
    switch (lookAhead.unicode()) {
    case '{': case '}':
    case ']': case ')':
    case ';': case ',':
    case '"': case '\'':
        return true;

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

        return false;
    } // switch
}

121
static bool shouldInsertMatchingText(const QTextCursor &tc)
122
123
124
125
126
{
    QTextDocument *doc = tc.document();
    return shouldInsertMatchingText(doc->characterAt(tc.selectionEnd()));
}

127
128
namespace {

Roberto Raggi's avatar
Roberto Raggi committed
129
class FindIdDeclarations: protected Visitor
130
131
{
public:
132
    typedef QHash<QString, QList<AST::SourceLocation> > Result;
133

134
    Result operator()(Document::Ptr doc)
135
136
137
    {
        _ids.clear();
        _maybeIds.clear();
138
139
        if (doc && doc->qmlProgram())
            doc->qmlProgram()->accept(this);
140
141
        return _ids;
    }
142
143

protected:
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
    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;
    }
200
201

private:
202
203
    Result _ids;
    Result _maybeIds;
204
205
};

206
207
class FindDeclarations: protected Visitor
{
208
209
    QList<Declaration> _declarations;
    int _depth;
210
211

public:
212
213
214
215
216
217
218
    QList<Declaration> operator()(AST::Node *node)
    {
        _depth = -1;
        _declarations.clear();
        accept(node);
        return _declarations;
    }
219
220

protected:
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    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('.');
        }
236

237
238
        return text;
    }
Roberto Raggi's avatar
Roberto Raggi committed
239

240
241
242
243
244
245
246
247
248
249
250
251
    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
252

253
254
255
256
257
258
259
260
261
262
    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;
    }

263
264
265
    virtual bool visit(AST::UiObjectDefinition *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
266

267
268
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
269

270
271
272
273
274
        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
275

276
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
277

278
279
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
280

281
282
283
284
    virtual void endVisit(AST::UiObjectDefinition *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
285

286
287
288
    virtual bool visit(AST::UiObjectBinding *node)
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
289

290
291
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
292

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

295
296
        decl.text.append(asString(node->qualifiedId));
        decl.text.append(QLatin1String(": "));
Roberto Raggi's avatar
Roberto Raggi committed
297

298
299
300
301
        if (node->qualifiedTypeNameId)
            decl.text.append(asString(node->qualifiedTypeNameId));
        else
            decl.text.append(QLatin1Char('?'));
Roberto Raggi's avatar
Roberto Raggi committed
302

303
        _declarations.append(decl);
Roberto Raggi's avatar
Roberto Raggi committed
304

305
306
        return true; // search for more bindings
    }
Roberto Raggi's avatar
Roberto Raggi committed
307

308
309
310
311
    virtual void endVisit(AST::UiObjectBinding *)
    {
        --_depth;
    }
Roberto Raggi's avatar
Roberto Raggi committed
312

313
    virtual bool visit(AST::UiScriptBinding *)
314
315
    {
        ++_depth;
Roberto Raggi's avatar
Roberto Raggi committed
316

317
#if 0 // ### ignore script bindings for now.
318
319
        Declaration decl;
        init(&decl, node);
Roberto Raggi's avatar
Roberto Raggi committed
320

321
322
        decl.text.fill(QLatin1Char(' '), _depth);
        decl.text.append(asString(node->qualifiedId));
Roberto Raggi's avatar
Roberto Raggi committed
323

324
        _declarations.append(decl);
325
#endif
Roberto Raggi's avatar
Roberto Raggi committed
326

327
328
        return false; // more more bindings in this subtree.
    }
Roberto Raggi's avatar
Roberto Raggi committed
329

330
331
332
333
    virtual void endVisit(AST::UiScriptBinding *)
    {
        --_depth;
    }
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
382
383
384
385

    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;
    }
386
387
};

388
389
390
391
392
393
394
395
396
397
class CreateRanges: protected AST::Visitor
{
    QTextDocument *_textDocument;
    QList<Range> _ranges;

public:
    QList<Range> operator()(QTextDocument *textDocument, Document::Ptr doc)
    {
        _textDocument = textDocument;
        _ranges.clear();
398
399
        if (doc && doc->ast() != 0)
            doc->ast()->accept(this);
400
401
402
403
404
405
406
407
        return _ranges;
    }

protected:
    using AST::Visitor::visit;

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

    virtual bool visit(AST::UiObjectDefinition *ast)
    {
415
416
        if (ast->initializer)
            _ranges.append(createRange(ast, ast->initializer));
417
418
419
        return true;
    }

420
421
422
423
424
425
426
427
428
429
430
431
    virtual bool visit(AST::FunctionExpression *ast)
    {
        _ranges.append(createRange(ast));
        return true;
    }

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

432
    Range createRange(AST::UiObjectMember *member, AST::UiObjectInitializer *ast)
433
434
435
    {
        Range range;

436
        range.ast = member;
437
438

        range.begin = QTextCursor(_textDocument);
439
        range.begin.setPosition(member->firstSourceLocation().begin());
440
441

        range.end = QTextCursor(_textDocument);
442
        range.end.setPosition(ast->rbraceToken.end());
443
444
        return range;
    }
445
446
447
448
449
450
451
452
453
454
455
456

    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());
457

458
459
460
        return range;
    }

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
492
493
494
495
496
497
498

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

499
500
501
} // end of anonymous namespace


502
AST::Node *SemanticInfo::declaringMember(int cursorPosition) const
503
{
504
    AST::Node *declaringMember = 0;
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519

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

520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
QmlJS::AST::Node *SemanticInfo::declaringMemberNoProperties(int cursorPosition) const
{
   AST::Node *node = declaringMember(cursorPosition);

   if (UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(node)) {
       QString name = objectDefinition->qualifiedTypeNameId->name->asString();
       if (!name.isNull() && name.at(0).isLower()) {
           QList<AST::Node *> path = astPath(cursorPosition);
           if (path.size() > 1)
               return path.at(path.size() - 2);
       } else if (name.contains("GradientStop")) {
           QList<AST::Node *> path = astPath(cursorPosition);
           if (path.size() > 2)
               return path.at(path.size() - 3);
       }
   } else if (UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node)) {
       QString name = objectBinding->qualifiedTypeNameId->name->asString();
       if (name.contains("Gradient")) {
           QList<AST::Node *> path = astPath(cursorPosition);
           if (path.size() > 1)
               return path.at(path.size() - 2);
       }
   }

   return node;
}

547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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;
}

562
563
LookupContext::Ptr SemanticInfo::lookupContext(const QList<QmlJS::AST::Node *> &path) const
{
564
565
566
567
568
    Q_ASSERT(! m_context.isNull());

    if (m_context.isNull())
        return LookupContext::create(document, snapshot, path);

569
570
571
    return LookupContext::create(document, snapshot, *m_context, path);
}

572
573
574
575
576
577
static bool importContainsCursor(UiImport *importAst, unsigned cursorPosition)
{
    return cursorPosition >= importAst->firstSourceLocation().begin()
           && cursorPosition <= importAst->lastSourceLocation().end();
}

578
579
580
581
582
583
584
AST::Node *SemanticInfo::nodeUnderCursor(int pos) const
{
    if (! document)
        return 0;

    const unsigned cursorPosition = pos;

585
586
587
    foreach (const Interpreter::ImportInfo &import, document->bind()->imports()) {
        if (importContainsCursor(import.ast(), cursorPosition))
            return import.ast();
588
589
    }

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    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;
}

615
616
617
618
619
620
621
622
bool SemanticInfo::isValid() const
{
    if (document && m_context)
        return true;

    return false;
}

623
624
625
int SemanticInfo::revision() const
{
    if (document)
626
        return document->editorRevision();
627
628
629
630

    return 0;
}

631
QmlJSEditorEditable::QmlJSEditorEditable(QmlJSTextEditor *editor)
mae's avatar
mae committed
632
    : BaseTextEditorEditable(editor)
633
{
634
635
    m_context.add(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
636
637
}

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Use preferred mode from Bauhaus settings
static bool openInDesignMode()
{
    static bool bauhausDetected = false;
    static bool bauhausPresent = false;
    // Check if Bauhaus is loaded, that is, a Design mode widget is
    // registered for the QML mime type.
    if (!bauhausDetected) {
        if (const Core::IMode *dm = Core::ModeManager::instance()->mode(QLatin1String(Core::Constants::MODE_DESIGN)))
            if (const Core::DesignMode *designMode = qobject_cast<const Core::DesignMode *>(dm))
                bauhausPresent = designMode->registeredMimeTypes().contains(QLatin1String(QmlJSEditor::Constants::QML_MIMETYPE));
        bauhausDetected =  true;
    }
    if (!bauhausPresent)
        return false;
653
654

    return bool(QmlDesigner::Constants::QML_OPENDESIGNMODE_DEFAULT);
655
656
}

657
QString QmlJSEditorEditable::preferredModeType() const
658
{
659
    Core::ModeManager *modeManager = Core::ModeManager::instance();
660
    if (modeManager->currentMode()
661
662
            && (modeManager->currentMode()->type() == Core::Constants::MODE_DESIGN_TYPE
                || modeManager->currentMode()->type() == Core::Constants::MODE_EDIT_TYPE))
663
    {
664
        return modeManager->currentMode()->type();
665
666
667
668
669
    }

    // if we are in other mode than edit or design, use the hard-coded default.
    // because the editor opening decision is modal, it would be confusing to
    // have the user also access to this failsafe setting.
670
671
    if (editor()->mimeType() == QLatin1String(QmlJSEditor::Constants::QML_MIMETYPE)
        && openInDesignMode())
672
        return QLatin1String(Core::Constants::MODE_DESIGN_TYPE);
673
674
675
    return QString();
}

676
QmlJSTextEditor::QmlJSTextEditor(QWidget *parent) :
677
    TextEditor::BaseTextEditor(parent),
678
    m_outlineCombo(0),
679
    m_outlineModel(new QmlOutlineModel(this)),
680
    m_modelManager(0),
681
    m_contextPane(0),
682
    m_updateSelectedElements(false),
683
684
    m_toolTipPosition(0),
    m_findReferences(new FindReferences(this))
685
{
686
    qRegisterMetaType<QmlJSEditor::Internal::SemanticInfo>("QmlJSEditor::Internal::SemanticInfo");
Christian Kamm's avatar
Christian Kamm committed
687
688
689
690

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

691
692
693
694
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);
    setCodeFoldingVisible(true);
695

696
697
698
699
    m_updateDocumentTimer = new QTimer(this);
    m_updateDocumentTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer->setSingleShot(true);
    connect(m_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));
700

701
702
703
704
705
    m_updateUsesTimer = new QTimer(this);
    m_updateUsesTimer->setInterval(UPDATE_USES_DEFAULT_INTERVAL);
    m_updateUsesTimer->setSingleShot(true);
    connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

706
707
708
    m_semanticRehighlightTimer = new QTimer(this);
    m_semanticRehighlightTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_semanticRehighlightTimer->setSingleShot(true);
709
    connect(m_semanticRehighlightTimer, SIGNAL(timeout()), this, SLOT(forceSemanticRehighlight()));
710

711
    connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));
712

713
    connect(this, SIGNAL(textChanged()), this, SLOT(updateUses()));
714
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateUses()));
715

716
717
718
719
720
    m_updateOutlineTimer = new QTimer(this);
    m_updateOutlineTimer->setInterval(UPDATE_OUTLINE_INTERVAL);
    m_updateOutlineTimer->setSingleShot(true);
    connect(m_updateOutlineTimer, SIGNAL(timeout()), this, SLOT(updateOutlineNow()));

721
722
723
724
    m_updateOutlineIndexTimer = new QTimer(this);
    m_updateOutlineIndexTimer->setInterval(UPDATE_OUTLINE_INTERVAL);
    m_updateOutlineIndexTimer->setSingleShot(true);
    connect(m_updateOutlineIndexTimer, SIGNAL(timeout()), this, SLOT(updateOutlineIndexNow()));
725

Lasse Holmstedt's avatar
Lasse Holmstedt committed
726
    m_cursorPositionTimer  = new QTimer(this);
727
    m_cursorPositionTimer->setInterval(UPDATE_OUTLINE_INTERVAL);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
728
729
    m_cursorPositionTimer->setSingleShot(true);
    connect(m_cursorPositionTimer, SIGNAL(timeout()), this, SLOT(updateCursorPositionNow()));
730

731
732
733
734
    m_toolTipTimer  = new QTimer(this);
    m_toolTipTimer->setInterval(TOOLTIP_TIMER_INTERVAL);
    m_toolTipTimer->setSingleShot(true);
    connect(m_toolTipTimer, SIGNAL(timeout()), this, SLOT(updateToolTipNow()));
735

736
    baseTextDocument()->setSyntaxHighlighter(new Highlighter(document()));
737

Roberto Raggi's avatar
Roberto Raggi committed
738
    m_modelManager = ExtensionSystem::PluginManager::instance()->getObject<ModelManagerInterface>();
739
    m_contextPane = ExtensionSystem::PluginManager::instance()->getObject<QmlJS::IContextPane>();
740
741
742


    if (m_contextPane) {
743
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));
744
745
        connect(m_contextPane, SIGNAL(closed()), this, SLOT(showTextMarker()));
    }
Kai Koehne's avatar
Kai Koehne committed
746
    m_oldCursorPosition = -1;
747
748

    if (m_modelManager) {
749
        m_semanticHighlighter->setModelManager(m_modelManager);
750
751
        connect(m_modelManager, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
                this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
752
        connect(this->document(), SIGNAL(modificationChanged(bool)), this, SLOT(modificationChanged(bool)));
753
    }
Christian Kamm's avatar
Christian Kamm committed
754

755
756
    connect(m_semanticHighlighter, SIGNAL(changed(QmlJSEditor::Internal::SemanticInfo)),
            this, SLOT(updateSemanticInfo(QmlJSEditor::Internal::SemanticInfo)));
757

758
759
760
    connect(this, SIGNAL(refactorMarkerClicked(TextEditor::Internal::RefactorMarker)),
            SLOT(onRefactorMarkerClicked(TextEditor::Internal::RefactorMarker)));

761
762
763
    connect(editableInterface(), SIGNAL(tooltipRequested(TextEditor::ITextEditor*, QPoint, int)),
            SLOT(onTooltipRequested(TextEditor::ITextEditor*, QPoint, int)));

764
    setRequestMarkEnabled(true);
765
766
}

767
QmlJSTextEditor::~QmlJSTextEditor()
768
{
Christian Kamm's avatar
Christian Kamm committed
769
770
    m_semanticHighlighter->abort();
    m_semanticHighlighter->wait();
771
772
}

773
774
775
776
777
SemanticInfo QmlJSTextEditor::semanticInfo() const
{
    return m_semanticInfo;
}

778
int QmlJSTextEditor::editorRevision() const
779
780
781
782
{
    return document()->revision();
}

783
784
bool QmlJSTextEditor::isOutdated() const
{
785
    if (m_semanticInfo.revision() != editorRevision())
786
787
788
789
790
        return true;

    return false;
}

791
792
793
794
795
QmlOutlineModel *QmlJSTextEditor::outlineModel() const
{
    return m_outlineModel;
}

796
QModelIndex QmlJSTextEditor::outlineModelIndex()
797
{
798
799
800
801
    if (!m_outlineModelIndex.isValid()) {
        m_outlineModelIndex = indexForPosition(position());
        emit outlineModelIndexChanged(m_outlineModelIndex);
    }
802
803
804
    return m_outlineModelIndex;
}

805
Core::IEditor *QmlJSEditorEditable::duplicate(QWidget *parent)
806
{
807
    QmlJSTextEditor *newEditor = new QmlJSTextEditor(parent);
808
    newEditor->duplicateFrom(editor());
809
    QmlJSEditorPlugin::instance()->initializeEditor(newEditor);
810
    return newEditor->editableInterface();
811
812
}

813
QString QmlJSEditorEditable::id() const
814
{
815
    return QLatin1String(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
816
817
}

818
819
820
821
822
823
824
bool QmlJSEditorEditable::open(const QString &fileName)
{
    bool b = TextEditor::BaseTextEditorEditable::open(fileName);
    editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type());
    return b;
}

825
Core::Context QmlJSEditorEditable::context() const
826
{
827
    return m_context;
828
829
}

830
void QmlJSTextEditor::updateDocument()
831
{
832
    m_updateDocumentTimer->start(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
833
834
}

835
void QmlJSTextEditor::updateDocumentNow()
836
{
837
    // ### move in the parser thread.
838

839
    m_updateDocumentTimer->stop();
840

841
    const QString fileName = file()->fileName();
842

843
    m_modelManager->updateSourceFiles(QStringList() << fileName, false);
844
845
}

846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
static void appendExtraSelectionsForMessages(
        QList<QTextEdit::ExtraSelection> *selections,
        const QList<DiagnosticMessage> &messages,
        const QTextDocument *document)
{
    foreach (const DiagnosticMessage &d, messages) {
        const int line = d.loc.startLine;
        const int column = qMax(1U, d.loc.startColumn);

        QTextEdit::ExtraSelection sel;
        QTextCursor c(document->findBlockByNumber(line - 1));
        sel.cursor = c;

        sel.cursor.setPosition(c.position() + column - 1);

        if (d.loc.length == 0) {
            if (sel.cursor.atBlockEnd())
                sel.cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
            else
                sel.cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
        } else {
            sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, d.loc.length);
        }

        if (d.isWarning())
            sel.format.setUnderlineColor(Qt::darkYellow);
        else
            sel.format.setUnderlineColor(Qt::red);

        sel.format.setUnderlineStyle(QTextCharFormat::WaveUnderline);
        sel.format.setToolTip(d.message);

        selections->append(sel);
    }
}

882
void QmlJSTextEditor::onDocumentUpdated(QmlJS::Document::Ptr doc)
883
{
884
    if (file()->fileName() != doc->fileName()
885
            || doc->editorRevision() != document()->revision()) {
886
887
        // didn't get the currently open, or an up to date document.
        // trigger a semantic rehighlight anyway, after a time
888
        m_semanticRehighlightTimer->start();
889
890
        return;
    }
891

892
893
894
    if (doc->ast()) {
        // got a correctly parsed (or recovered) file.

Christian Kamm's avatar
Christian Kamm committed
895
896
        const SemanticHighlighter::Source source = currentSource(/*force = */ true);
        m_semanticHighlighter->rehighlight(source);
897
    } else {
898
        // show parsing errors
899
900
901
        QList<QTextEdit::ExtraSelection> selections;
        appendExtraSelectionsForMessages(&selections, doc->diagnosticMessages(), document());
        setExtraSelections(CodeWarningsSelection, selections);
902
    }
903
904
}

905
906
907
908
909
910
void QmlJSTextEditor::modificationChanged(bool changed)
{
    if (!changed && m_modelManager)
        m_modelManager->fileChangedOnDisk(file()->fileName());
}

Kai Koehne's avatar
Kai Koehne committed
911
void QmlJSTextEditor::jumpToOutlineElement(int /*index*/)
912
{
913
    QModelIndex index = m_outlineCombo->view()->currentIndex();
914
915
916
917
    AST::SourceLocation location = m_outlineModel->sourceLocation(index);

    if (!location.isValid())
        return;
918

919
920
921
922
    Core::EditorManager *editorManager = Core::EditorManager::instance();
    editorManager->cutForwardNavigationHistory();
    editorManager->addCurrentPositionToNavigationHistory();

923
924
925
926
927
    QTextCursor cursor = textCursor();
    cursor.setPosition(location.offset);
    setTextCursor(cursor);

    setFocus();
928
929
}

930
void QmlJSTextEditor::updateOutlineNow()
931
{
932
    if (!m_semanticInfo.document)
933
934
        return;

935
    if (m_semanticInfo.document->editorRevision() != editorRevision()) {
936
937
        m_updateOutlineTimer->start();
        return;
938
    }
939

940
    m_outlineModel->update(m_semanticInfo);
941
942
943
944

    QTreeView *treeView = static_cast<QTreeView*>(m_outlineCombo->view());
    treeView->expandAll();

945
    updateOutlineIndexNow();
946
947
}

948
void QmlJSTextEditor::updateOutlineIndexNow()
949
{
950
    if (m_updateOutlineTimer->isActive())
Kai Koehne's avatar
Kai Koehne committed
951
        return; // updateOutlineNow will call this function soon anyway
952

953
    if (!m_outlineModel->document())
954
        return;
955

956
    if (m_outlineModel->document()->editorRevision() != editorRevision()) {
957
        m_updateOutlineIndexTimer->start();
958
959
        return;
    }
960

961
962
    m_outlineModelIndex = QModelIndex(); // invalidate
    QModelIndex comboIndex = outlineModelIndex();
963

964
    if (comboIndex.isValid()) {
965
        bool blocked = m_outlineCombo->blockSignals(true);
966

967
        // There is no direct way to select a non-root item
968
969
970
        m_outlineCombo->setRootModelIndex(comboIndex.parent());
        m_outlineCombo->setCurrentIndex(comboIndex.row());
        m_outlineCombo->setRootModelIndex(QModelIndex());
971

972
        m_outlineCombo->blockSignals(blocked);
973
    }
974
975
}

976
static UiQualifiedId *qualifiedTypeNameId(Node *m)
977
978
979
980
981
982
983
984
985
986
{
    if (UiObjectDefinition *def = cast<UiObjectDefinition *>(m))
        return def->qualifiedTypeNameId;
    else if (UiObjectBinding *binding = cast<UiObjectBinding *>(m))
        return binding->qualifiedTypeNameId;
    return 0;
}

void QmlJSTextEditor::updateCursorPositionNow()
{
987
988
    if (m_contextPane && document() && semanticInfo().isValid()
            && document()->revision() == semanticInfo().document->editorRevision())
989
    {
990
991
        Node *oldNode = m_semanticInfo.declaringMemberNoProperties(m_oldCursorPosition);
        Node *newNode = m_semanticInfo.declaringMemberNoProperties(position());
Thomas Hartmann's avatar
Thomas Hartmann committed
992
        if (oldNode != newNode && m_oldCursorPosition != -1)
993
            m_contextPane->apply(editableInterface(), m_semanticInfo.lookupContext(), newNode, false);
994
        if (m_contextPane->isAvailable(editableInterface(), m_semanticInfo.lookupContext(), newNode) &&
995
            !m_contextPane->widget()->isVisible()) {
996
997
            QList<TextEditor::Internal::RefactorMarker> markers;
            if (UiObjectMember *m = newNode->uiObjectMemberCast()) {
998
                const int start = qualifiedTypeNameId(m)->identifierToken.begin();
999
1000
1001
                for (UiQualifiedId *q = qualifiedTypeNameId(m); q; q = q->next) {
                    if (! q->next) {
                        const int end = q->identifierToken.end();
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
                        if (position() >= start && position() <= end) {
                            TextEditor::Internal::RefactorMarker marker;
                            QTextCursor tc(document());
                            tc.setPosition(end);
                            marker.cursor = tc;
                            marker.tooltip = tr("Show Qt Quick ToolBar");
                            markers.append(marker);
                        } else {
                             QList<TextEditor::Internal::RefactorMarker> markers;
                             setRefactorMarkers(markers);
                        }
1013
1014
1015
1016
                    }
                }
            }
            setRefactorMarkers(markers);
Thomas Hartmann's avatar
Thomas Hartmann committed
1017
        } else if (oldNode != newNode) {
1018
1019
            QList<TextEditor::Internal::RefactorMarker> markers;
            setRefactorMarkers(markers);
1020
1021
        }
        m_oldCursorPosition = position();
1022
1023

        setSelectedElements();
1024
1025
1026
    }
}

1027
1028
1029
1030
1031
1032
void QmlJSTextEditor::showTextMarker()
{
    m_oldCursorPosition = -1;
    updateCursorPositionNow();
}

1033
void QmlJSTextEditor::updateUses()
1034
1035
1036
1037
{
    m_updateUsesTimer->start();
}

1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
bool QmlJSTextEditor::updateSelectedElements() const
{
    return m_updateSelectedElements;
}

void QmlJSTextEditor::setUpdateSelectedElements(bool value)
{
    m_updateSelectedElements = value;
}

1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
void QmlJSTextEditor::renameId(const QString &oldId, const QString &newId)
{
    Utils::ChangeSet changeSet;

    foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(oldId)) {
        changeSet.replace(loc.begin(), loc.end(), newId);
    }

    QTextCursor tc = textCursor();
    changeSet.apply(&tc);
}

1060
void QmlJSTextEditor::updateUsesNow()
1061
{
1062
    if (document()->revision() != m_semanticInfo.revision()) {
1063
1064
1065
1066
1067
        updateUses();
        return;
    }

    m_updateUsesTimer->stop();
1068

1069
    QList<QTextEdit::ExtraSelection> selections;
1070
    foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(wordUnderCursor())) {
1071
1072
        if (! loc.isValid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
1073

1074
        QTextEdit::ExtraSelection sel;
1075
        sel.format = m_occurrencesFormat;
1076
1077
1078
1079
1080
        sel.cursor = textCursor();
        sel.cursor.setPosition(loc.begin());
        sel.cursor.setPosition(loc.end(), QTextCursor::KeepAnchor);
        selections.append(sel);
    }
1081

1082
    setExtraSelections(CodeSemanticsSelection, selections);
1083
1084
1085
1086
}

class SelectedElement: protected Visitor
{
1087
1088
1089
1090
    unsigned m_cursorPositionStart;
    unsigned m_cursorPositionEnd;
    QList<UiObjectMember *> m_selectedMembers;
    LookupContext::Ptr m_lookupContext;
1091
1092
1093

public:
    SelectedElement()
1094
        : m_cursorPositionStart(0), m_cursorPositionEnd(0) {}
1095

1096
    QList<UiObjectMember *> operator()(LookupContext::Ptr lookupContext, unsigned startPosition, unsigned endPosition)
1097
    {
1098
        m_lookupContext = lookupContext;
1099
1100
1101
        m_cursorPositionStart = startPosition;
        m_cursorPositionEnd = endPosition;
        m_selectedMembers.clear();
1102
        Node::accept(lookupContext->document()->qmlProgram(), this);
1103
        return m_selectedMembers;
1104
1105
1106
    }

protected:
1107

1108
    bool isSelectable(UiObjectMember *member) const