qmljseditor.cpp 55.4 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 "qmloutlinemodel.h"
36
#include "qmljseditorcodeformatter.h"
37

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

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

68
#include <QtCore/QFileInfo>
69
70
71
72
#include <QtCore/QTimer>

#include <QtGui/QMenu>
#include <QtGui/QComboBox>
73
#include <QtGui/QHeaderView>
Roberto Raggi's avatar
Roberto Raggi committed
74
#include <QtGui/QInputDialog>
75
#include <QtGui/QMainWindow>
con's avatar
con committed
76
#include <QtGui/QToolBar>
77
#include <QtGui/QTreeView>
78
79

enum {
80
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 50,
81
    UPDATE_USES_DEFAULT_INTERVAL = 150,
82
    UPDATE_OUTLINE_INTERVAL = 500 // msecs after new semantic info has been arrived / cursor has moved
83
84
};

85
86
using namespace QmlJS;
using namespace QmlJS::AST;
87
using namespace QmlJSEditor::Internal;
88

89
static int blockStartState(const QTextBlock &block)
90
91
92
93
94
95
96
97
{
    int state = block.userState();

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

99
static bool shouldInsertMatchingText(QChar lookAhead)
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
{
    switch (lookAhead.unicode()) {
    case '{': case '}':
    case ']': case ')':
    case ';': case ',':
    case '"': case '\'':
        return true;

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

        return false;
    } // switch
}

116
static bool shouldInsertMatchingText(const QTextCursor &tc)
117
118
119
120
121
{
    QTextDocument *doc = tc.document();
    return shouldInsertMatchingText(doc->characterAt(tc.selectionEnd()));
}

122
123
namespace {

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

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

protected:
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    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;
    }
195
196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

protected:
    using AST::Visitor::visit;

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

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

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

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

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

431
        range.ast = member;
432
433

        range.begin = QTextCursor(_textDocument);
434
        range.begin.setPosition(member->firstSourceLocation().begin());
435
436

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

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

453
454
455
        return range;
    }

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
492
493

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

494
495
496
} // end of anonymous namespace


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

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

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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;
}

542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
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;
}

557
558
559
560
561
LookupContext::Ptr SemanticInfo::lookupContext(const QList<QmlJS::AST::Node *> &path) const
{
    return LookupContext::create(document, snapshot, *m_context, path);
}

562
563
564
565
566
567
static bool importContainsCursor(UiImport *importAst, unsigned cursorPosition)
{
    return cursorPosition >= importAst->firstSourceLocation().begin()
           && cursorPosition <= importAst->lastSourceLocation().end();
}

568
569
570
571
572
573
574
AST::Node *SemanticInfo::nodeUnderCursor(int pos) const
{
    if (! document)
        return 0;

    const unsigned cursorPosition = pos;

575
576
577
578
579
580
581
582
583
584
585
586
587
    foreach (const Bind::ImportInfo &import, document->bind()->fileImports()) {
        if (importContainsCursor(import.ast, cursorPosition))
            return import.ast;
    }
    foreach (const Bind::ImportInfo &import, document->bind()->directoryImports()) {
        if (importContainsCursor(import.ast, cursorPosition))
            return import.ast;
    }
    foreach (const Bind::ImportInfo &import, document->bind()->libraryImports()) {
        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
    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;
}

613
614
615
int SemanticInfo::revision() const
{
    if (document)
616
        return document->editorRevision();
617
618
619
620

    return 0;
}

621
QmlJSEditorEditable::QmlJSEditorEditable(QmlJSTextEditor *editor)
mae's avatar
mae committed
622
    : BaseTextEditorEditable(editor)
623
{
624
625
    m_context.add(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
    m_context.add(TextEditor::Constants::C_TEXTEDITOR);
626
627
}

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
// 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;
643
644

    return bool(QmlDesigner::Constants::QML_OPENDESIGNMODE_DEFAULT);
645
646
647
648
}

QString QmlJSEditorEditable::preferredMode() const
{
649
    Core::ModeManager *modeManager = Core::ModeManager::instance();
650
651
652
    if (modeManager->currentMode()
            && (modeManager->currentMode()->id() == Core::Constants::MODE_DESIGN
                || modeManager->currentMode()->id() == Core::Constants::MODE_EDIT))
653
654
655
656
657
658
659
    {
        return modeManager->currentMode()->id();
    }

    // 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.
660
661
    if (editor()->mimeType() == QLatin1String(QmlJSEditor::Constants::QML_MIMETYPE)
        && openInDesignMode())
662
663
664
665
        return QLatin1String(Core::Constants::MODE_DESIGN);
    return QString();
}

666
QmlJSTextEditor::QmlJSTextEditor(QWidget *parent) :
667
    TextEditor::BaseTextEditor(parent),
668
    m_outlineCombo(0),
669
    m_outlineModel(new QmlOutlineModel(this)),
670
    m_modelManager(0),
671
672
    m_contextPane(0),
    m_updateSelectedElements(false)
673
{
674
    qRegisterMetaType<QmlJSEditor::Internal::SemanticInfo>("QmlJSEditor::Internal::SemanticInfo");
Christian Kamm's avatar
Christian Kamm committed
675
676
677
678

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

679
680
681
682
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);
    setCodeFoldingVisible(true);
683

684
685
686
687
    m_updateDocumentTimer = new QTimer(this);
    m_updateDocumentTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer->setSingleShot(true);
    connect(m_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));
