summaryrefslogtreecommitdiff
path: root/src/plugins/qmljseditor/qmloutlinemodel.cpp
blob: 2a8049d81d561707300704e26069d3bbec8b0952 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qmloutlinemodel.h"
#include "qmljseditor.h"

#include <qmljs/parser/qmljsastvisitor_p.h>
#include <qmljs/qmljscontext.h>
#include <qmljs/qmljsscopechain.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljs/qmljsrewriter.h>
#include <qmljstools/qmljsrefactoringchanges.h>

#include <utils/qtcassert.h>

#include <coreplugin/icore.h>
#include <QDebug>
#include <QTime>
#include <QMimeData>
#include <typeinfo>

using namespace QmlJS;
using namespace QmlJSEditor::Internal;
using namespace QmlJSTools;

enum {
    debug = false
};

namespace QmlJSEditor {
namespace Internal {

QmlOutlineItem::QmlOutlineItem(QmlOutlineModel *model) :
    m_outlineModel(model)
{
}

QVariant QmlOutlineItem::data(int role) const
{
    if (role == Qt::ToolTipRole) {
        AST::SourceLocation location = m_outlineModel->sourceLocation(index());
        AST::UiQualifiedId *uiQualifiedId = m_outlineModel->idNode(index());
        if (!uiQualifiedId || !location.isValid() || !m_outlineModel->m_semanticInfo.isValid())
            return QVariant();

        QList<AST::Node *> astPath = m_outlineModel->m_semanticInfo.rangePath(location.begin());
        ScopeChain scopeChain = m_outlineModel->m_semanticInfo.scopeChain(astPath);
        const Value *value = scopeChain.evaluate(uiQualifiedId);

        return prettyPrint(value, scopeChain.context());
    }

    if (role == Qt::DecorationRole) {
        return m_outlineModel->icon(index());
    }

    return QStandardItem::data(role);
}

int QmlOutlineItem::type() const
{
    return UserType;
}

void QmlOutlineItem::setItemData(const QMap<int, QVariant> &roles)
{
    QMap<int,QVariant>::const_iterator iter(roles.constBegin());
    while (iter != roles.constEnd()) {
        setData(iter.value(), iter.key());
        iter++;
    }
}

QString QmlOutlineItem::prettyPrint(const Value *value, const ContextPtr &context) const
{
    if (! value)
        return QString();

    if (const ObjectValue *objectValue = value->asObjectValue()) {
        const QString className = objectValue->className();
        if (!className.isEmpty()) {
            return className;
        }
    }

    const QString typeId = context->valueOwner()->typeId(value);
    if (typeId == QLatin1String("undefined")) {
        return QString();
    }

    return typeId;
}

/**
  Returns mapping of every UiObjectMember object to it's direct UiObjectMember parent object.
  */
class ObjectMemberParentVisitor : public AST::Visitor
{
public:
    QHash<AST::UiObjectMember*,AST::UiObjectMember*> operator()(Document::Ptr doc) {
        parent.clear();
        if (doc && doc->ast())
            doc->ast()->accept(this);
        return parent;
    }

private:
    QHash<AST::UiObjectMember*,AST::UiObjectMember*> parent;
    QList<AST::UiObjectMember *> stack;

    bool preVisit(AST::Node *node)
    {
        if (AST::UiObjectMember *objMember = node->uiObjectMemberCast())
            stack.append(objMember);
        return true;
    }

    void postVisit(AST::Node *node)
    {
        if (AST::UiObjectMember *objMember = node->uiObjectMemberCast()) {
            stack.removeLast();
            if (!stack.isEmpty()) {
                parent.insert(objMember, stack.last());
            }
        }
    }
};


class QmlOutlineModelSync : protected AST::Visitor
{
public:
    QmlOutlineModelSync(QmlOutlineModel *model) :
        m_model(model),
        indent(0)
    {
    }

