nodeinstanceserver.cpp 42.4 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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

34
35
36
37
38
39
40
41
42
43
#include "nodeinstanceserver.h"

#include <QGraphicsItem>
#include <private/qgraphicsitem_p.h>
#include <private/qgraphicsscene_p.h>
#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QFileSystemWatcher>
#include <QUrl>
#include <QSet>
44
#include <QDir>
45
46
#include <QVariant>
#include <QMetaType>
47
#include <QDeclarativeComponent>
48
49
#include <QDeclarativeContext>
#include <private/qlistmodelinterface_p.h>
50
51
#include <QAbstractAnimation>
#include <private/qabstractanimation_p.h>
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include "servernodeinstance.h"
#include "childrenchangeeventfilter.h"
#include "propertyabstractcontainer.h"
#include "propertybindingcontainer.h"
#include "propertyvaluecontainer.h"
#include "instancecontainer.h"
#include "createinstancescommand.h"
#include "changefileurlcommand.h"
#include "clearscenecommand.h"
#include "reparentinstancescommand.h"
#include "changevaluescommand.h"
#include "changebindingscommand.h"
#include "changeidscommand.h"
#include "removeinstancescommand.h"
#include "nodeinstanceclientinterface.h"
#include "removepropertiescommand.h"
#include "valueschangedcommand.h"
#include "informationchangedcommand.h"
#include "pixmapchangedcommand.h"
#include "commondefines.h"
#include "childrenchangeeventfilter.h"
#include "changestatecommand.h"
75
#include "addimportcommand.h"
76
#include "childrenchangedcommand.h"
77
78
#include "completecomponentcommand.h"
#include "componentcompletedcommand.h"
79
#include "createscenecommand.h"
80

81
82
#include "dummycontextobject.h"

83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <stdio.h>


namespace QmlDesigner {

NodeInstanceServer::NodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) :
    NodeInstanceServerInterface(),
    m_childrenChangeEventFilter(new Internal::ChildrenChangeEventFilter(this)),
    m_nodeInstanceClient(nodeInstanceClient),
93
    m_timer(0),
94
95
    m_renderTimerInterval(16),
    m_slowRenderTimer(false),
96
    m_slowRenderTimerInterval(200)
97
{
98
99
    qmlRegisterType<DummyContextObject>("QmlDesigner", 1, 0, "DummyContextObject");

100
    m_importList.append("import Qt 4.7\n");
101
102
103
104
105
106
107
108
    connect(m_childrenChangeEventFilter.data(), SIGNAL(childrenChanged(QObject*)), this, SLOT(emitParentChanged(QObject*)));
}

NodeInstanceServer::~NodeInstanceServer()
{
    delete m_declarativeView.data();
}

109
QList<ServerNodeInstance>  NodeInstanceServer::createInstances(const QVector<InstanceContainer> &containerVector)
110
111
112
{
    Q_ASSERT(m_declarativeView);
    QList<ServerNodeInstance> instanceList;
113
    foreach(const InstanceContainer &instanceContainer, containerVector) {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        ServerNodeInstance instance = ServerNodeInstance::create(this, instanceContainer);
        insertInstanceRelationship(instance);
        instanceList.append(instance);
        instance.internalObject()->installEventFilter(childrenChangeEventFilter());
        if (instanceContainer.instanceId() == 0) {
            m_rootNodeInstance = instance;
            QGraphicsObject *rootGraphicsObject = qobject_cast<QGraphicsObject*>(instance.internalObject());
            if (rootGraphicsObject) {
                m_declarativeView->scene()->addItem(rootGraphicsObject);
                m_declarativeView->setSceneRect(rootGraphicsObject->boundingRect());
            }

        }
    }

129
130
131
132
133
134
    return instanceList;
}

void NodeInstanceServer::createInstances(const CreateInstancesCommand &command)
{
    createInstances(command.instances());
135
    refreshBindings();
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
    startRenderTimer();
}

ServerNodeInstance NodeInstanceServer::instanceForId(qint32 id) const
{
    if (id < 0)
        return ServerNodeInstance();

    Q_ASSERT(m_idInstanceHash.contains(id));
    return m_idInstanceHash.value(id);
}

bool NodeInstanceServer::hasInstanceForId(qint32 id) const
{
    if (id < 0)
        return false;

    return m_idInstanceHash.contains(id);
}

ServerNodeInstance NodeInstanceServer::instanceForObject(QObject *object) const
{
    Q_ASSERT(m_objectInstanceHash.contains(object));
    return m_objectInstanceHash.value(object);
}

bool NodeInstanceServer::hasInstanceForObject(QObject *object) const
{
    if (object == 0)
        return false;

    return m_objectInstanceHash.contains(object);
}

170
171
172
173
174
175
176
177
178
179
void NodeInstanceServer::setRenderTimerInterval(int timerInterval)
{
    m_renderTimerInterval = timerInterval;
}

void NodeInstanceServer::setSlowRenderTimerInterval(int timerInterval)
{
    m_slowRenderTimerInterval = timerInterval;
}

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
void NodeInstanceServer::setTimerId(int timerId)
{
    m_timer = timerId;
}

int NodeInstanceServer::timerId() const
{
    return m_timer;
}