688

689
690
691
692
693
    m_updateUsesTimer = new QTimer(this);
    m_updateUsesTimer->setInterval(UPDATE_USES_DEFAULT_INTERVAL);
    m_updateUsesTimer->setSingleShot(true);
    connect(m_updateUsesTimer, SIGNAL(timeout()), this, SLOT(updateUsesNow()));

694
695
696
    m_semanticRehighlightTimer = new QTimer(this);
    m_semanticRehighlightTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_semanticRehighlightTimer->setSingleShot(true);
697
    connect(m_semanticRehighlightTimer, SIGNAL(timeout()), this, SLOT(forceSemanticRehighlight()));
698

699
    connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));
700

701
    connect(this, SIGNAL(textChanged()), this, SLOT(updateUses()));
702
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateUses()));
703

704
705
706
707
708
    m_updateOutlineTimer = new QTimer(this);
    m_updateOutlineTimer->setInterval(UPDATE_OUTLINE_INTERVAL);
    m_updateOutlineTimer->setSingleShot(true);
    connect(m_updateOutlineTimer, SIGNAL(timeout()), this, SLOT(updateOutlineNow()));

709
710
711
712
    m_updateOutlineIndexTimer = new QTimer(this);
    m_updateOutlineIndexTimer->setInterval(UPDATE_OUTLINE_INTERVAL);
    m_updateOutlineIndexTimer->setSingleShot(true);
    connect(m_updateOutlineIndexTimer, SIGNAL(timeout()), this, SLOT(updateOutlineIndexNow()));
713

Lasse Holmstedt's avatar
Lasse Holmstedt committed
714
715
716
717
    m_cursorPositionTimer  = new QTimer(this);
    m_cursorPositionTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_cursorPositionTimer->setSingleShot(true);
    connect(m_cursorPositionTimer, SIGNAL(timeout()), this, SLOT(updateCursorPositionNow()));
718

719
    baseTextDocument()->setSyntaxHighlighter(new Highlighter(document()));
720

Roberto Raggi's avatar
Roberto Raggi committed
721
    m_modelManager = ExtensionSystem::PluginManager::instance()->getObject<ModelManagerInterface>();
722
    m_contextPane = ExtensionSystem::PluginManager::instance()->getObject<QmlJS::IContextPane>();
723
724
725


    if (m_contextPane) {
726
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));
727
728
        connect(m_contextPane, SIGNAL(closed()), this, SLOT(showTextMarker()));
    }
Kai Koehne's avatar
Kai Koehne committed
729
    m_oldCursorPosition = -1;
730
731

    if (m_modelManager) {
732
        m_semanticHighlighter->setModelManager(m_modelManager);
733
734
        connect(m_modelManager, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
                this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
735
        connect(this->document(), SIGNAL(modificationChanged(bool)), this, SLOT(modificationChanged(bool)));
736
    }
Christian Kamm's avatar
Christian Kamm committed
737

738
739
    connect(m_semanticHighlighter, SIGNAL(changed(QmlJSEditor::Internal::SemanticInfo)),
            this, SLOT(updateSemanticInfo(QmlJSEditor::Internal::SemanticInfo)));
740

741
742
743
    connect(this, SIGNAL(refactorMarkerClicked(TextEditor::Internal::RefactorMarker)),
            SLOT(onRefactorMarkerClicked(TextEditor::Internal::RefactorMarker)));

744
    setRequestMarkEnabled(true);
745
746
}