    void operator()(Document::Ptr doc)
    {
        m_nodeToIndex.clear();

        if (debug)
            qDebug() << "QmlOutlineModel ------";
        if (doc && doc->ast())
            doc->ast()->accept(this);
    }

private:
    bool preVisit(AST::Node *node)
    {
        if (!node)
            return false;
        if (debug)
            qDebug() << "QmlOutlineModel -" << QByteArray(indent++, '-').constData() << node << typeid(*node).name();
        return true;
    }

    void postVisit(AST::Node *)
    {
        indent--;
    }

    typedef QPair<QString,QString> ElementType;
    bool visit(AST::UiObjectDefinition *objDef)
    {
        QModelIndex index = m_model->enterObjectDefinition(objDef);
        m_nodeToIndex.insert(objDef, index);
        return true;
    }

    void endVisit(AST::UiObjectDefinition * /*objDef*/)
    {
        m_model->leaveObjectDefiniton();
    }

    bool visit(AST::UiObjectBinding *objBinding)
    {
        QModelIndex index = m_model->enterObjectBinding(objBinding);
        m_nodeToIndex.insert(objBinding, index);
        return true;
    }

    void endVisit(AST::UiObjectBinding * /*objBinding*/)
    {
        m_model->leaveObjectBinding();
    }

    bool visit(AST::UiArrayBinding *arrayBinding)
    {
        QModelIndex index = m_model->enterArrayBinding(arrayBinding);
        m_nodeToIndex.insert(arrayBinding, index);

        return true;
    }

    void endVisit(AST::UiArrayBinding * /*arrayBinding*/)
    {
        m_model->leaveArrayBinding();
    }

    bool visit(AST::UiScriptBinding *scriptBinding)
    {
        QModelIndex index = m_model->enterScriptBinding(scriptBinding);
        m_nodeToIndex.insert(scriptBinding, index);

        return true;
    }

    void endVisit(AST::UiScriptBinding * /*scriptBinding*/)
    {
        m_model->leaveScriptBinding();
    }

    bool visit(AST::UiPublicMember *publicMember)
    {
        QModelIndex index = m_model->enterPublicMember(publicMember);
        m_nodeToIndex.insert(publicMember, index);

        return true;
    }

    void endVisit(AST::UiPublicMember * /*publicMember*/)
    {
        m_model->leavePublicMember();
    }

    bool visit(AST::FunctionDeclaration *functionDeclaration)
    {
        QModelIndex index = m_model->enterFunctionDeclaration(functionDeclaration);
        m_nodeToIndex.insert(functionDeclaration, index);

        return true;
    }

    void endVisit(AST::FunctionDeclaration * /*functionDeclaration*/)
    {
        m_model->leaveFunctionDeclaration();
    }

    bool visit(AST::BinaryExpression *binExp)
    {
        AST::IdentifierExpression *lhsIdent = AST::cast<AST::IdentifierExpression *>(binExp->left);
        AST::ObjectLiteral *rhsObjLit = AST::cast<AST::ObjectLiteral *>(binExp->right);

        if (lhsIdent && rhsObjLit && (lhsIdent->name == "testcase")
            && (binExp->op == QSOperator::Assign)) {
            QModelIndex index = m_model->enterTestCase(rhsObjLit);
            m_nodeToIndex.insert(rhsObjLit, index);

            if (AST::PropertyNameAndValueList *properties = rhsObjLit->properties)
                visitProperties(properties);

            m_model->leaveTestCase();
        }
        return true;
    }

    void visitProperties(AST::PropertyNameAndValueList *properties)
    {
        while (properties) {
            QModelIndex index = m_model->enterTestCaseProperties(properties);
            m_nodeToIndex.insert(properties, index);

            if (AST::ObjectLiteral *objLiteral = AST::cast<AST::ObjectLiteral *>(properties->value))
                visitProperties(objLiteral->properties);

            m_model->leaveTestCaseProperties();
            properties = properties->next;
        }
    }

    QmlOutlineModel *m_model;