int NodeInstanceServer::renderTimerInterval() const
{
    return m_renderTimerInterval;
}

195
196
void NodeInstanceServer::startRenderTimer()
{
197
198
199
    if (m_slowRenderTimer)
        stopRenderTimer();

200
    if (m_timer == 0)
201
        m_timer = startTimer(m_renderTimerInterval);
202
203
204
205
206
207
208
209
210

    m_slowRenderTimer = false;
}

void NodeInstanceServer::slowDownRenderTimer()
{
    if (!m_slowRenderTimer)
        stopRenderTimer();

211
212
213
214
215
    if (m_timer != 0) {
        killTimer(m_timer);
        m_timer = 0;
    }

216
    if (m_timer == 0)
217
        m_timer = startTimer(m_slowRenderTimerInterval);
218
219

    m_slowRenderTimer = true;
220
221
222
223
224
225
226
227
228
229
}

void NodeInstanceServer::stopRenderTimer()
{
    if (m_timer) {
        killTimer(m_timer);
        m_timer = 0;
    }
}

230
void NodeInstanceServer::createScene(const CreateSceneCommand &command)
231
{
232
233
    initializeDeclarativeView();
    QList<ServerNodeInstance> instanceList = setupScene(command);
234

235
236
    refreshBindings();

237
    nodeInstanceClient()->informationChanged(createAllInformationChangedCommand(instanceList, true));
238
    nodeInstanceClient()->valuesChanged(createValuesChangedCommand(instanceList));
239
240
241
242
    sendChildrenChangedCommand(instanceList);
    nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList));
    nodeInstanceClient()->componentCompleted(createComponentCompletedCommand(instanceList));

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    startRenderTimer();
}

void NodeInstanceServer::clearScene(const ClearSceneCommand &/*command*/)
{
    stopRenderTimer();

    removeAllInstanceRelationships();
    m_fileSystemWatcherHash.clear();
    m_rootNodeInstance.makeInvalid();
    m_changedPropertyList.clear();
    m_fileUrl.clear();

    delete m_declarativeView.data();
}

void NodeInstanceServer::removeInstances(const RemoveInstancesCommand &command)
{
261
262
263
    if (activeStateInstance().isValid())
        activeStateInstance().deactivateState();

264
265
266
267
    foreach(qint32 instanceId, command.instanceIds()) {
        removeInstanceRelationsip(instanceId);
    }

268
269
270
    if (activeStateInstance().isValid())
        activeStateInstance().activateState();

271
272

    refreshBindings();
273
274
275
276
277
    startRenderTimer();
}

void NodeInstanceServer::removeProperties(const RemovePropertiesCommand &command)
{
278
279
280
    bool hasDynamicProperties = false;
    foreach(const PropertyAbstractContainer &container, command.properties()) {
        hasDynamicProperties |= container.isDynamic();
281
        resetInstanceProperty(container);
282
283
284
285
    }

    if (hasDynamicProperties)
        refreshBindings();
286
287
288
289

    startRenderTimer();
}

290
void NodeInstanceServer::reparentInstances(const QVector<ReparentContainer> &containerVector)
291
{
292
    foreach(const ReparentContainer &container, containerVector) {
293
294
295
296
297
        ServerNodeInstance instance = instanceForId(container.instanceId());
        if (instance.isValid()) {
            instance.reparent(instanceForId(container.oldParentInstanceId()), container.oldParentProperty(), instanceForId(container.newParentInstanceId()), container.newParentProperty());
        }
    }
298

299
300
301
302
303
}

void NodeInstanceServer::reparentInstances(const ReparentInstancesCommand &command)
{
    reparentInstances(command.reparentInstances());
304
    refreshBindings();
305
306
307
308
309
310
    startRenderTimer();
}

void NodeInstanceServer::changeState(const ChangeStateCommand &command)
{
    if (hasInstanceForId(command.stateInstanceId())) {
311
312
        if (activeStateInstance().isValid())
            activeStateInstance().deactivateState();
313
314
315
316
317
318
319
320
321
322
        ServerNodeInstance instance = instanceForId(command.stateInstanceId());
        instance.activateState();
    } else {
        if (activeStateInstance().isValid())
            activeStateInstance().deactivateState();
    }

    startRenderTimer();
}

323
324
void NodeInstanceServer::completeComponent(const CompleteComponentCommand &command)
{
325
326
    QList<ServerNodeInstance> instanceList;

327
328
329
330
    foreach(qint32 instanceId, command.instances()) {
        if (hasInstanceForId(instanceId)) {
            ServerNodeInstance instance = instanceForId(instanceId);
            instance.doComponentComplete();
331
            instanceList.append(instance);
332
333
        }
    }
334

335
    m_completedComponentList.append(instanceList);
336
    refreshBindings();
337

338
339
340
    nodeInstanceClient()->valuesChanged(createValuesChangedCommand(instanceList));
    nodeInstanceClient()->informationChanged(createAllInformationChangedCommand(instanceList, true));
    nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList));
341
342

    startRenderTimer();
343
344
}

