modeltotextmerger.cpp 12.7 KB
Newer Older
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "modelnodepositionrecalculator.h"
#include "modeltotextmerger.h"
#include "qmltextgenerator.h"
#include "rewriteactioncompressor.h"
#include "rewriterview.h"
35

36
#include <qmljs/qmljsdocument.h>
37
38
39
40
41
#include <variantproperty.h>
#include <nodelistproperty.h>
#include <nodeproperty.h>
#include <textmodifier.h>

42
43
#include <QDebug>

44
#define INDENT_DEPTH 4
45
46
47
48
49
50

namespace {
    enum {
        DebugRewriteActions = 0
    };
}
51

52
using namespace QmlJS;
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
using namespace QmlDesigner;
using namespace QmlDesigner::Internal;

ModelToTextMerger::ModelToTextMerger(RewriterView *reWriterView):
        m_rewriterView(reWriterView)
{
}

void ModelToTextMerger::nodeCreated(const ModelNode &/*createdNode*/)
{
    //the rewriter ignores model nodes outside of the hierachy
}

void ModelToTextMerger::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)
{
    if (!isInHierarchy(parentProperty))
        return;

    if (parentProperty.isDefaultProperty()) {
        schedule(new RemoveNodeRewriteAction(removedNode));
    } else if (AbstractView::EmptyPropertiesRemoved == propertyChange) {
        schedule(new RemovePropertyRewriteAction(parentProperty));
    } else if (parentProperty.isNodeListProperty()) {
        schedule(new RemoveNodeRewriteAction(removedNode));
    }
}

void ModelToTextMerger::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
    foreach (const AbstractProperty &property, propertyList) {
        if (isInHierarchy(property) && !property.isDefaultProperty())
            schedule(new RemovePropertyRewriteAction(property));
    }
}

void ModelToTextMerger::propertiesChanged(const QList<AbstractProperty>& propertyList, PropertyChangeFlags propertyChange)
{
    foreach (const AbstractProperty &property, propertyList) {
        if (!isInHierarchy(property))
            continue;

        ModelNode containedModelNode;

        switch (propertyChange) {
        case AbstractView::PropertiesAdded:
            if (property.isNodeProperty())
                containedModelNode = property.toNodeProperty().modelNode();

            schedule(new AddPropertyRewriteAction(property,
                                                  QmlTextGenerator(getPropertyOrder(), INDENT_DEPTH)(property),
                                                  propertyType(property),
                                                  containedModelNode));
            break;

        case AbstractView::NoAdditionalChanges:
            if (property.isNodeProperty())
                containedModelNode = property.toNodeProperty().modelNode();

            schedule(new ChangePropertyRewriteAction(property,
                                                     QmlTextGenerator(getPropertyOrder(), INDENT_DEPTH)(property),
                                                     propertyType(property),
                                                     containedModelNode));
            break;

        case AbstractView::EmptyPropertiesRemoved:
            break;

        default:
            Q_ASSERT(!"Unknown PropertyChangeFlags");
        }
    }
}

void ModelToTextMerger::nodeTypeChanged(const ModelNode &node,const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/)
{
    if (!node.isInHierarchy())
        return;

    // TODO: handle the majorVersion and the minorVersion

    schedule(new ChangeTypeRewriteAction(node));
}

Erik Verbruggen's avatar
Erik Verbruggen committed
136
137
138
139
140
141
142
143
144
145
146
147
void ModelToTextMerger::addImport(const Import &import)
{
    if (!import.isEmpty())
        schedule(new AddImportRewriteAction(import));
}