    QHash<AST::Node*, QModelIndex> m_nodeToIndex;
    int indent;
};

QmlOutlineModel::QmlOutlineModel(QmlJSTextEditorWidget *editor) :
    QStandardItemModel(editor),
    m_textEditor(editor)
{
    m_icons = Icons::instance();
    const QString resourcePath = Core::ICore::resourcePath();
    Icons::instance()->setIconFilesPath(resourcePath + "/qmlicons");

    // TODO: Maybe add a Copy Action?
    setSupportedDragActions(Qt::MoveAction);
    setItemPrototype(new QmlOutlineItem(this));
}

QStringList QmlOutlineModel::mimeTypes() const
{
    QStringList types;
    types << QLatin1String("application/x-qtcreator-qmloutlinemodel");
    return types;
}


QMimeData *QmlOutlineModel::mimeData(const QModelIndexList &indexes) const
{
    if (indexes.count() <= 0)
        return 0;
    QStringList types = mimeTypes();
    QMimeData *data = new QMimeData();
    QString format = types.at(0);
    QByteArray encoded;
    QDataStream stream(&encoded, QIODevice::WriteOnly);
    stream << indexes.size();

    for (int i = 0; i < indexes.size(); ++i) {
        QModelIndex index = indexes.at(i);

        QList<int> rowPath;
        for (QModelIndex i = index; i.isValid(); i = i.parent()) {
            rowPath.prepend(i.row());
        }

        stream << rowPath;
    }
    data->setData(format, encoded);
    return data;
}

bool QmlOutlineModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex &parent)
{
    if (debug)
        qDebug() << __FUNCTION__ << row << parent;

    // check if the action is supported
    if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
        return false;

    // We cannot reparent outside of the root item
    if (!parent.isValid())
        return false;

    // check if the format is supported
    QStringList types = mimeTypes();
    if (types.isEmpty())
        return false;
    QString format = types.at(0);
    if (!data->hasFormat(format))
        return false;

    // decode and insert
    QByteArray encoded = data->data(format);
    QDataStream stream(&encoded, QIODevice::ReadOnly);
    int indexSize;
    stream >> indexSize;
    QList<QmlOutlineItem*> itemsToMove;
    for (int i = 0; i < indexSize; ++i) {
        QList<int> rowPath;
        stream >> rowPath;

        QModelIndex index;
        foreach (int row, rowPath) {
            index = this->index(row, 0, index);
            if (!index.isValid())
                continue;
        }

        itemsToMove << static_cast<QmlOutlineItem*>(itemFromIndex(index));
    }

    QmlOutlineItem *targetItem = static_cast<QmlOutlineItem*>(itemFromIndex(parent));
    reparentNodes(targetItem, row, itemsToMove);

    // Prevent view from calling removeRow() on it's own
    return false;
}

Qt::ItemFlags QmlOutlineModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return QStandardItemModel::flags(index);

    Qt::ItemFlags flags = Qt::ItemIsSelectable|Qt::ItemIsEnabled;

    // only allow drag&drop if we're in sync
    if (m_semanticInfo.isValid()
            && !m_textEditor->isSemanticInfoOutdated()) {
        if (index.parent().isValid())
            flags |= Qt::ItemIsDragEnabled;
        if (index.data(ItemTypeRole) != NonElementBindingType)
            flags |= Qt::ItemIsDropEnabled;
    }
    return flags;
}


Document::Ptr QmlOutlineModel::document() const
{
    return m_semanticInfo.document;
}

void QmlOutlineModel::update(const SemanticInfo &semanticInfo)
{
    m_semanticInfo = semanticInfo;
    if (! m_semanticInfo.isValid())
        return;

    m_treePos.clear();
    m_treePos.append(0);
    m_currentItem = invisibleRootItem();

    // resetModel() actually gives better average performance
    // then the incremental updates.
    beginResetModel();

    m_typeToIcon.clear();
    m_itemToNode.clear();
    m_itemToIdNode.clear();
    m_itemToIcon.clear();


    QmlOutlineModelSync syncModel(this);
    syncModel(m_semanticInfo.document);

    endResetModel();

    emit updated();
}