345
void NodeInstanceServer::addImports(const QVector<AddImportContainer> &containerVector)
346
{
347
348
349
350
351
352
353
    foreach (const AddImportContainer &container, containerVector) {
        QString importStatement = QString("import ");

        if (!container.fileName().isEmpty())
            importStatement += '"' + container.fileName() + '"';
        else if (!container.url().isEmpty())
            importStatement += container.url().toString();
354

355
        if (!container.version().isEmpty())
356
            importStatement += ' ' + container.version();
357

358
359
        if (!container.alias().isEmpty())
            importStatement += " as " + container.alias();
360

361
        importStatement.append('\n');
362

363
364
        if (!m_importList.contains(importStatement))
            m_importList.append(importStatement);
365

366
367
368
369
370
        foreach(const QString &importPath, container.importPaths()) { // this is simply ugly
            engine()->addImportPath(importPath);
            engine()->addPluginPath(importPath);
        }
    }
Marco Bubke's avatar
Marco Bubke committed
371

372
373
374
375
    delete m_importComponent.data();
    delete m_importComponentObject.data();

    m_importComponent = new QDeclarativeComponent(engine(), 0);
376
377
    QString componentString;
    foreach(const QString &importStatement, m_importList)
378
        componentString += QString("%1").arg(importStatement);
379

380
    componentString += QString("Item {}\n");
381

382
383
    m_importComponent->setData(componentString.toUtf8(), fileUrl());
    m_importComponentObject = m_importComponent->create();
384

385
386
    if (!m_importComponent->errorString().isEmpty())
        qDebug() << "QmlDesigner.NodeInstances: import wrong: " << m_importComponent->errorString();
387
388
}

389
390
391
392
393
void NodeInstanceServer::addImport(const AddImportCommand &command)
{
    addImports(QVector<AddImportContainer>() << command.import());
}

394
395
396
397
398
399
400
void NodeInstanceServer::changeFileUrl(const ChangeFileUrlCommand &command)
{
    m_fileUrl = command.fileUrl();

    if (engine())
        engine()->setBaseUrl(m_fileUrl);

401
    refreshBindings();
402
403
404
405
406
    startRenderTimer();
}

void NodeInstanceServer::changePropertyValues(const ChangeValuesCommand &command)
{
407
408
409
410
411
    bool hasDynamicProperties = false;
    foreach(const PropertyValueContainer &container, command.valueChanges()) {
        hasDynamicProperties |= container.isDynamic();
        setInstancePropertyVariant(container);
    }
412

413
414
415
416
    if (hasDynamicProperties)
        refreshBindings();

    startRenderTimer();
417
418
419
420
421
}


void NodeInstanceServer::changePropertyBindings(const ChangeBindingsCommand &command)
{
422
423
424
    bool hasDynamicProperties = false;
    foreach(const PropertyBindingContainer &container, command.bindingChanges()) {
        hasDynamicProperties |= container.isDynamic();
425
        setInstancePropertyBinding(container);
426
427
428
429
    }

    if (hasDynamicProperties)
        refreshBindings();
430
431
432
433
434
435
436
437
438
439
440

    startRenderTimer();
}

void NodeInstanceServer::changeIds(const ChangeIdsCommand &command)
{
    foreach(const IdContainer &container, command.ids()) {
        if (hasInstanceForId(container.instanceId()))
            instanceForId(container.instanceId()).setId(container.id());
    }

441
    refreshBindings();
442
443
444
445
446
447
448
449
450
451
452
    startRenderTimer();
}

QDeclarativeEngine *NodeInstanceServer::engine() const
{
    if (m_declarativeView)
        return m_declarativeView->engine();

    return 0;
}

453
454
QDeclarativeContext *NodeInstanceServer::context() const
{
455
456
457
458
459
460
461
462
463
464
    if (m_importComponentObject) {
        QDeclarativeContext *importComponentContext = QDeclarativeEngine::contextForObject(m_importComponentObject.data());
        if (importComponentContext) // this should be the default
            return importComponentContext;
    }

    if (engine())
        return engine()->rootContext();

    return 0;
465
466
}

467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
QDeclarativeView *NodeInstanceServer::delcarativeView() const
{
    return m_declarativeView.data();
}

const QVector<NodeInstanceServer::InstancePropertyPair> NodeInstanceServer::changedPropertyList() const
{
    return m_changedPropertyList;
}

void NodeInstanceServer::clearChangedPropertyList()
{
    m_changedPropertyList.clear();
}

482
483
484
485
486
487
void NodeInstanceServer::refreshBindings()
{
    static int counter = 0;
    engine()->rootContext()->setContextProperty(QString("__%1").arg(counter++), 0); // refreshing bindings
}

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
void NodeInstanceServer::removeAllInstanceRelationships()
{
    // prevent destroyed() signals calling back

    foreach (ServerNodeInstance instance, m_objectInstanceHash.values()) {
        if (instance.isValid())
            instance.setId(QString());
    }

    //first  the root object
    if (rootNodeInstance().internalObject())
        rootNodeInstance().internalObject()->disconnect();

    rootNodeInstance().makeInvalid();


    foreach (ServerNodeInstance instance, m_objectInstanceHash.values()) {
        if (instance.internalObject())
            instance.internalObject()->disconnect();
        instance.makeInvalid();
    }

    m_idInstanceHash.clear();
    m_objectInstanceHash.clear();
}