void ModelToTextMerger::removeImport(const Import &import)
{
    if (!import.isEmpty())
        schedule(new RemoveImportRewriteAction(import));
}

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
void ModelToTextMerger::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
    if (isInHierarchy(oldPropertyParent) && isInHierarchy(newPropertyParent)) { // the node is moved
        schedule(new ReparentNodeRewriteAction(node, newPropertyParent, propertyType(newPropertyParent)));
    } else if (isInHierarchy(oldPropertyParent) && !isInHierarchy(newPropertyParent)) { // the node is removed from hierarchy
        if (oldPropertyParent.isNodeProperty()) {
            // ignore, the subsequent remove property will take care of all
        } else if (oldPropertyParent.isNodeListProperty()) {
            if (!oldPropertyParent.isDefaultProperty() && oldPropertyParent.toNodeListProperty().toModelNodeList().size() == 0) {
                schedule(new RemovePropertyRewriteAction(oldPropertyParent));
            } else {
                schedule(new RemoveNodeRewriteAction(node));
            }
        } else {
            schedule(new RemoveNodeRewriteAction(node));
        }
    } else if (!isInHierarchy(oldPropertyParent) && isInHierarchy(newPropertyParent)) { // the node is inserted into to hierarchy
        switch (propertyChange) {
        case AbstractView::PropertiesAdded:
            schedule(new AddPropertyRewriteAction(newPropertyParent, QmlTextGenerator(getPropertyOrder())(node), propertyType(newPropertyParent), node));
            break;

        case AbstractView::NoAdditionalChanges:
            schedule(new ChangePropertyRewriteAction(newPropertyParent, QmlTextGenerator(getPropertyOrder())(node), propertyType(newPropertyParent), node));
            break;

        case AbstractView::EmptyPropertiesRemoved:
            break;

        default:
            Q_ASSERT(!"Unknown PropertyChange value");
        }
    } else {
        // old is outside of hierarchy, new is outside of hierarchy, so who cares?
    }
}

void ModelToTextMerger::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
{
    if (!node.isInHierarchy())
        return;

    schedule(new ChangeIdRewriteAction(node, oldId, newId));
}

void ModelToTextMerger::nodeSlidAround(const ModelNode &movingNode, const ModelNode &inFrontOfNode)
{
    if (!inFrontOfNode.isValid() || movingNode.parentProperty() == inFrontOfNode.parentProperty())
        schedule(new MoveNodeRewriteAction(movingNode, inFrontOfNode));
    else
        Q_ASSERT(!"Nodes do not belong to the same containing property");
}

RewriterView *ModelToTextMerger::view()
{
    return m_rewriterView;
}

206
void ModelToTextMerger::applyChanges()
207
{
208
    if (m_rewriteActions.isEmpty())
209
        return;
210

211
212
213
214
215
216
    dumpRewriteActions(QLatin1String("Before compression"));
    RewriteActionCompressor compress(getPropertyOrder());
    compress(m_rewriteActions);
    dumpRewriteActions(QLatin1String("After compression"));

    if (m_rewriteActions.isEmpty())
217
        return;
218

219
    Document::Ptr tmpDocument(Document::create(QLatin1String("<ModelToTextMerger>")));
220
    tmpDocument->setSource(m_rewriterView->textModifier()->text());
Erik Verbruggen's avatar
Erik Verbruggen committed
221
    if (!tmpDocument->parseQml()) {
222
223
        qDebug() << "*** Possible problem: QML file wasn't parsed correctly.";
        qDebug() << "*** QML text:" << m_rewriterView->textModifier()->text();
224
225
226
227
228
229
230

        QString errorMessage = QLatin1String("Error while rewriting");
        if (!tmpDocument->diagnosticMessages().isEmpty())
            errorMessage = tmpDocument->diagnosticMessages().first().message;

        m_rewriterView->enterErrorState(errorMessage);
        return;
231
232
233
234
235
236
237
238
    }

    TextModifier *textModifier = m_rewriterView->textModifier();

    try {
        ModelNodePositionRecalculator positionRecalculator(m_rewriterView->positionStorage(), m_rewriterView->positionStorage()->modelNodes());
        positionRecalculator.connectTo(textModifier);

239
        QmlDesigner::QmlRefactoring refactoring(tmpDocument, *textModifier, getPropertyOrder());
240
241
242
243
244
245

        textModifier->deactivateChangeSignals();
        textModifier->startGroup();

        for (int i = 0; i < m_rewriteActions.size(); ++i) {
            RewriteAction* action = m_rewriteActions.at(i);
246
247
248
249
            if (DebugRewriteActions) {
                qDebug() << "Next rewrite action:" << qPrintable(action->info());
            }

250
            ModelNodePositionStorage *positionStore = m_rewriterView->positionStorage();
251
252
253
254
255
256
257
258
259
260
            bool success = action->execute(refactoring, *positionStore);

            if (success) {
                textModifier->flushGroup();
                success = refactoring.reparseDocument();
            }
            // don't merge these two if statements, because the previous then-part changes the value
            // of "success" !
            if (!success) {
                m_rewriterView->enterErrorState(QLatin1String("Error rewriting document"));
261

262
263
264
265
266
                if (true || DebugRewriteActions) {
                    qDebug() << "*** QML source code: ***";
                    qDebug() << qPrintable(textModifier->text());
                    qDebug() << "*** End of QML source code. ***";
                }
267

268
269
                break;
            }
270
        }
271

272
273
274
275
276
277
278
279
        qDeleteAll(m_rewriteActions);
        m_rewriteActions.clear();

        textModifier->commitGroup();

        reindent(positionRecalculator.dirtyAreas());

        textModifier->reactivateChangeSignals();
280
281
282
    } catch (Exception &e) {
        m_rewriterView->enterErrorState(e.description());

283
284
285
        qDeleteAll(m_rewriteActions);
        m_rewriteActions.clear();
        textModifier->commitGroup();
286
287
288
289
        textModifier->reactivateChangeSignals();
    }
}