QModelIndex QmlOutlineModel::enterObjectDefinition(AST::UiObjectDefinition *objDef)
{
    const QString typeName = asString(objDef->qualifiedTypeNameId);

    QMap<int, QVariant> data;
    AST::UiQualifiedId *idNode = 0;
    QIcon icon;

    data.insert(Qt::DisplayRole, typeName);

    if (typeName.at(0).isUpper()) {
        data.insert(ItemTypeRole, ElementType);
        data.insert(AnnotationRole, getAnnotation(objDef->initializer));
        idNode = objDef->qualifiedTypeNameId;
        if (!m_typeToIcon.contains(typeName)) {
            m_typeToIcon.insert(typeName, getIcon(objDef->qualifiedTypeNameId));
        }
        icon = m_typeToIcon.value(typeName);
    } else {
        // it's a grouped propery like 'anchors'
        data.insert(ItemTypeRole, NonElementBindingType);
        icon = m_icons->scriptBindingIcon();
    }

    QmlOutlineItem *item = enterNode(data, objDef, idNode, icon);

    return item->index();
}

void QmlOutlineModel::leaveObjectDefiniton()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterObjectBinding(AST::UiObjectBinding *objBinding)
{
    QMap<int, QVariant> bindingData;

    bindingData.insert(Qt::DisplayRole, asString(objBinding->qualifiedId));
    bindingData.insert(ItemTypeRole, ElementBindingType);

    QmlOutlineItem *bindingItem = enterNode(bindingData, objBinding, objBinding->qualifiedId, m_icons->scriptBindingIcon());

    const QString typeName = asString(objBinding->qualifiedTypeNameId);
    if (!m_typeToIcon.contains(typeName)) {
        m_typeToIcon.insert(typeName, getIcon(objBinding->qualifiedTypeNameId));
    }

    QMap<int, QVariant> objectData;
    objectData.insert(Qt::DisplayRole, typeName);
    objectData.insert(AnnotationRole, getAnnotation(objBinding->initializer));
    objectData.insert(ItemTypeRole, ElementType);

    enterNode(objectData, objBinding, objBinding->qualifiedTypeNameId, m_typeToIcon.value(typeName));

    return bindingItem->index();
}

void QmlOutlineModel::leaveObjectBinding()
{
    leaveNode();
    leaveNode();
}

QModelIndex QmlOutlineModel::enterArrayBinding(AST::UiArrayBinding *arrayBinding)
{
    QMap<int, QVariant> bindingData;

    bindingData.insert(Qt::DisplayRole, asString(arrayBinding->qualifiedId));
    bindingData.insert(ItemTypeRole, ElementBindingType);

    QmlOutlineItem *item = enterNode(bindingData, arrayBinding, arrayBinding->qualifiedId, m_icons->scriptBindingIcon());

    return item->index();
}

void QmlOutlineModel::leaveArrayBinding()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterScriptBinding(AST::UiScriptBinding *scriptBinding)
{
    QMap<int, QVariant> objectData;

    objectData.insert(Qt::DisplayRole, asString(scriptBinding->qualifiedId));
    objectData.insert(AnnotationRole, getAnnotation(scriptBinding->statement));
    objectData.insert(ItemTypeRole, NonElementBindingType);

    QmlOutlineItem *item = enterNode(objectData, scriptBinding, scriptBinding->qualifiedId, m_icons->scriptBindingIcon());

    return item->index();
}