514
515
516
517
518
519
520
521
522
QFileSystemWatcher *NodeInstanceServer::dummydataFileSystemWatcher()
{
    if (m_dummdataFileSystemWatcher.isNull()) {
        m_dummdataFileSystemWatcher = new QFileSystemWatcher(this);
        connect(m_dummdataFileSystemWatcher.data(), SIGNAL(fileChanged(QString)), this, SLOT(refreshDummyData(QString)));
    }

    return m_dummdataFileSystemWatcher.data();
}
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

QFileSystemWatcher *NodeInstanceServer::fileSystemWatcher()
{
    if (m_fileSystemWatcher.isNull()) {
        m_fileSystemWatcher = new QFileSystemWatcher(this);
        connect(m_fileSystemWatcher.data(), SIGNAL(fileChanged(QString)), this, SLOT(refreshLocalFileProperty(QString)));
    }

    return m_fileSystemWatcher.data();
}

Internal::ChildrenChangeEventFilter *NodeInstanceServer::childrenChangeEventFilter() const
{
    return m_childrenChangeEventFilter.data();
}

void NodeInstanceServer::addFilePropertyToFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path)
{
541
542
543
544
    if (!m_fileSystemWatcherHash.contains(path)) {
        m_fileSystemWatcherHash.insert(path, ObjectPropertyPair(object, propertyName));
        fileSystemWatcher()->addPath(path);
    }
545
546
547
548
}

void NodeInstanceServer::removeFilePropertyFromFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path)
{
549
550
551
552
    if (m_fileSystemWatcherHash.contains(path)) {
        fileSystemWatcher()->removePath(path);
        m_fileSystemWatcherHash.remove(path, ObjectPropertyPair(object, propertyName));
    }
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
}

void NodeInstanceServer::refreshLocalFileProperty(const QString &path)
{
    if (m_fileSystemWatcherHash.contains(path)) {
        QList<ObjectPropertyPair> objectPropertyPairList = m_fileSystemWatcherHash.values();
        foreach(const ObjectPropertyPair &objectPropertyPair, objectPropertyPairList) {
            QObject *object = objectPropertyPair.first.data();
            QString propertyName = objectPropertyPair.second;

            if (hasInstanceForObject(object)) {
                instanceForObject(object).refreshProperty(propertyName);
            }
        }
    }
}

570
571
572
void NodeInstanceServer::refreshDummyData(const QString &path)
{
    engine()->clearComponentCache();
573
574
575
576
577
578
    QFileInfo filePath(path);
    if (filePath.completeBaseName().contains("_dummycontext")) {
        loadDummyContextObjectFile(filePath);
    } else {
        loadDummyDataFile(filePath);
    }
579
580

    refreshBindings();
581
582
583
    startRenderTimer();
}

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
void NodeInstanceServer::addChangedProperty(const InstancePropertyPair &property)
{
    if (!m_changedPropertyList.contains(property))
        m_changedPropertyList.append(property);
}

void NodeInstanceServer::emitParentChanged(QObject *child)
{
    if (hasInstanceForObject(child)) {
        addChangedProperty(InstancePropertyPair(instanceForObject(child), "parent"));
    }
}

Internal::ChildrenChangeEventFilter *NodeInstanceServer::childrenChangeEventFilter()
{
    if (m_childrenChangeEventFilter.isNull()) {
        m_childrenChangeEventFilter = new Internal::ChildrenChangeEventFilter(this);
        connect(m_childrenChangeEventFilter.data(), SIGNAL(childrenChanged(QObject*)), this, SLOT(emitParentChanged(QObject*)));
    }

    return m_childrenChangeEventFilter.data();
}

void NodeInstanceServer::resetInstanceProperty(const PropertyAbstractContainer &propertyContainer)
{
    if (hasInstanceForId(propertyContainer.instanceId())) { // TODO ugly workaround
        ServerNodeInstance instance = instanceForId(propertyContainer.instanceId());
        Q_ASSERT(instance.isValid());

        const QString name = propertyContainer.name();

615
        if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
            bool statePropertyWasReseted = activeStateInstance().resetStateProperty(instance, name, instance.resetVariant(name));
            if (!statePropertyWasReseted)
                instance.resetProperty(name);
        } else {
            instance.resetProperty(name);
        }
    }
}


void NodeInstanceServer::setInstancePropertyBinding(const PropertyBindingContainer &bindingContainer)
{
    if (hasInstanceForId(bindingContainer.instanceId())) {
        ServerNodeInstance instance = instanceForId(bindingContainer.instanceId());

        const QString name = bindingContainer.name();
        const QString expression = bindingContainer.expression();


635
        if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
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
            bool stateBindingWasUpdated = activeStateInstance().updateStateBinding(instance, name, expression);
            if (!stateBindingWasUpdated) {
                if (bindingContainer.isDynamic())
                    instance.setPropertyDynamicBinding(name, bindingContainer.dynamicTypeName(), expression);
                else
                    instance.setPropertyBinding(name, expression);
            }
        } else {
            if (bindingContainer.isDynamic())
                instance.setPropertyDynamicBinding(name, bindingContainer.dynamicTypeName(), expression);
            else
                instance.setPropertyBinding(name, expression);
        }
    }
}


void NodeInstanceServer::removeProperties(const QList<PropertyAbstractContainer> &propertyList)
{
    foreach (const PropertyAbstractContainer &property, propertyList)
        resetInstanceProperty(property);
}