Marco Bubke's avatar
Marco Bubke committed
290
void ModelToTextMerger::reindent(const QMap<int, int> &/*dirtyAreas*/) const
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
{
//    QList<int> offsets = dirtyAreas.keys();
//    qSort(offsets);
//
//    foreach (const int offset, offsets) {
//        const int length = dirtyAreas[offset];
//        xxxx
//    }
}

void ModelToTextMerger::schedule(RewriteAction *action)
{
    Q_ASSERT(action);

    m_rewriteActions.append(action);
}

308
QmlDesigner::QmlRefactoring::PropertyType ModelToTextMerger::propertyType(const AbstractProperty &property)
309
310
{
    if (property.isBindingProperty())
311
        return QmlDesigner::QmlRefactoring::ObjectBinding;
312
    else if (property.isNodeListProperty())
313
        return QmlDesigner::QmlRefactoring::ArrayBinding;
314
    else if (property.isNodeProperty())
315
        return QmlDesigner::QmlRefactoring::ObjectBinding;
316
    else if (property.isVariantProperty())
317
        return QmlDesigner::QmlRefactoring::ScriptBinding;
318
319

    Q_ASSERT(!"cannot convert property type");
320
    return (QmlDesigner::QmlRefactoring::PropertyType) -1;
321
322
323
324
325
326
327
328
329
}

QStringList ModelToTextMerger::m_propertyOrder;

QStringList ModelToTextMerger::getPropertyOrder()
{
    if (m_propertyOrder.isEmpty()) {
        m_propertyOrder
                << QLatin1String("id")
330
331
                << QLatin1String("name")
                << QLatin1String("target")
332
                << QLatin1String("property")
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
                << QLatin1String("x")
                << QLatin1String("y")
                << QLatin1String("width")
                << QLatin1String("height")
                << QLatin1String("position")
                << QLatin1String("color")
                << QLatin1String("radius")
                << QLatin1String("text")
                << QString::null
                << QLatin1String("states")
                << QLatin1String("transitions")
                ;
    }

    return m_propertyOrder;
}

bool ModelToTextMerger::isInHierarchy(const AbstractProperty &property) {
    return property.isValid() && property.parentModelNode().isInHierarchy();
}

void ModelToTextMerger::dumpRewriteActions(const QString &msg)
{
356
357
    if (DebugRewriteActions) {
        qDebug() << "---->" << qPrintable(msg);
358

359
360
361
        foreach (RewriteAction *action, m_rewriteActions) {
            qDebug() << "-----" << qPrintable(action->info());
        }
362

363
364
        qDebug() << "<----" << qPrintable(msg);
    }
365
}