747
QmlJSTextEditor::~QmlJSTextEditor()
748
{
Christian Kamm's avatar
Christian Kamm committed
749
750
    m_semanticHighlighter->abort();
    m_semanticHighlighter->wait();
751
752
}

753
754
755
756
757
SemanticInfo QmlJSTextEditor::semanticInfo() const
{
    return m_semanticInfo;
}

758
int QmlJSTextEditor::editorRevision() const
759
760
761
762
{
    return document()->revision();
}

763
764
bool QmlJSTextEditor::isOutdated() const
{
765
    if (m_semanticInfo.revision() != editorRevision())
766
767
768
769
770
        return true;

    return false;
}

771
772
773
774
775
QmlOutlineModel *QmlJSTextEditor::outlineModel() const
{
    return m_outlineModel;
}

776
QModelIndex QmlJSTextEditor::outlineModelIndex()
777
{
778
779
780
781
    if (!m_outlineModelIndex.isValid()) {
        m_outlineModelIndex = indexForPosition(position());
        emit outlineModelIndexChanged(m_outlineModelIndex);
    }
782
783
784
    return m_outlineModelIndex;
}

785
Core::IEditor *QmlJSEditorEditable::duplicate(QWidget *parent)
786
{
787
    QmlJSTextEditor *newEditor = new QmlJSTextEditor(parent);
788
    newEditor->duplicateFrom(editor());
789
    QmlJSEditorPlugin::instance()->initializeEditor(newEditor);
790
    return newEditor->editableInterface();
791
792
}

793
QString QmlJSEditorEditable::id() const
794
{
795
    return QLatin1String(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
796
797
}

798
799
800
801
802
803
804
bool QmlJSEditorEditable::open(const QString &fileName)
{
    bool b = TextEditor::BaseTextEditorEditable::open(fileName);
    editor()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type());
    return b;
}

805
Core::Context QmlJSEditorEditable::context() const
806
{
807
    return m_context;
808
809
}

810
void QmlJSTextEditor::updateDocument()
811
{
812
    m_updateDocumentTimer->start(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
813
814
}

815
void QmlJSTextEditor::updateDocumentNow()
816
{
817
    // ### move in the parser thread.
818

819
    m_updateDocumentTimer->stop();
820

821
    const QString fileName = file()->fileName();
822

823
    m_modelManager->updateSourceFiles(QStringList() << fileName, false);
824
825
}

826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
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);
    }
}

862
void QmlJSTextEditor::onDocumentUpdated(QmlJS::Document::Ptr doc)
863
{
864
    if (file()->fileName() != doc->fileName()
865
            || doc->editorRevision() != document()->revision()) {
866
867
        // didn't get the currently open, or an up to date document.
        // trigger a semantic rehighlight anyway, after a time
868
        m_semanticRehighlightTimer->start();
869
870
        return;
    }
871

872
873
874
    if (doc->ast()) {
        // got a correctly parsed (or recovered) file.

Christian Kamm's avatar
Christian Kamm committed
875
876
        const SemanticHighlighter::Source source = currentSource(/*force = */ true);
        m_semanticHighlighter->rehighlight(source);
877
    } else {
878
        // show parsing errors
879
880
881
        QList<QTextEdit::ExtraSelection> selections;
        appendExtraSelectionsForMessages(&selections, doc->diagnosticMessages(), document());
        setExtraSelections(CodeWarningsSelection, selections);
882
    }
883
884
}

885
886
887
888
889
890
void QmlJSTextEditor::modificationChanged(bool changed)
{
    if (!changed && m_modelManager)
        m_modelManager->fileChangedOnDisk(file()->fileName());
}