void NodeInstanceServer::setInstancePropertyVariant(const PropertyValueContainer &valueContainer)
{
    if (hasInstanceForId(valueContainer.instanceId())) {
        ServerNodeInstance instance = instanceForId(valueContainer.instanceId());


        const QString name = valueContainer.name();
        const QVariant value = valueContainer.value();


669
        if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
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
            bool stateValueWasUpdated = activeStateInstance().updateStateVariant(instance, name, value);
            if (!stateValueWasUpdated) {
                if (valueContainer.isDynamic())
                    instance.setPropertyDynamicVariant(name, valueContainer.dynamicTypeName(), value);
                else
                    instance.setPropertyVariant(name, value);
            }
        } else { //base state
            if (valueContainer.isDynamic())
                instance.setPropertyDynamicVariant(name, valueContainer.dynamicTypeName(), value);
            else
                instance.setPropertyVariant(name, value);
        }

//        instance.paintUpdate();
    }
}


QUrl NodeInstanceServer::fileUrl() const
{
    return m_fileUrl;
}

ServerNodeInstance NodeInstanceServer::activeStateInstance() const
{
    return m_activeStateInstance;
}

ServerNodeInstance NodeInstanceServer::rootNodeInstance() const
{
    return m_rootNodeInstance;
}

void NodeInstanceServer::setStateInstance(const ServerNodeInstance &stateInstance)
{
    m_activeStateInstance = stateInstance;
}

void NodeInstanceServer::clearStateInstance()
{
    m_activeStateInstance = ServerNodeInstance();
}

void NodeInstanceServer::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_timer) {
        findItemChangesAndSendChangeCommands();
    }

    NodeInstanceServerInterface::timerEvent(event);
}

NodeInstanceClientInterface *NodeInstanceServer::nodeInstanceClient() const
{
    return m_nodeInstanceClient;
}

728
729
730
731
732
733
734
735
void NodeInstanceServer::sendChildrenChangedCommand(const QList<ServerNodeInstance> childList)
{
    QSet<ServerNodeInstance> parentSet;
    QList<ServerNodeInstance> noParentList;

    foreach (const ServerNodeInstance &child, childList) {
        if (!child.hasParent())
            noParentList.append(child);
Thomas Hartmann's avatar
Thomas Hartmann committed
736
737
        else
            parentSet.insert(child.parent());
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
    }


    foreach (const ServerNodeInstance &parent, parentSet)
        nodeInstanceClient()->childrenChanged(createChildrenChangedCommand(parent, parent.childItems()));

    if (!noParentList.isEmpty())
        nodeInstanceClient()->childrenChanged(createChildrenChangedCommand(ServerNodeInstance(), noParentList));

}

ChildrenChangedCommand NodeInstanceServer::createChildrenChangedCommand(const ServerNodeInstance &parentInstance, const QList<ServerNodeInstance> &instanceList) const
{
    QVector<qint32> instanceVector;

    foreach(const ServerNodeInstance &instance, instanceList)
        instanceVector.append(instance.instanceId());

    return ChildrenChangedCommand(parentInstance.instanceId(), instanceVector);
}

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
InformationChangedCommand NodeInstanceServer::createAllInformationChangedCommand(const QList<ServerNodeInstance> &instanceList, bool initial) const
{
    QVector<InformationContainer> informationVector;

    foreach(const ServerNodeInstance &instance, instanceList) {
        informationVector.append(InformationContainer(instance.instanceId(), Position, instance.position()));
        informationVector.append(InformationContainer(instance.instanceId(), Transform, instance.transform()));
        informationVector.append(InformationContainer(instance.instanceId(), SceneTransform, instance.sceneTransform()));
        informationVector.append(InformationContainer(instance.instanceId(), Size, instance.size()));
        informationVector.append(InformationContainer(instance.instanceId(), BoundingRect, instance.boundingRect()));
        informationVector.append(InformationContainer(instance.instanceId(), Transform, instance.transform()));
        informationVector.append(InformationContainer(instance.instanceId(), HasContent, instance.hasContent()));
        informationVector.append(InformationContainer(instance.instanceId(), IsMovable, instance.isMovable()));
        informationVector.append(InformationContainer(instance.instanceId(), IsResizable, instance.isResizable()));
        informationVector.append(InformationContainer(instance.instanceId(), IsInPositioner, instance.isInPositioner()));
        informationVector.append(InformationContainer(instance.instanceId(), PenWidth, instance.penWidth()));
        informationVector.append(InformationContainer(instance.instanceId(), IsAnchoredByChildren, instance.isAnchoredByChildren()));
        informationVector.append(InformationContainer(instance.instanceId(), IsAnchoredBySibling, instance.isAnchoredBySibling()));

        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.fill"), instance.hasAnchor("anchors.fill")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.centerIn"), instance.hasAnchor("anchors.centerIn")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.right"), instance.hasAnchor("anchors.right")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.top"), instance.hasAnchor("anchors.top")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.left"), instance.hasAnchor("anchors.left")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.bottom"), instance.hasAnchor("anchors.bottom")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.horizontalCenter"), instance.hasAnchor("anchors.horizontalCenter")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.verticalCenter"), instance.hasAnchor("anchors.verticalCenter")));
        informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.baseline"), instance.hasAnchor("anchors.baseline")));

        QPair<QString, ServerNodeInstance> anchorPair = instance.anchor("anchors.fill");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.fill"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.centerIn");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.centerIn"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.right");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.right"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.top");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.top"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.left");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.left"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.bottom");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.bottom"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.horizontalCenter");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.horizontalCenter"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.verticalCenter");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.verticalCenter"), anchorPair.first, anchorPair.second.instanceId()));

        anchorPair = instance.anchor("anchors.baseline");
        informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.baseline"), anchorPair.first, anchorPair.second.instanceId()));

        QStringList propertyNames = instance.propertyNames();

        if (initial) {
            foreach (const QString &propertyName,propertyNames)
                informationVector.append(InformationContainer(instance.instanceId(), InstanceTypeForProperty, propertyName, instance.instanceType(propertyName)));
        }

        foreach (const QString &propertyName,instance.propertyNames()) {
            bool hasChanged = false;
            bool hasBinding = instance.hasBindingForProperty(propertyName, &hasChanged);
            if (hasChanged)
                informationVector.append(InformationContainer(instance.instanceId(), HasBindingForProperty, propertyName, hasBinding));
        }

    }

    return InformationChangedCommand(informationVector);
}

ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QList<ServerNodeInstance> &instanceList) const
{
    QVector<PropertyValueContainer> valueVector;

    foreach(const ServerNodeInstance &instance, instanceList) {
        foreach(const QString &propertyName, instance.propertyNames()) {
            QVariant propertyValue = instance.property(propertyName);
            if (propertyValue.type() < QVariant::UserType)
                valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, QString()));
        }
    }

    return ValuesChangedCommand(valueVector);
}

