rewriterview.cpp 14.6 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
35
/**************************************************************************
**
** 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 <filemanager/astobjecttextextractor.h>
#include <filemanager/objectlengthcalculator.h>
#include <filemanager/firstdefinitionfinder.h>
#include <customnotifications.h>

#include "rewriterview.h"
36
#include "rewritingexception.h"
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "textmodifier.h"
#include "texttomodelmerger.h"
#include "modelnodepositionstorage.h"
#include "modeltotextmerger.h"
#include "nodelistproperty.h"
#include "nodeproperty.h"
#include "invalidmodelnodeexception.h"

using namespace QmlDesigner::Internal;

namespace QmlDesigner {

RewriterView::Error::Error():
        m_type(NoError),
        m_line(-1),
        m_column(-1)
{
}

56
RewriterView::Error::Error(Exception *exception):
57
        m_type(InternalError),
58
        m_line(exception->line()),
59
        m_column(-1),
60
61
        m_description(exception->description()),
        m_url(exception->file())
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
{
}

RewriterView::Error::Error(const QmlError &qmlError):
        m_type(ParseError),
        m_line(qmlError.line()),
        m_column(qmlError.column()),
        m_description(qmlError.description()),
        m_url(qmlError.url())
{
}

QString RewriterView::Error::toString() const
{
    QString str;

78
79
80
    if (m_type == ParseError)
        str += tr("Error parsing");
    else if (m_type == InternalError)
81
        str += tr("Internal error");
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    if (url().isValid()) {
        if (!str.isEmpty())
            str += QLatin1Char(' ');

        str += tr("\"%1\"").arg(url().toString());
    }

    if (line() != -1) {
        if (!str.isEmpty())
            str += QLatin1Char(' ');
        str += tr("line %1").arg(line());
    }

    if(column() != -1) {
        if (!str.isEmpty())
            str += QLatin1Char(' ');

        str += tr("column %1").arg(column());
    }

    if (!str.isEmpty())
        QLatin1String(": ");
105
106
107
108
109
110
111
112
113
114
115
116
117
    str += description();

    return str;
}

RewriterView::RewriterView(DifferenceHandling differenceHandling, QObject *parent):
        AbstractView(parent),
        m_differenceHandling(differenceHandling),
        m_modificationGroupActive(false),
        m_positionStorage(new ModelNodePositionStorage),
        m_modelToTextMerger(new Internal::ModelToTextMerger(this)),
        m_textToModelMerger(new Internal::TextToModelMerger(this)),
        m_textModifier(0),
118
        transactionLevel(0)
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
{
}

RewriterView::~RewriterView()
{
    delete m_positionStorage;
}

Internal::ModelToTextMerger *RewriterView::modelToTextMerger() const
{
    return m_modelToTextMerger.data();
}

Internal::TextToModelMerger *RewriterView::textToModelMerger() const
{
    return m_textToModelMerger.data();
}

void RewriterView::modelAttached(Model *model)
{
    AbstractView::modelAttached(model);

    ModelAmender differenceHandler(m_textToModelMerger.data());
142
143
144
145
    const QString qmlSource = m_textModifier->text();
    if (m_textToModelMerger->load(qmlSource.toUtf8(), differenceHandler)) {
        lastCorrectQmlSource = qmlSource;
    }
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
}

void RewriterView::modelAboutToBeDetached(Model * /*model*/)
{
    m_positionStorage->clear();
}

void RewriterView::nodeCreated(const ModelNode &createdNode)
{
    Q_ASSERT(textModifier());
    m_positionStorage->setNodeOffset(createdNode, ModelNodePositionStorage::INVALID_LOCATION);
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->nodeCreated(createdNode);

    if (!isModificationGroupActive())
163
        applyChanges();
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
}

void RewriterView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/)
{
}

void RewriterView::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->nodeRemoved(removedNode, parentProperty, propertyChange);

    if (!isModificationGroupActive())
179
        applyChanges();
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
}

void RewriterView::propertiesAdded(const ModelNode &/*node*/, const QList<AbstractProperty>& /*propertyList*/)
{
    Q_ASSERT(0);
}