void QmlOutlineModel::leaveScriptBinding()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterPublicMember(AST::UiPublicMember *publicMember)
{
    QMap<int, QVariant> objectData;

    if (!publicMember->name.isEmpty())
        objectData.insert(Qt::DisplayRole, publicMember->name.toString());
    objectData.insert(AnnotationRole, getAnnotation(publicMember->statement));
    objectData.insert(ItemTypeRole, NonElementBindingType);

    QmlOutlineItem *item = enterNode(objectData, publicMember, 0, m_icons->publicMemberIcon());

    return item->index();
}

void QmlOutlineModel::leavePublicMember()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterFunctionDeclaration(AST::FunctionDeclaration *functionDeclaration)
{
    QMap<int, QVariant> objectData;

    if (!functionDeclaration->name.isEmpty())
        objectData.insert(Qt::DisplayRole, functionDeclaration->name.toString());
    objectData.insert(ItemTypeRole, ElementBindingType);

    QmlOutlineItem *item = enterNode(objectData, functionDeclaration, 0, m_icons->functionDeclarationIcon());

    return item->index();
}

void QmlOutlineModel::leaveFunctionDeclaration()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterTestCase(AST::ObjectLiteral *objectLiteral)
{
    QMap<int, QVariant> objectData;

    objectData.insert(Qt::DisplayRole, "testcase");
    objectData.insert(ItemTypeRole, ElementBindingType);

    QmlOutlineItem *item = enterNode(objectData, objectLiteral, 0, m_icons->objectDefinitionIcon());

    return item->index();
}

void QmlOutlineModel::leaveTestCase()
{
    leaveNode();
}

QModelIndex QmlOutlineModel::enterTestCaseProperties(AST::PropertyNameAndValueList *propertyNameAndValueList)
{
    QMap<int, QVariant> objectData;
    if (AST::IdentifierPropertyName *propertyName = AST::cast<AST::IdentifierPropertyName *>(propertyNameAndValueList->name)) {
        objectData.insert(Qt::DisplayRole, propertyName->id.toString());
        objectData.insert(ItemTypeRole, ElementBindingType);
        QmlOutlineItem *item;
        if (propertyNameAndValueList->value->kind == AST::Node::Kind_FunctionExpression) {
            item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->functionDeclarationIcon());
        } else if (propertyNameAndValueList->value->kind == AST::Node::Kind_ObjectLiteral) {
            item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->objectDefinitionIcon());
        } else {
            item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->scriptBindingIcon());
        }

        return item->index();
    } else {
        return QModelIndex();
    }
}

void QmlOutlineModel::leaveTestCaseProperties()
{
    leaveNode();
}

AST::Node *QmlOutlineModel::nodeForIndex(const QModelIndex &index) const
{
    QTC_ASSERT(index.isValid() && (index.model() == this), return 0);
    if (index.isValid()) {
        QmlOutlineItem *item = static_cast<QmlOutlineItem*>(itemFromIndex(index));
        QTC_ASSERT(item, return 0);
        QTC_ASSERT(m_itemToNode.contains(item), return 0);
        return m_itemToNode.value(item);
    }
    return 0;
}

AST::SourceLocation QmlOutlineModel::sourceLocation(const QModelIndex &index) const
{
    AST::SourceLocation location;
    QTC_ASSERT(index.isValid() && (index.model() == this), return location);
    AST::Node *node = nodeForIndex(index);
    if (node) {
        if (AST::UiObjectMember *member = node->uiObjectMemberCast()) {
            location = getLocation(member);
        } else if (AST::ExpressionNode *expression = node->expressionCast()) {
            location = getLocation(expression);
        } else if (AST::PropertyNameAndValueList *propertyNameAndValueList = AST::cast<AST::PropertyNameAndValueList *>(node)) {
            location = getLocation(propertyNameAndValueList);
        }
    }
    return location;
}

AST::UiQualifiedId *QmlOutlineModel::idNode(const QModelIndex &index) const
{
    QTC_ASSERT(index.isValid() && (index.model() == this), return 0);
    QmlOutlineItem *item = static_cast<QmlOutlineItem*>(itemFromIndex(index));
    return m_itemToIdNode.value(item);
}