849
850
851
852
853
854
855
856
857
858
859
ComponentCompletedCommand NodeInstanceServer::createComponentCompletedCommand(const QList<ServerNodeInstance> &instanceList)
{
    QVector<qint32> idVector;
    foreach (const ServerNodeInstance &instance, instanceList) {
        if (instance.instanceId() >= 0)
            idVector.append(instance.instanceId());
    }

    return ComponentCompletedCommand(idVector);
}

860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QVector<InstancePropertyPair> &propertyList) const
{
    QVector<PropertyValueContainer> valueVector;

    foreach (const InstancePropertyPair &property, propertyList) {
        const QString propertyName = property.second;
        const ServerNodeInstance instance = property.first;

        if( instance.isValid()) {
            QVariant propertyValue = instance.property(propertyName);
            if (propertyValue.type() < QVariant::UserType)
                valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, QString()));
        }
    }

    return ValuesChangedCommand(valueVector);
}

Marco Bubke's avatar
Marco Bubke committed
878
879
880
881
882
QStringList NodeInstanceServer::imports() const
{
    return m_importList;
}

883
884
885
886
887
QObject *NodeInstanceServer::dummyContextObject() const
{
    return m_dummyContextObject.data();
}

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
void NodeInstanceServer::notifyPropertyChange(qint32 instanceid, const QString &propertyName)
{
    if (hasInstanceForId(instanceid))
        addChangedProperty(InstancePropertyPair(instanceForId(instanceid), propertyName));
}

void NodeInstanceServer::insertInstanceRelationship(const ServerNodeInstance &instance)
{
    Q_ASSERT(instance.isValid());
    Q_ASSERT(!m_idInstanceHash.contains(instance.instanceId()));
    Q_ASSERT(!m_objectInstanceHash.contains(instance.internalObject()));
    m_objectInstanceHash.insert(instance.internalObject(), instance);
    m_idInstanceHash.insert(instance.instanceId(), instance);
}

void NodeInstanceServer::removeInstanceRelationsip(qint32 instanceId)
{
    if (hasInstanceForId(instanceId)) {
        ServerNodeInstance instance = instanceForId(instanceId);
        if (instance.isValid())
            instance.setId(QString());
        m_idInstanceHash.remove(instanceId);
        m_objectInstanceHash.remove(instance.internalObject());
        instance.makeInvalid();
    }
}

915
PixmapChangedCommand NodeInstanceServer::createPixmapChangedCommand(const QList<ServerNodeInstance> &instanceList) const
916
{
917
918
    QVector<ImageContainer> imageVector;

919
920
921
922
    foreach (const ServerNodeInstance &instance, instanceList) {
        if (instance.isValid())
            imageVector.append(ImageContainer(instance.instanceId(), instance.renderImage()));
    }
923
924

    return PixmapChangedCommand(imageVector);
925
926
927
928
929
930
931
932
933
934
935
936
}

bool NodeInstanceServer::nonInstanceChildIsDirty(QGraphicsObject *graphicsObject) const
{
    QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(graphicsObject);
    if (d->dirtyChildren) {
        foreach(QGraphicsItem *child, graphicsObject->childItems()) {
            QGraphicsObject *childGraphicsObject = child->toGraphicsObject();
            if (hasInstanceForObject(childGraphicsObject))
                continue;

            QGraphicsItemPrivate *childPrivate = QGraphicsItemPrivate::get(child);
937
            if (childPrivate->dirty || nonInstanceChildIsDirty(childGraphicsObject))
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
                return true;
        }
    }

    return false;
}