void RewriterView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;


    foreach (const AbstractProperty &property, propertyList) {
        if (property.isDefaultProperty() && property.isNodeListProperty()) {
            m_removeDefaultPropertyTransaction = beginRewriterTransaction();

            foreach (const ModelNode &node, property.toNodeListProperty().toModelNodeList()) {
                modelToTextMerger()->nodeRemoved(node, property.toNodeAbstractProperty(), AbstractView::NoAdditionalChanges);
            }
        }
    }
}

void RewriterView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->propertiesRemoved(propertyList);

    if (m_removeDefaultPropertyTransaction.isValid())
        m_removeDefaultPropertyTransaction.commit();

    if (!isModificationGroupActive())
217
        applyChanges();
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
}

void RewriterView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    QList<AbstractProperty> usefulPropertyList;
    foreach (const VariantProperty &property, propertyList)
        usefulPropertyList.append(property);

    modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);

    if (!isModificationGroupActive())
233
        applyChanges();
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
}

void RewriterView::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    QList<AbstractProperty> usefulPropertyList;
    foreach (const BindingProperty &property, propertyList)
        usefulPropertyList.append(property);

    modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);

    if (!isModificationGroupActive())
249
        applyChanges();
250
251
252
253
254
255
256
257
258
259
260
}

void RewriterView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);

    if (!isModificationGroupActive())
261
        applyChanges();
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
void RewriterView::importAdded(const Import &import)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->addImport(import);

    if (!isModificationGroupActive())
        applyChanges();
}

void RewriterView::importRemoved(const Import &import)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->removeImport(import);

    if (!isModificationGroupActive())
        applyChanges();
}

288
289
290
291
292
293
294
295
296
297
298
299
300
void RewriterView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/)
{
}

void RewriterView::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
{
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    modelToTextMerger()->nodeIdChanged(node, newId, oldId);

    if (!isModificationGroupActive())
301
        applyChanges();
302
303
}

304
305
void RewriterView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int /*oldIndex*/)
{
306
307
308
309
310
    Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

    const QList<ModelNode> nodes = listProperty.toModelNodeList();
311

312
    ModelNode trailingNode;
313
    int newIndex = nodes.indexOf(movedNode);
314
315
    if (newIndex + 1 < nodes.size())
        trailingNode = nodes.at(newIndex + 1);
316
    modelToTextMerger()->nodeSlidAround(movedNode, trailingNode);
317
318

    if (!isModificationGroupActive())
319
        applyChanges();
320
321
}

322
void RewriterView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
323
324
325
326
327
{
     Q_ASSERT(textModifier());
    if (textToModelMerger()->isActive())
        return;

328
    modelToTextMerger()->nodeTypeChanged(rootModelNode(), type, majorVersion, minorVersion);
329
330

    if (!isModificationGroupActive())
331
        applyChanges();
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
}

void RewriterView::customNotification(const AbstractView * /*view*/, const QString &identifier, const QList<ModelNode> & /* nodeList */, const QList<QVariant> & /*data */)
{
    if (identifier == ("__start rewriter transaction__")) {
        transactionLevel++;
        setModificationGroupActive(true);
    }
    else if (identifier == ("__end rewriter transaction__")) {
        transactionLevel--;
        Q_ASSERT(transactionLevel >= 0);

    }
    if (transactionLevel == 0)
    {
        setModificationGroupActive(false);
        applyModificationGroupChanges();
    }
}

void RewriterView::selectedNodesChanged(const QList<ModelNode> & /* selectedNodeList, */, const QList<ModelNode> & /*lastSelectedNodeList */)
{
}

bool RewriterView::isModificationGroupActive() const
{
    return m_modificationGroupActive;
}

void RewriterView::setModificationGroupActive(bool active)
{
    m_modificationGroupActive = active;
}

TextModifier *RewriterView::textModifier() const
{
    return m_textModifier;
}

void RewriterView::setTextModifier(TextModifier *textModifier)
{
    if (m_textModifier)
        disconnect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));

    m_textModifier = textModifier;

    if (m_textModifier)
        connect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));
}

void RewriterView::applyModificationGroupChanges()
{
    Q_ASSERT(transactionLevel == 0);
385
    applyChanges();
386
387
}