QIcon QmlOutlineModel::icon(const QModelIndex &index) const
{
    QTC_ASSERT(index.isValid() && (index.model() == this), return QIcon());
    QmlOutlineItem *item = static_cast<QmlOutlineItem*>(itemFromIndex(index));
    return m_itemToIcon.value(item);
}

QmlOutlineItem *QmlOutlineModel::enterNode(QMap<int, QVariant> data, AST::Node *node, AST::UiQualifiedId *idNode, const QIcon &icon)
{
    int siblingIndex = m_treePos.last();
    QmlOutlineItem *newItem = 0;
    if (siblingIndex == 0) {
        // first child
        if (!m_currentItem->hasChildren()) {
            if (debug)
                qDebug() << "QmlOutlineModel - Adding" << "element to" << m_currentItem->text();

            newItem = new QmlOutlineItem(this);
        } else {
            m_currentItem = m_currentItem->child(0);
        }
    } else {
        // sibling
        if (m_currentItem->rowCount() <= siblingIndex) {
            if (debug)
                qDebug() << "QmlOutlineModel - Adding" << "element to" << m_currentItem->text();

            newItem = new QmlOutlineItem(this);
        } else {
            m_currentItem = m_currentItem->child(siblingIndex);
        }
    }

    QmlOutlineItem *item = newItem ? newItem : static_cast<QmlOutlineItem*>(m_currentItem);
    m_itemToNode.insert(item, node);
    m_itemToIdNode.insert(item, idNode);
    m_itemToIcon.insert(item, icon);

    if (newItem) {
        m_currentItem->appendRow(newItem);
        m_currentItem = newItem;
    }

    setItemData(m_currentItem->index(), data);

    m_treePos.append(0);

    return item;
}

void QmlOutlineModel::leaveNode()
{
    int lastIndex = m_treePos.takeLast();


    if (lastIndex > 0) {
        // element has children
        if (lastIndex < m_currentItem->rowCount()) {
            if (debug)
                qDebug() << "QmlOutlineModel - removeRows from " << m_currentItem->text() << lastIndex << m_currentItem->rowCount() - lastIndex;
            m_currentItem->removeRows(lastIndex, m_currentItem->rowCount() - lastIndex);
        }
        m_currentItem = parentItem();
    } else {
        if (m_currentItem->hasChildren()) {
            if (debug)
                qDebug() << "QmlOutlineModel - removeRows from " << m_currentItem->text() << 0 << m_currentItem->rowCount();
            m_currentItem->removeRows(0, m_currentItem->rowCount());
        }
        m_currentItem = parentItem();
    }


    m_treePos.last()++;
}

void QmlOutlineModel::reparentNodes(QmlOutlineItem *targetItem, int row, QList<QmlOutlineItem*> itemsToMove)
{
    Utils::ChangeSet changeSet;

    AST::UiObjectMember *targetObjectMember = m_itemToNode.value(targetItem)->uiObjectMemberCast();
    if (!targetObjectMember)
        return;

    QList<Utils::ChangeSet::Range> changedRanges;

    for (int i = 0; i < itemsToMove.size(); ++i) {
        QmlOutlineItem *outlineItem = itemsToMove.at(i);
        AST::UiObjectMember *sourceObjectMember = m_itemToNode.value(outlineItem)->uiObjectMemberCast();
        if (!sourceObjectMember)
            return;

        bool insertionOrderSpecified = true;
        AST::UiObjectMember *memberToInsertAfter = 0;
        {
            if (row == -1) {
                insertionOrderSpecified = false;
            } else if (row > 0) {
                QmlOutlineItem *outlineItem = static_cast<QmlOutlineItem*>(targetItem->child(row - 1));
                memberToInsertAfter = m_itemToNode.value(outlineItem)->uiObjectMemberCast();
            }
        }

        Utils::ChangeSet::Range range;
        if (sourceObjectMember)
            moveObjectMember(sourceObjectMember, targetObjectMember, insertionOrderSpecified,
                             memberToInsertAfter, &changeSet, &range);
        changedRanges << range;
    }

    QmlJSRefactoringChanges refactoring(ModelManagerInterface::instance(), m_semanticInfo.snapshot);
    TextEditor::RefactoringFilePtr file = refactoring.file(m_semanticInfo.document->fileName());
    file->setChangeSet(changeSet);
    foreach (const Utils::ChangeSet::Range &range, changedRanges) {
        file->appendIndentRange(range);
    }
    file->apply();
}