Kai Koehne's avatar
Kai Koehne committed
891
void QmlJSTextEditor::jumpToOutlineElement(int /*index*/)
892
{
893
    QModelIndex index = m_outlineCombo->view()->currentIndex();
894
895
896
897
    AST::SourceLocation location = m_outlineModel->sourceLocation(index);

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

899
900
901
902
    Core::EditorManager *editorManager = Core::EditorManager::instance();
    editorManager->cutForwardNavigationHistory();
    editorManager->addCurrentPositionToNavigationHistory();

903
904
905
906
907
    QTextCursor cursor = textCursor();
    cursor.setPosition(location.offset);
    setTextCursor(cursor);

    setFocus();
908
909
}

910
void QmlJSTextEditor::updateOutlineNow()
911
{
912
    if (!m_semanticInfo.document)
913
914
        return;

915
    if (m_semanticInfo.document->editorRevision() != editorRevision()) {
916
917
        m_updateOutlineTimer->start();
        return;
918
    }
919

920
    m_outlineModel->update(m_semanticInfo);
921
922
923
924

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

925
    updateOutlineIndexNow();
926
927
}

928
void QmlJSTextEditor::updateOutlineIndexNow()
929
{
930
    if (m_updateOutlineTimer->isActive())
Kai Koehne's avatar
Kai Koehne committed
931
        return; // updateOutlineNow will call this function soon anyway
932

933
    if (!m_outlineModel->document())
934
        return;
935

936
    if (m_outlineModel->document()->editorRevision() != editorRevision()) {
937
        m_updateOutlineIndexTimer->start();
938
939
        return;
    }
940

941
942
    m_outlineModelIndex = QModelIndex(); // invalidate
    QModelIndex comboIndex = outlineModelIndex();
943

944
    if (comboIndex.isValid()) {
945
        bool blocked = m_outlineCombo->blockSignals(true);
946

947
        // There is no direct way to select a non-root item
948
949
950
        m_outlineCombo->setRootModelIndex(comboIndex.parent());
        m_outlineCombo->setCurrentIndex(comboIndex.row());
        m_outlineCombo->setRootModelIndex(QModelIndex());
951

952
        m_outlineCombo->blockSignals(blocked);
953
    }
954
955
}

956
957
958
959
960
961
962
963
964
965
966
967
static UiQualifiedId *qualifiedTypeNameId(UiObjectMember *m)
{
    if (UiObjectDefinition *def = cast<UiObjectDefinition *>(m))
        return def->qualifiedTypeNameId;
    else if (UiObjectBinding *binding = cast<UiObjectBinding *>(m))
        return binding->qualifiedTypeNameId;
    return 0;
}

void QmlJSTextEditor::updateCursorPositionNow()
{
    if (m_contextPane && document() && !semanticInfo().document.isNull() &&
968
969
        document()->revision() == semanticInfo().document->editorRevision())
    {
970
971
        Node *oldNode = m_semanticInfo.declaringMemberNoProperties(m_oldCursorPosition);
        Node *newNode = m_semanticInfo.declaringMemberNoProperties(position());
Thomas Hartmann's avatar
Thomas Hartmann committed
972
        if (oldNode != newNode && m_oldCursorPosition != -1)
973
            m_contextPane->apply(editableInterface(), m_semanticInfo.lookupContext(), newNode, false);
974
        if (oldNode != newNode &&
975
            m_contextPane->isAvailable(editableInterface(), m_semanticInfo.lookupContext(), newNode) &&
976
            !m_contextPane->widget()->isVisible()) {
977
978
979
980
981
982
983
984
985
            QList<TextEditor::Internal::RefactorMarker> markers;
            if (UiObjectMember *m = newNode->uiObjectMemberCast()) {
                for (UiQualifiedId *q = qualifiedTypeNameId(m); q; q = q->next) {
                    if (! q->next) {
                        const int end = q->identifierToken.end();
                        TextEditor::Internal::RefactorMarker marker;
                        QTextCursor tc(document());
                        tc.setPosition(end);
                        marker.cursor = tc;
986
                        marker.tooltip = tr("Show Qt Quick ToolBar");
987
988
989
990
991
                        markers.append(marker);
                    }
                }
            }
            setRefactorMarkers(markers);
Thomas Hartmann's avatar
Thomas Hartmann committed
992
        } else if (oldNode != newNode) {
993
994
            QList<TextEditor::Internal::RefactorMarker> markers;
            setRefactorMarkers(markers);
995
996
        }
        m_oldCursorPosition = position();
997
998

        setSelectedElements();
999
1000
1001
    }
}