void NodeInstanceServer::resetAllItems()
{
//     m_declarativeView->scene()->update();
//    m_declarativeView->viewport()->repaint();
    static_cast<QGraphicsScenePrivate*>(QObjectPrivate::get(m_declarativeView->scene()))->processDirtyItemsEmitted = true;

    foreach (QGraphicsItem *item, m_declarativeView->items())
         static_cast<QGraphicsScenePrivate*>(QObjectPrivate::get(m_declarativeView->scene()))->resetDirtyItem(item);
}

955
956
957
958
959
960
961
962
963
964
965
966
967
void NodeInstanceServer::initializeDeclarativeView()
{
    Q_ASSERT(!m_declarativeView.data());

    m_declarativeView = new QDeclarativeView;
#ifndef Q_WS_MAC
    m_declarativeView->setAttribute(Qt::WA_DontShowOnScreen, true);
#endif
    m_declarativeView->setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    m_declarativeView->show();
#ifdef Q_WS_MAC
    m_declarativeView->setAttribute(Qt::WA_DontShowOnScreen, true);
#endif
968
    QUnifiedTimer::instance()->setSlowdownFactor(0.00001);
969
    QUnifiedTimer::instance()->setSlowModeEnabled(true);
970
971
}

972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
QImage NodeInstanceServer::renderPreviewImage()
{
    QSize size = rootNodeInstance().boundingRect().size().toSize();
    size.scale(100, 100, Qt::KeepAspectRatio);

    QImage image(size, QImage::Format_ARGB32);
    image.fill(0xFFFFFFFF);

    if (m_declarativeView) {
        QPainter painter(&image);
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
        painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
        painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
        painter.setRenderHint(QPainter::NonCosmeticDefaultPen, true);

        m_declarativeView->scene()->render(&painter, image.rect(), rootNodeInstance().boundingRect().toRect(), Qt::IgnoreAspectRatio);
    }

    return image;
}

994
void NodeInstanceServer::loadDummyDataFile(const QFileInfo& qmlFileInfo)
995
{
996
997
998
999
1000
1001
    QDeclarativeComponent component(engine(), qmlFileInfo.filePath());
    QObject *dummyData = component.create();
    if(component.isError()) {
        QList<QDeclarativeError> errors = component.errors();
        foreach (const QDeclarativeError &error, errors) {
            qWarning() << error;
1002
        }
1003
    }
1004

1005
1006
1007
1008
1009
1010
    QVariant oldDummyDataObject = m_declarativeView->rootContext()->contextProperty(qmlFileInfo.completeBaseName());

    if (dummyData) {
        qWarning() << "Loaded dummy data:" << qmlFileInfo.filePath();
        m_declarativeView->rootContext()->setContextProperty(qmlFileInfo.completeBaseName(), dummyData);
        dummyData->setParent(this);
1011
    }
1012
1013
1014
1015
1016
1017
1018
1019

    if (!oldDummyDataObject.isNull())
        delete oldDummyDataObject.value<QObject*>();

    if (!dummydataFileSystemWatcher()->files().contains(qmlFileInfo.filePath()))
        dummydataFileSystemWatcher()->addPath(qmlFileInfo.filePath());
}

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
void NodeInstanceServer::loadDummyContextObjectFile(const QFileInfo& qmlFileInfo)
{
    delete m_dummyContextObject.data();

    QDeclarativeComponent component(engine(), qmlFileInfo.filePath());
    m_dummyContextObject = component.create();

    if(component.isError()) {
        QList<QDeclarativeError> errors = component.errors();
        foreach (const QDeclarativeError &error, errors) {
            qWarning() << error;
        }
    }

    if (m_dummyContextObject) {
        qWarning() << "Loaded dummy context object:" << qmlFileInfo.filePath();
        m_dummyContextObject->setParent(this);
    }

    if (!dummydataFileSystemWatcher()->files().contains(qmlFileInfo.filePath()))
        dummydataFileSystemWatcher()->addPath(qmlFileInfo.filePath());
1041
1042

    refreshBindings();
1043
1044
}

1045
1046
1047
1048
void NodeInstanceServer::loadDummyDataFiles(const QString& directory)
{
    QDir dir(directory, "*.qml");
    QList<QFileInfo> filePathList = dir.entryInfoList();
1049
1050
1051
1052
1053
1054
1055
1056
    QString baseName = QFileInfo(fileUrl().toLocalFile()).completeBaseName();
    foreach (const QFileInfo &qmlFileInfo, filePathList) {
        if (!qmlFileInfo.completeBaseName().contains("_dummycontext")) {
            loadDummyDataFile(qmlFileInfo);
        } else if (qmlFileInfo.completeBaseName() == baseName+"_dummycontext") {
            loadDummyContextObjectFile(qmlFileInfo);
        }
    }
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
}

QStringList dummyDataDirectories(const QString& directoryPath)
{
    QStringList dummyDataDirectoryList;
    QDir directory(directoryPath);
    while(true) {
        if (directory.isRoot() || !directory.exists())
            return dummyDataDirectoryList;

        if (directory.exists("dummydata"))
            dummyDataDirectoryList.prepend(directory.absoluteFilePath("dummydata"));

        directory.cdUp();
    }
}