388
389
void RewriterView::applyChanges()
{
390
    if (inErrorState()) {
391
        qDebug() << "RewriterView::applyChanges() got called while in error state. Will do a quick-exit now.";
392
        throw RewritingException(__LINE__, __FUNCTION__, __FILE__, "RewriterView::applyChanges() already in error state");
393
394
395
    }

    try {
396
        modelToTextMerger()->applyChanges();
397
    } catch (Exception &e) {
398
399
400
401
402
        enterErrorState(e.description());
    }

    if (inErrorState()) {
        throw RewritingException(__LINE__, __FUNCTION__, __FILE__, m_rewritingErrorMessage);
403
404
405
    }
}

406
407
408
409
410
411
412
413
414
415
416
QList<RewriterView::Error> RewriterView::errors() const
{
    return m_errors;
}

void RewriterView::clearErrors()
{
    m_errors.clear();
    emit errorsChanged(m_errors);
}

417
void RewriterView::setErrors(const QList<RewriterView::Error> &errors)
418
{
419
    m_errors = errors;
420
421
422
423
424
425
426
427
428
    emit errorsChanged(m_errors);
}

void RewriterView::addError(const RewriterView::Error &error)
{
    m_errors.append(error);
    emit errorsChanged(m_errors);
}

429
430
431
432
433
void RewriterView::enterErrorState(const QString &errorMessage)
{
    m_rewritingErrorMessage = errorMessage;
}

434
435
void RewriterView::resetToLastCorrectQml()
{
436
    m_textModifier->textDocument()->undo();
437
    m_textModifier->textDocument()->clearUndoRedoStacks(QTextDocument::RedoStack);
438
    ModelAmender differenceHandler(m_textToModelMerger.data());
439
440
//    m_textToModelMerger->load(lastCorrectQmlSource.toUtf8(), differenceHandler);
    m_textToModelMerger->load(m_textModifier->text().toUtf8(), differenceHandler);
441
442

    leaveErrorState();
443
444
}

445
446
QMap<ModelNode, QString> RewriterView::extractText(const QList<ModelNode> &nodes) const
{
447
    QmlDesigner::ASTObjectTextExtractor extract(m_textModifier->text());
448
449
450
451
452
453
    QMap<ModelNode, QString> result;

    foreach (const ModelNode &node, nodes) {
        const int nodeLocation = m_positionStorage->nodeOffset(node);

        if (nodeLocation == ModelNodePositionStorage::INVALID_LOCATION)
454
            result.insert(node, QString());
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
        else
            result.insert(node, extract(nodeLocation));
    }

    return result;
}

int RewriterView::nodeOffset(const ModelNode &node) const
{
    return m_positionStorage->nodeOffset(node);
}

int RewriterView::nodeLength(const ModelNode &node) const
{
    ObjectLengthCalculator objectLengthCalculator(m_textModifier->text());
    return objectLengthCalculator(nodeOffset(node));
}

int RewriterView::firstDefinitionInsideOffset(const ModelNode &node) const
{
    FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());
    return firstDefinitionFinder(nodeOffset(node));
}

int RewriterView::firstDefinitionInsideLength(const ModelNode &node) const
{
    FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());
    int offset =  firstDefinitionFinder(nodeOffset(node));
    ObjectLengthCalculator objectLengthCalculator(m_textModifier->text());
    return objectLengthCalculator(offset);
}

void RewriterView::qmlTextChanged()
{
489
490
491
    if (inErrorState())
        return;

492
493
494
495
496
497
498
499
    if (m_textToModelMerger && m_textModifier) {
        const QString newQmlText = m_textModifier->text();

//        qDebug() << "qmlTextChanged:" << newQmlText;

        switch (m_differenceHandling) {
            case Validate: {
                ModelValidator differenceHandler(m_textToModelMerger.data());
500
501
502
                if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler)) {
                    lastCorrectQmlSource = newQmlText;
                }
503
504
505
506
507
508
509
                break;
            }

            case Amend:
            default: {
                emitCustomNotification(StartRewriterAmend);
                ModelAmender differenceHandler(m_textToModelMerger.data());
510
511
512
                if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler)) {
                    lastCorrectQmlSource = newQmlText;
                }
513
514
515
516
517
518
519
520
                emitCustomNotification(EndRewriterAmend);
                break;
            }
        }
    }
}

} //QmlDesigner