void QmlOutlineModel::moveObjectMember(AST::UiObjectMember *toMove,
                                       AST::UiObjectMember *newParent,
                                       bool insertionOrderSpecified,
                                       AST::UiObjectMember *insertAfter,
                                       Utils::ChangeSet *changeSet,
                                       Utils::ChangeSet::Range *addedRange)
{
    Q_ASSERT(toMove);
    Q_ASSERT(newParent);
    Q_ASSERT(changeSet);

    QHash<AST::UiObjectMember*, AST::UiObjectMember*> parentMembers;
    {
        ObjectMemberParentVisitor visitor;
        parentMembers = visitor(m_semanticInfo.document);
    }

    AST::UiObjectMember *oldParent = parentMembers.value(toMove);
    Q_ASSERT(oldParent);

    // make sure that target parent is actually a direct ancestor of target sibling
    if (insertAfter)
        newParent = parentMembers.value(insertAfter);

    const QString documentText = m_semanticInfo.document->source();

    Rewriter rewriter(documentText, changeSet, QStringList());

    if (AST::UiObjectDefinition *objDefinition = AST::cast<AST::UiObjectDefinition*>(newParent)) {
        AST::UiObjectMemberList *listInsertAfter = 0;
        if (insertionOrderSpecified) {
            if (insertAfter) {
                listInsertAfter = objDefinition->initializer->members;
                while (listInsertAfter && (listInsertAfter->member != insertAfter))
                    listInsertAfter = listInsertAfter->next;
            }
        }

        if (AST::UiScriptBinding *moveScriptBinding = AST::cast<AST::UiScriptBinding*>(toMove)) {
            const QString propertyName = asString(moveScriptBinding->qualifiedId);
            QString propertyValue;
            {
                const int offset = moveScriptBinding->statement->firstSourceLocation().begin();
                const int length = moveScriptBinding->statement->lastSourceLocation().end() - offset;
                propertyValue = documentText.mid(offset, length);
            }
            Rewriter::BindingType bindingType = Rewriter::ScriptBinding;

            if (insertionOrderSpecified) {
                *addedRange = rewriter.addBinding(objDefinition->initializer, propertyName, propertyValue, bindingType, listInsertAfter);
            } else {
                *addedRange = rewriter.addBinding(objDefinition->initializer, propertyName, propertyValue, bindingType);
            }
        } else {
            QString strToMove;
            {
                const int offset = toMove->firstSourceLocation().begin();
                const int length = toMove->lastSourceLocation().end() - offset;
                strToMove = documentText.mid(offset, length);
            }

            if (insertionOrderSpecified) {
                *addedRange = rewriter.addObject(objDefinition->initializer, strToMove, listInsertAfter);
            } else {
                *addedRange = rewriter.addObject(objDefinition->initializer, strToMove);
            }
        }
    } else if (AST::UiArrayBinding *arrayBinding = AST::cast<AST::UiArrayBinding*>(newParent)) {
        AST::UiArrayMemberList *listInsertAfter = 0;
        if (insertionOrderSpecified) {
            if (insertAfter) {
                listInsertAfter = arrayBinding->members;
                while (listInsertAfter && (listInsertAfter->member != insertAfter))
                    listInsertAfter = listInsertAfter->next;
            }
        }
        QString strToMove;
        {
            const int offset = toMove->firstSourceLocation().begin();
            const int length = toMove->lastSourceLocation().end() - offset;
            strToMove = documentText.mid(offset, length);
        }

        if (insertionOrderSpecified) {
            *addedRange = rewriter.addObject(arrayBinding, strToMove, listInsertAfter);
        } else {
            *addedRange = rewriter.addObject(arrayBinding, strToMove);
        }
    } else if (AST::cast<AST::UiObjectBinding*>(newParent)) {
        qDebug() << "TODO: Reparent to UiObjectBinding";
        return;
        // target is a property
    } else {
        return;
    }

    rewriter.removeObjectMember(toMove, oldParent);
}