1002
1003
1004
1005
1006
1007
void QmlJSTextEditor::showTextMarker()
{
    m_oldCursorPosition = -1;
    updateCursorPositionNow();
}

1008
void QmlJSTextEditor::updateUses()
1009
1010
1011
1012
{
    m_updateUsesTimer->start();
}

1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
bool QmlJSTextEditor::updateSelectedElements() const
{
    return m_updateSelectedElements;
}

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

1023
void QmlJSTextEditor::updateUsesNow()
1024
{
1025
    if (document()->revision() != m_semanticInfo.revision()) {
1026
1027
1028
1029
1030
        updateUses();
        return;
    }

    m_updateUsesTimer->stop();
1031

1032
    QList<QTextEdit::ExtraSelection> selections;
1033
    foreach (const AST::SourceLocation &loc, m_semanticInfo.idLocations.value(wordUnderCursor())) {
1034
1035
        if (! loc.isValid())
            continue;
Roberto Raggi's avatar
Roberto Raggi committed
1036

1037
        QTextEdit::ExtraSelection sel;
1038
        sel.format = m_occurrencesFormat;
1039
1040
1041
1042
1043
        sel.cursor = textCursor();
        sel.cursor.setPosition(loc.begin());
        sel.cursor.setPosition(loc.end(), QTextCursor::KeepAnchor);
        selections.append(sel);
    }
1044

1045
    setExtraSelections(CodeSemanticsSelection, selections);
1046
1047
1048
1049
}

class SelectedElement: protected Visitor
{
1050
1051
1052
1053
    unsigned m_cursorPositionStart;
    unsigned m_cursorPositionEnd;
    QList<UiObjectMember *> m_selectedMembers;
    LookupContext::Ptr m_lookupContext;
1054
1055
1056

public:
    SelectedElement()
1057
        : m_cursorPositionStart(0), m_cursorPositionEnd(0) {}
1058

1059
    QList<UiObjectMember *> operator()(LookupContext::Ptr lookupContext, unsigned startPosition, unsigned endPosition)
1060
    {
1061
        m_lookupContext = lookupContext;
1062
1063
1064
        m_cursorPositionStart = startPosition;
        m_cursorPositionEnd = endPosition;
        m_selectedMembers.clear();
1065
        Node::accept(lookupContext->document()->qmlProgram(), this);
1066
        return m_selectedMembers;
1067
1068
1069
    }

protected:
1070

1071
    bool isSelectable(UiObjectMember *member) const
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
    {
        UiQualifiedId *id = 0;
        if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member))
            id = def->qualifiedTypeNameId;
        else if (UiObjectBinding *binding = cast<UiObjectBinding *>(member))
            id = binding->qualifiedTypeNameId;

        if (id) {
            QString name = id->name->asString();
            if (!name.isEmpty() && name.at(0).isUpper()) {
                return true;
            }
        }

        return false;
    }

1089
    inline UiObjectInitializer *initializer(UiObjectMember *member) const
1090
1091
1092
1093
1094
1095
1096
1097
    {
        if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member))
            return def->initializer;
        else if (UiObjectBinding *binding = cast<UiObjectBinding *>(member))
            return binding->initializer;
        return 0;
    }

1098
    inline bool hasVisualPresentation(Node *ast)
1099
    {
1100
        Bind *bind = m_lookupContext->document()->bind();
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
        const Interpreter::ObjectValue *objValue = bind->findQmlObject(ast);
        QStringList prototypes;

        while (objValue) {
            prototypes.append(objValue->className());
            objValue = objValue->prototype(m_lookupContext->context());
        }

        return prototypes.contains(QString("QGraphicsObject"));
    }

1112
    inline bool isIdBinding(UiObjectMember *member) const
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
    {
        if (UiScriptBinding *script = cast<UiScriptBinding *>(member)) {
            if (! script->qualifiedId)
                return false;
            else if (! script->qualifiedId->name)
                return false;
            else if (script->qualifiedId->next)
                return false;

            const QString propertyName = script->qualifiedId->name->asString();

            if (propertyName == QLatin1String("id"))
                return true;
        }

        return false;
    }