1074
1075
QList<ServerNodeInstance> NodeInstanceServer::setupScene(const CreateSceneCommand &command)
{
1076
    if (!command.fileUrl().isEmpty()) {
1077
        engine()->setBaseUrl(command.fileUrl());
1078
        m_fileUrl = command.fileUrl();
1079
1080
1081
1082
1083
    }

    addImports(command.imports());

    if (!command.fileUrl().isEmpty()) {
1084
1085
1086
1087
        QStringList dummyDataDirectoryList = dummyDataDirectories(QFileInfo(command.fileUrl().toLocalFile()).path());
        foreach(const QString &dummyDataDirectory, dummyDataDirectoryList)
            loadDummyDataFiles(dummyDataDirectory);
    }
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098

    static_cast<QGraphicsScenePrivate*>(QObjectPrivate::get(m_declarativeView->scene()))->processDirtyItemsEmitted = true;

    QList<ServerNodeInstance> instanceList = createInstances(command.instances());
    reparentInstances(command.reparentInstances());

    foreach(const IdContainer &container, command.ids()) {
        if (hasInstanceForId(container.instanceId()))
            instanceForId(container.instanceId()).setId(container.id());
    }

1099
1100
1101
1102
    foreach(const PropertyValueContainer &container, command.valueChanges()) {
        if (container.isDynamic())
            setInstancePropertyVariant(container);
    }
1103

1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
    foreach(const PropertyValueContainer &container, command.valueChanges()) {
        if (!container.isDynamic())
            setInstancePropertyVariant(container);
    }

    foreach(const PropertyBindingContainer &container, command.bindingChanges()) {
        if (container.isDynamic())
            setInstancePropertyBinding(container);
    }

    foreach(const PropertyBindingContainer &container, command.bindingChanges()) {
        if (!container.isDynamic())
            setInstancePropertyBinding(container);
    }
1118
1119
1120
1121
1122
1123
1124
1125
1126

    foreach(ServerNodeInstance instance, instanceList)
        instance.doComponentComplete();

    m_declarativeView->scene()->setSceneRect(rootNodeInstance().boundingRect());

    return instanceList;
}

1127
1128
1129
void NodeInstanceServer::findItemChangesAndSendChangeCommands()
{
    static bool inFunction = false;
1130
    if (!inFunction) {
1131
1132
1133
1134
        inFunction = true;

        QSet<ServerNodeInstance> informationChangedInstanceSet;
        QVector<InstancePropertyPair> propertyChangedList;
1135
        QSet<ServerNodeInstance> parentChangedSet;
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
        bool adjustSceneRect = false;

        if (m_declarativeView) {
            foreach (QGraphicsItem *item, m_declarativeView->items()) {
                QGraphicsObject *graphicsObject = item->toGraphicsObject();
                if (graphicsObject && hasInstanceForObject(graphicsObject)) {
                    ServerNodeInstance instance = instanceForObject(graphicsObject);
                    QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(item);

                    if (d->dirtySceneTransform || d->geometryChanged || d->dirty)
                        informationChangedInstanceSet.insert(instance);

                    if (d->geometryChanged) {
                        if (instance.isRootNodeInstance())
                            m_declarativeView->scene()->setSceneRect(item->boundingRect());
                    }

                }
            }

            foreach (const InstancePropertyPair& property, m_changedPropertyList) {
                const ServerNodeInstance instance = property.first;
                const QString propertyName = property.second;

1160
1161
1162
                if (instance.isValid()) {
                    if (instance.isRootNodeInstance() && (propertyName == "width" || propertyName == "height"))
                        adjustSceneRect = true;
1163

1164
1165
1166
1167
1168
1169
1170
                    if (propertyName.contains("anchors") && informationChangedInstanceSet.contains(instance))
                        informationChangedInstanceSet.insert(instance);

                    if (propertyName == "parent") {
                        informationChangedInstanceSet.insert(instance);
                        parentChangedSet.insert(instance);
                    }
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184

                    propertyChangedList.append(property);
                }
            }

            m_changedPropertyList.clear();
            resetAllItems();

            if (!informationChangedInstanceSet.isEmpty())
                nodeInstanceClient()->informationChanged(createAllInformationChangedCommand(informationChangedInstanceSet.toList()));

            if (!propertyChangedList.isEmpty())
                nodeInstanceClient()->valuesChanged(createValuesChangedCommand(propertyChangedList));

1185
1186
1187
            if (!parentChangedSet.isEmpty())
                sendChildrenChangedCommand(parentChangedSet.toList());

1188
1189
1190
1191
1192
1193
1194
            if (adjustSceneRect) {
                QRectF boundingRect = m_rootNodeInstance.boundingRect();
                if (boundingRect.isValid()) {
                    m_declarativeView->setSceneRect(boundingRect);
                }
            }

1195
1196
1197
1198
1199
            if (!m_completedComponentList.isEmpty()) {
                nodeInstanceClient()->componentCompleted(createComponentCompletedCommand(m_completedComponentList));
                m_completedComponentList.clear();
            }

1200
            slowDownRenderTimer();
1201
            nodeInstanceClient()->flush();
1202
            nodeInstanceClient()->synchronizeWithClientProcess();
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
        }

        inFunction = false;
    }

}
}