QStandardItem *QmlOutlineModel::parentItem()
{
    QStandardItem *parent = m_currentItem->parent();
    if (!parent)
        parent = invisibleRootItem();
    return parent;
}


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

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

    return text;
}

AST::SourceLocation QmlOutlineModel::getLocation(AST::UiObjectMember *objMember) {
    AST::SourceLocation location;
    location.offset = objMember->firstSourceLocation().offset;
    location.length = objMember->lastSourceLocation().offset
            - objMember->firstSourceLocation().offset
            + objMember->lastSourceLocation().length;
    return location;
}

AST::SourceLocation QmlOutlineModel::getLocation(AST::ExpressionNode *exprNode) {
    AST::SourceLocation location;
    location.offset = exprNode->firstSourceLocation().offset;
    location.length = exprNode->lastSourceLocation().offset
            - exprNode->firstSourceLocation().offset
            + exprNode->lastSourceLocation().length;
    return location;
}

AST::SourceLocation QmlOutlineModel::getLocation(AST::PropertyNameAndValueList *propertyNode) {
    AST::SourceLocation location;
    location.offset = propertyNode->name->propertyNameToken.offset;
    location.length = propertyNode->value->lastSourceLocation().end() - location.offset;

    return location;
}

QIcon QmlOutlineModel::getIcon(AST::UiQualifiedId *qualifiedId) {
    QIcon icon;
    if (qualifiedId) {
        QString name = asString(qualifiedId);
        if (name.contains(QLatin1Char('.')))
            name = name.split(QLatin1Char('.')).last();

        // TODO: get rid of namespace prefixes.
        icon = m_icons->icon("Qt", name);
        if (icon.isNull())
            icon = m_icons->icon("QtWebkit", name);
    }
    return icon;
}

QString QmlOutlineModel::getAnnotation(AST::UiObjectInitializer *objectInitializer) {
    const QHash<QString,QString> bindings = getScriptBindings(objectInitializer);

    if (bindings.contains("id"))
        return bindings.value("id");

    if (bindings.contains("name"))
        return bindings.value("name");

    if (bindings.contains("target"))
        return bindings.value("target");

    return QString();
}

QString QmlOutlineModel::getAnnotation(AST::Statement *statement)
{
    if (AST::ExpressionStatement *expr = AST::cast<AST::ExpressionStatement*>(statement))
        return getAnnotation(expr->expression);
    return QString();
}

QString QmlOutlineModel::getAnnotation(AST::ExpressionNode *expression)
{
    if (!expression)
        return QString();
    QString source = m_semanticInfo.document->source();
    return source.mid(expression->firstSourceLocation().begin(),
                      expression->lastSourceLocation().end() - expression->firstSourceLocation().begin());
}

QHash<QString,QString> QmlOutlineModel::getScriptBindings(AST::UiObjectInitializer *objectInitializer) {
    QHash <QString,QString> scriptBindings;
    for (AST::UiObjectMemberList *it = objectInitializer->members; it; it = it->next) {
        if (AST::UiScriptBinding *binding = AST::cast<AST::UiScriptBinding*>(it->member)) {
            const QString bindingName = asString(binding->qualifiedId);
            scriptBindings.insert(bindingName, getAnnotation(binding->statement));
        }
    }
    return scriptBindings;
}

} // namespace Internal
} // namespace QmlJSEditor