summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Palettes/Action/ActionView.cpp
blob: d71972858865d526bbce487af5e6c079cb57c98a (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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "ActionView.h"
#include "ActionContextMenu.h"
#include "ActionModel.h"
#include "CmdDataModelActionSetValue.h"
#include "ClientDataModelBridge.h"
#include "Core.h"
#include "Dialogs.h"
#include "Dispatch.h"
#include "Doc.h"
#include "IDocumentEditor.h"
#include "IDocumentReader.h"
#include "IObjectReferenceHelper.h"
#include "Literals.h"
#include "ObjectListModel.h"
#include "StudioUtils.h"
#include "StudioApp.h"
#include "StudioClipboard.h"
#include "StudioObjectTypes.h"
#include "StudioPreferences.h"
#include "Qt3DSFileTools.h"
#include "Qt3DSDMActionCore.h"
#include "Qt3DSDMDataTypes.h"
#include "Qt3DSDMSlides.h"

#include <QtCore/qcoreapplication.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlengine.h>
#include <QtCore/qtimer.h>
#include <QtWidgets/qdesktopwidget.h>

ActionView::ActionView(const QSize &preferredSize, QWidget *parent)
    : QQuickWidget(parent)
    , TabNavigable()
    , m_actionsModel(new ActionModel(this))
    , m_preferredSize(preferredSize)
{
    setResizeMode(QQuickWidget::SizeRootObjectToView);
    QTimer::singleShot(0, this, &ActionView::initialize);

    g_StudioApp.GetCore()->GetDispatch()->AddPresentationChangeListener(this);

    connect(this, &ActionView::actionChanged, this, [this] {
        if (!m_itemHandle.Valid())
            return;

        if (!m_propertyModel)
            m_propertyModel = new PropertyModel(this);

        const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
        if (actionInfo.m_Handler == L"Set Property") {
            setPropertyValueInvalid(true);
            m_currentPropertyNameHandle = actionInfo.m_HandlerArgs.at(0);
            m_currentPropertyValueHandle = actionInfo.m_HandlerArgs.at(1);
            m_propertyModel->setAction(m_actionsModel->actionAt(m_currentActionIndex));
            m_propertyModel->setNameHandle(m_currentPropertyNameHandle);
            m_propertyModel->setValueHandle(m_currentPropertyValueHandle);
            m_currentPropertyIndex = m_propertyModel->defaultPropertyIndex();
            Q_EMIT propertyChanged();
            Q_EMIT propertyModelChanged();
            setPropertyValueInvalid(false);
        }
    });

    m_actionChangedCompressionTimer.setInterval(20);
    m_actionChangedCompressionTimer.setSingleShot(true);
    connect(&m_actionChangedCompressionTimer, &QTimer::timeout, this, [this] {
        updateHandlerArguments();
        updateFiredEvent();
        Q_EMIT actionChanged();
    });

    QString ctrlKey(QStringLiteral("Ctrl+"));
    QString shiftKey(QStringLiteral("Shift+"));
#ifdef Q_OS_MACOS
    ctrlKey = "⌘";
    shiftKey = "⇧";
#endif

    // These actions will be passed to the context menu. Some of them need to me members, as we
    // have to change their enabled state based on selection and previous actions.
    QAction *action = new QAction(tr("New Action\t%1A").arg(shiftKey));
    action->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_A));
    connect(action, &QAction::triggered, this, &ActionView::addAction);
    QQuickWidget::addAction(action);

    m_actionCopy = new QAction(tr("Copy Action\t%1C").arg(ctrlKey));
    connect(m_actionCopy, &QAction::triggered, this, &ActionView::copyAction);
    QQuickWidget::addAction(m_actionCopy);

    m_actionPaste = new QAction(tr("Paste Action\t%1V").arg(ctrlKey));
    connect(m_actionPaste, &QAction::triggered, this, &ActionView::pasteAction);
    QQuickWidget::addAction(m_actionPaste);

    m_actionCut = new QAction(tr("Cut Action\t%1X").arg(ctrlKey));
    connect(m_actionCut, &QAction::triggered, this, &ActionView::cutAction);
    QQuickWidget::addAction(m_actionCut);

    m_actionDel = new QAction(tr("Delete Action\tDel"));
    connect(m_actionDel, &QAction::triggered, [=](){ deleteAction(m_currentActionIndex); });
    QQuickWidget::addAction(m_actionDel);
}

ActionView::~ActionView()
{
    m_connections.clear();
}

QSize ActionView::sizeHint() const
{
    return m_preferredSize;
}

void ActionView::focusInEvent(QFocusEvent *event)
{
    updateActionStates();
    QQuickWidget::focusInEvent(event);
}

void ActionView::mousePressEvent(QMouseEvent *event)
{
    g_StudioApp.setLastActiveView(this);
    QQuickWidget::mousePressEvent(event);
}

bool ActionView::event(QEvent *event)
{
    if (event->type() == QEvent::ShortcutOverride) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (m_currentActionIndex >= 0 && (ke->key() == Qt::Key_Delete
                                          || (ke->modifiers() == Qt::ControlModifier
                                              && (ke->key() == Qt::Key_C || ke->key() == Qt::Key_V
                                                  || ke->key() == Qt::Key_X)))) {
            auto focusItem = quickWindow()->activeFocusItem();
            if (focusItem && (focusItem->objectName() == QStringLiteral("actionListDelegate")
                              || focusItem->objectName() == QStringLiteral("focusEater"))) {
                if (ke->key() == Qt::Key_Delete) {
                    if (m_actionDel->isEnabled())
                        deleteAction(m_currentActionIndex);
                } else if (ke->modifiers() == Qt::ControlModifier) {
                    if (ke->key() == Qt::Key_C) {
                        if (m_actionCopy->isEnabled())
                            copyAction();
                    } else if (ke->key() == Qt::Key_V) {
                        if (m_actionPaste->isEnabled())
                            pasteAction();
                    } else if (ke->key() == Qt::Key_X) {
                        if (m_actionCut->isEnabled())
                            cutAction();
                    }
                }
                event->accept();
                return true;
            }
        }
    }
    return QQuickWidget::event(event);
}

void ActionView::setItem(const qt3dsdm::Qt3DSDMInstanceHandle &handle)
{
    m_objRefHelper = GetDoc()->GetDataModelObjectReferenceHelper();
    m_itemHandle = handle;
    m_actionsModel->setInstanceHandle(handle);
    if (m_itemHandle.Valid() != m_hasItem) {
        m_hasItem = m_itemHandle.Valid();
        Q_EMIT hasItemChanged();
    }
    emitActionChanged();
    Q_EMIT itemChanged();
    Q_EMIT itemTextChanged();
}

QString ActionView::itemIcon() const
{
    if (!m_itemHandle.Valid())
        return QString();

    auto info = m_objRefHelper->GetInfo(m_itemHandle);
    return CStudioObjectTypes::GetNormalIconName(info.m_Type);
}

QString ActionView::itemText() const
{
    if (!m_itemHandle.Valid())
        return tr("No Object Selected");

    const auto data = m_objRefHelper->GetInfo(m_itemHandle);
    return data.m_Name.toQString();
}

QColor ActionView::itemColor() const
{
    if (!m_itemHandle.Valid())
        return Qt::white;

    auto info = m_objRefHelper->GetInfo(m_itemHandle);
    if (info.m_Master)
        return CStudioPreferences::masterColor();
    else
        return CStudioPreferences::textColor();
}

QAbstractItemModel *ActionView::actionsModel() const
{
    return m_actionsModel;
}

QAbstractItemModel *ActionView::propertyModel() const
{
    return m_propertyModel;
}

QString ActionView::targetObjectName() const
{
    if (!GetDoc()->IsValid() || !m_itemHandle.Valid())
        return QString();

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);

    const auto targetInstance =
            GetBridge()->GetInstance(actionInfo.m_Owner, actionInfo.m_TargetObject);

    QString targetName = targetInstance.Valid()
            ? GetBridge()->GetName(targetInstance).toQString()
            : tr("[Unknown Target]");

    return targetName;
}

QString ActionView::triggerObjectName() const
{
    if (!GetDoc()->IsValid() || !m_itemHandle.Valid())
        return QString();

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);

    const auto sourceInstance =
            GetBridge()->GetInstance(actionInfo.m_Owner, actionInfo.m_TriggerObject);

    QString sourceName = sourceInstance.Valid()
            ? GetBridge()->GetName(sourceInstance).toQString()
            : tr("[Unknown Source]");

    return sourceName;
}

QString ActionView::eventName() const
{
    if (!GetDoc()->IsValid() || !m_itemHandle.Valid())
        return QString();

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto eventHandle = bridge->ResolveEvent(actionInfo);
    const auto eventInfo = bridge->GetEventInfo(eventHandle);

    const QString formalName = QString::fromWCharArray(eventInfo.m_FormalName.wide_str());
    return formalName.isEmpty() ? tr("[Unknown Event]") : formalName;
}

QString ActionView::handlerName() const
{
    if (!GetDoc()->IsValid() || !m_itemHandle.Valid())
        return QString();

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto handlerHandle = bridge->ResolveHandler(actionInfo);

    if (handlerHandle.Valid()) {
        const auto handlerInfo = bridge->GetHandlerInfo(handlerHandle);
        return QString::fromWCharArray(handlerInfo.m_FormalName.wide_str());
    }

    return tr("[Unknown Handler]");
}

QVariantList ActionView::handlerArguments() const
{
    return m_handlerArguments;
}

PropertyInfo ActionView::property() const
{
    if (!m_propertyModel)
        return {};
    return m_propertyModel->property(m_currentPropertyIndex);
}

bool ActionView::isPropertyValueInvalid() const
{
    return m_propertyValueInvalid;
}

void ActionView::setCurrentActionIndex(int index)
{
    if (index == m_currentActionIndex)
        return;

    m_currentActionIndex = index;
    emitActionChanged();

    updateActionStates();
}

void ActionView::setCurrentPropertyIndex(int handle, int index)
{
    setPropertyValueInvalid(true);
    // Make sure propertymodel name & value handles are always up-to-date,
    // even when index is same as before
    m_currentPropertyValueHandle = 0;
    m_currentPropertyNameHandle = handle;
    for (int i = 0; i < m_handlerArguments.size(); ++i) {
        auto handlerArg = m_handlerArguments[i].value<HandlerArgument>();
        if (handlerArg.m_handle.GetHandleValue() == handle && i < m_handlerArguments.size() - 1) {
            m_currentPropertyValueHandle
                    = m_handlerArguments[i + 1].value<HandlerArgument>().m_handle;
            if (m_propertyModel) {
                m_propertyModel->setNameHandle(m_currentPropertyNameHandle);
                m_propertyModel->setValueHandle(m_currentPropertyValueHandle);
            }
        }
    }

    if (index == m_currentPropertyIndex)
        return;

    m_currentPropertyIndex = index;

    // set the property for the handler
    if (m_propertyModel && handle != 0) {
        qt3dsdm::SValue sValue(QVariant(m_propertyModel->property(index).m_nameId));
        qt3dsdm::SValue oldValue;
        GetDoc()->GetStudioSystem()->GetActionCore()->GetHandlerArgumentValue(handle, oldValue);

        if (!Equals(oldValue, sValue)) {
            CCmd *theCmd =
                    new CCmdDataModelActionSetArgumentValue(GetDoc(), handle, sValue);
            g_StudioApp.GetCore()->ExecuteCommand(theCmd);
        }
    }

    Q_EMIT propertyChanged();
    // Clear the value invalid flag asynchronously as the value doesn't actually change until
    // backend tells us it does
    QTimer::singleShot(0, this, &ActionView::clearPropertyValueInvalid);
}

void ActionView::addAction()
{
    if (m_itemHandle.Valid()) {
        // Query data model bridge to see the applicable events and actions for this instance.
        CClientDataModelBridge *theBridge = GetBridge();

        std::wstring theEventName = theBridge->GetDefaultEvent(m_itemHandle);
        std::wstring theHandlerName = theBridge->GetDefaultHandler(m_itemHandle);

        Q3DStudio::SCOPED_DOCUMENT_EDITOR(*GetDoc(), QObject::tr("Add Action"))
                ->AddAction(GetDoc()->GetActiveSlide(), m_itemHandle, theEventName,
                            theHandlerName);
    }
    updateActionStates();
}

void ActionView::deleteAction(int index)
{
    if (!m_itemHandle.Valid())
        return;

    const auto action = m_actionsModel->actionAt(index);
    if (action.Valid()) {
        Q3DStudio::SCOPED_DOCUMENT_EDITOR(*GetDoc(),
                                          QObject::tr("Delete Action"))->DeleteAction(action);
        emitActionChanged();
    }
    updateActionStates();
}

QObject *ActionView::showTriggerObjectBrowser(const QPoint &point)
{
    if (!m_itemHandle.Valid())
        return nullptr;

    if (!m_objectsModel) {
        m_objectsModel = new ObjectListModel(g_StudioApp.GetCore(),
                                             GetDoc()->GetSceneInstance(), this);
    }

    if (!m_triggerObjectBrowser)
        m_triggerObjectBrowser = new ObjectBrowserView(this);

    m_triggerObjectBrowser->setModel(m_objectsModel);

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto instanceHandle = GetBridge()->GetInstance(actionInfo.m_Owner,
                                                         actionInfo.m_TriggerObject);
    m_triggerObjectBrowser->disconnect();
    m_triggerObjectBrowser->selectAndExpand(instanceHandle, actionInfo.m_Owner);
    CDialogs::showWidgetBrowser(this, m_triggerObjectBrowser, point);

    connect(m_triggerObjectBrowser, &ObjectBrowserView::selectionChanged,
            this, &ActionView::OnTriggerSelectionChanged);
    // update also pathtype in the trigger object when changed from UI
    connect(m_triggerObjectBrowser, &ObjectBrowserView::pathTypeChanged,
            this, &ActionView::OnTriggerSelectionChanged);

    return m_triggerObjectBrowser;
}

QObject *ActionView::showTargetObjectBrowser(const QPoint &point)
{
    if (!m_itemHandle.Valid())
        return nullptr;

    if (!m_objectsModel) {
        m_objectsModel = new ObjectListModel(g_StudioApp.GetCore(),
                                             GetDoc()->GetSceneInstance(), this);
    }

    if (!m_targetObjectBrowser)
        m_targetObjectBrowser = new ObjectBrowserView(this);

    m_targetObjectBrowser->setModel(m_objectsModel);

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto instanceHandle = GetBridge()->GetInstance(actionInfo.m_Owner,
                                                         actionInfo.m_TargetObject);
    m_targetObjectBrowser->disconnect();
    m_targetObjectBrowser->selectAndExpand(instanceHandle, actionInfo.m_Owner);
    CDialogs::showWidgetBrowser(this, m_targetObjectBrowser, point);

    connect(m_targetObjectBrowser, &ObjectBrowserView::selectionChanged,
            this, &ActionView::OnTargetSelectionChanged);
    // update also pathtype in the target object when changed from UI
    connect(m_targetObjectBrowser, &ObjectBrowserView::pathTypeChanged,
            this, &ActionView::OnTargetSelectionChanged);

    return m_targetObjectBrowser;
}

void ActionView::OnTargetSelectionChanged()
{
    auto selectedItem = m_targetObjectBrowser->selectedHandle();
    setTargetObject(m_objRefHelper->GetAssetRefValue(
                        selectedItem, m_itemHandle,
                        (CRelativePathTools::EPathType)(m_targetObjectBrowser->pathType())));
    resetFiredEvent();
}

void ActionView::OnTriggerSelectionChanged()
{
    auto selectedItem = m_triggerObjectBrowser->selectedHandle();
    setTriggerObject(m_objRefHelper->GetAssetRefValue(
                         selectedItem, m_itemHandle,
                         (CRelativePathTools::EPathType)(m_triggerObjectBrowser->pathType())));
    resetFiredEvent();
}

void ActionView::showContextMenu(int x, int y)
{
    updateActionStates();
    CActionContextMenu contextMenu(QQuickWidget::actions(), this);
    contextMenu.exec(mapToGlobal({x, y}));
}

QObject *ActionView::showEventBrowser(const QPoint &point)
{
    if (!m_itemHandle.Valid())
        return nullptr;

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto instanceHandle = bridge->GetInstance(actionInfo.m_Owner, actionInfo.m_TriggerObject);

    if (!instanceHandle.Valid())
        return nullptr;

    if (!m_eventsModel)
        m_eventsModel = new EventsModel(this);

    qt3dsdm::TEventHandleList eventList;
    bridge->GetEvents(instanceHandle, eventList);
    m_eventsModel->setEventList(eventList);

    if (!m_eventsBrowser)
        m_eventsBrowser = new EventsBrowserView(this);

    m_eventsBrowser->setModel(m_eventsModel);

    m_eventsBrowser->disconnect();
    m_eventsBrowser->selectAndExpand(QString::fromStdWString(actionInfo.m_Event));
    CDialogs::showWidgetBrowser(this, m_eventsBrowser, point);

    connect(m_eventsBrowser, &EventsBrowserView::selectionChanged,
            this, [this] {
        setEvent(qt3dsdm::Qt3DSDMEventHandle(m_eventsBrowser->selectedHandle()));
    });

    return m_eventsBrowser;
}

QObject *ActionView::showHandlerBrowser(const QPoint &point)
{
    if (!m_itemHandle.Valid())
        return nullptr;

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto instanceHandle = bridge->GetInstance(actionInfo.m_Owner, actionInfo.m_TargetObject);

    if (!instanceHandle.Valid())
        return nullptr;

    if (!m_handlersModel)
        m_handlersModel = new EventsModel(this);

    qt3dsdm::THandlerHandleList handlerList;
    bridge->GetHandlers(instanceHandle, handlerList);
    m_handlersModel->setHandlerList(handlerList);

    if (!m_handlerBrowser)
        m_handlerBrowser = new EventsBrowserView(this);

    m_handlerBrowser->setModel(m_handlersModel);

    m_handlerBrowser->disconnect();
    m_handlerBrowser->selectAndExpand(QString::fromStdWString(actionInfo.m_Handler));
    CDialogs::showWidgetBrowser(this, m_handlerBrowser, point);

    connect(m_handlerBrowser, &EventsBrowserView::selectionChanged,
            this, [this] {
        setHandler(qt3dsdm::Qt3DSDMHandlerHandle(m_handlerBrowser->selectedHandle()));
    });

    return m_handlerBrowser;
}

QObject *ActionView::showEventBrowserForArgument(int handle, const QPoint &point)
{
    if (!m_itemHandle.Valid())
        return nullptr;

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto instanceHandle = bridge->GetInstance(actionInfo.m_Owner, actionInfo.m_TargetObject);

    if (!instanceHandle.Valid())
        return nullptr;

    if (!m_fireEventsModel)
        m_fireEventsModel = new EventsModel(this);

    qt3dsdm::TEventHandleList eventList;
    bridge->GetEvents(instanceHandle, eventList);
    m_fireEventsModel->setEventList(eventList);

    if (!m_fireEventsBrowser)
        m_fireEventsBrowser = new EventsBrowserView(this);

    m_fireEventsBrowser->setModel(m_fireEventsModel);

    qt3dsdm::SValue oldValue;
    GetDoc()->GetStudioSystem()->GetActionCore()->GetHandlerArgumentValue(handle, oldValue);

    QString eventName;
    for (Qt3DSDMEventHandle eventHandle : eventList) {
        if (oldValue == eventHandle.GetHandleValue()) {
            qt3dsdm::SEventInfo eventInfo = bridge->GetEventInfo(eventHandle);
            eventName = QString::fromWCharArray(eventInfo.m_FormalName.wide_str());
            if (eventName.isEmpty())
                eventName = QString::fromWCharArray(eventInfo.m_Name.wide_str());
        }
    }
    m_fireEventsBrowser->disconnect();
    m_fireEventsBrowser->selectAndExpand(eventName);
    CDialogs::showWidgetBrowser(this, m_fireEventsBrowser, point);

    connect(m_fireEventsBrowser, &EventsBrowserView::selectionChanged,
            this, [this, handle] {
        setArgumentValue(handle, qt3dsdm::Qt3DSDMEventHandle(
                             m_fireEventsBrowser->selectedHandle()).GetHandleValue());
    });

    return m_fireEventsBrowser;
}

void ActionView::updateFiredEvent()
{
    if (!m_itemHandle.Valid())
        return;

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    if (actionInfo.m_Handler != L"Fire Event") {
        m_firedEvent = tr("[Unknown event]");
        return;
    }

    const auto doc = GetDoc();
    if (!doc->IsValid())
        return;

    const auto bridge = GetBridge();
    const auto handlerHandle = bridge->ResolveHandler(actionInfo);
    IActionCore *actionCore = doc->GetStudioSystem()->GetActionCore();

    if (handlerHandle.Valid()) {
        for (const auto &argHandle: actionInfo.m_HandlerArgs) {
            const auto &argumentInfo = actionCore->GetHandlerArgumentInfo(argHandle);
            DataModelDataType::Value theArgType(GetValueType(argumentInfo.m_Value));
            SValue theArgValue(argumentInfo.m_Value);
            if (argumentInfo.m_ArgType == HandlerArgumentType::Event) {
                theArgType = DataModelDataType::String;
                auto theEventHandle = get<qt3ds::QT3DSI32>(argumentInfo.m_Value);
                theArgValue = SValue(std::make_shared<CDataStr>(
                                         bridge->GetEventInfo(theEventHandle).m_Name.wide_str()));
                m_firedEvent = theArgValue.toQVariant().toString();
                Q_EMIT firedEventChanged();
            }
        }
    }
}

void ActionView::updateFiredEventFromHandle(int handle)
{
    m_firedEvent = QString::fromWCharArray(
                GetBridge()->GetEventInfo(handle).m_FormalName.wide_str());
    Q_EMIT firedEventChanged();
}

void ActionView::resetFiredEvent()
{
    m_firedEvent = tr("[Unknown Event]");
    Q_EMIT firedEventChanged();
}

void ActionView::OnNewPresentation()
{
    // Register callback
    qt3dsdm::IStudioFullSystemSignalProvider *theSignalProvider =
            g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()->GetFullSystemSignalProvider();
    m_connections.push_back(theSignalProvider->ConnectActionCreated(
                                std::bind(&ActionView::OnActionAdded, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2, std::placeholders::_3)));
    m_connections.push_back(theSignalProvider->ConnectActionDeleted(
                                std::bind(&ActionView::OnActionDeleted, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2, std::placeholders::_3)));
    m_connections.push_back(theSignalProvider->ConnectTriggerObjectSet(
                                std::bind(&ActionView::OnActionModified, this,
                                          std::placeholders::_1)));
    m_connections.push_back(theSignalProvider->ConnectTargetObjectSet(
                                std::bind(&ActionView::OnActionModified, this,
                                          std::placeholders::_1)));
    m_connections.push_back(theSignalProvider->ConnectEventSet(
                                std::bind(&ActionView::OnActionModified, this,
                                          std::placeholders::_1)));
    m_connections.push_back(theSignalProvider->ConnectHandlerSet(
                                std::bind(&ActionView::OnActionModified, this,
                                          std::placeholders::_1)));
    m_connections.push_back(theSignalProvider->ConnectHandlerArgumentValueSet(
                                std::bind(&ActionView::OnHandlerArgumentModified, this,
                                          std::placeholders::_1)));
    m_connections.push_back(theSignalProvider->ConnectInstancePropertyValue(
                                std::bind(&ActionView::OnInstancePropertyValueChanged, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2)));
    m_connections.push_back(theSignalProvider->ConnectInstanceDeleted(
                                std::bind(&ActionView::OnInstanceDeleted, this,
                                          std::placeholders::_1)));
    CDispatch *theDispatch = g_StudioApp.GetCore()->GetDispatch();
    m_connections.push_back(theDispatch->ConnectSelectionChange(
                                std::bind(&ActionView::OnSelectionSet, this,
                                          std::placeholders::_1)));
}

void ActionView::OnSelectionSet(Q3DStudio::SSelectedValue inSelectable)
{
    qt3dsdm::Qt3DSDMInstanceHandle theInstance;
    std::vector<qt3dsdm::Qt3DSDMInstanceHandle> instances;

    switch (inSelectable.getType()) {
    case Q3DStudio::SelectedValueTypes::Instance:
        theInstance = inSelectable.getData<qt3dsdm::Qt3DSDMInstanceHandle>();
        break;
    case Q3DStudio::SelectedValueTypes::MultipleInstances:
        instances = inSelectable.getData<std::vector<qt3dsdm::Qt3DSDMInstanceHandle>>();
        // handling only if we have one selected element.
        if (instances.size() == 1)
            theInstance = instances[0];
        break;
    case Q3DStudio::SelectedValueTypes::Slide: {
        qt3dsdm::Qt3DSDMSlideHandle theSlideHandle =
                inSelectable.getData<Q3DStudio::SSlideInstanceWrapper>().m_Slide;
        // Get the owning component instance
        CClientDataModelBridge *theBridge = GetBridge();
        qt3dsdm::SLong4 theComponentGuid = theBridge->GetComponentGuid(theSlideHandle);
        Q_ASSERT(GuidValid(theComponentGuid));
        theInstance = theBridge->GetInstanceByGUID(theComponentGuid);
        Q_ASSERT(theInstance.Valid());
    }
        break;
    default:
        // Do nothing on slide insertion, guide and unknown types
        return;
    };

    setItem(theInstance);
}

void ActionView::OnActionAdded(qt3dsdm::Qt3DSDMActionHandle inAction,
                               qt3dsdm::Qt3DSDMSlideHandle inSlide,
                               qt3dsdm::Qt3DSDMInstanceHandle inOwner)
{
    CDoc *theDoc = GetDoc();
    qt3dsdm::CStudioSystem *theStudioSystem = theDoc->GetStudioSystem();

    qt3dsdm::Qt3DSDMSlideHandle theCurrentSlide = theDoc->GetActiveSlide();
    qt3dsdm::Qt3DSDMSlideHandle theMasterSlideOfAction =
            theStudioSystem->GetSlideSystem()->GetMasterSlide(inSlide);
    qt3dsdm::Qt3DSDMSlideHandle theMasterOfCurrentSlide =
            theStudioSystem->GetSlideSystem()->GetMasterSlide(theCurrentSlide);

    if (inOwner == m_itemHandle  // the action is added to current viewed instance
            && (theCurrentSlide == inSlide // and is added to the current viewed slide
                || (theMasterSlideOfAction == inSlide
                    && theMasterOfCurrentSlide == theMasterSlideOfAction))) {
        // or it is added to the master of the current viewed slide
        m_actionsModel->addAction(inAction);
    }
}

void ActionView::OnActionDeleted(qt3dsdm::Qt3DSDMActionHandle inAction,
                                 qt3dsdm::Qt3DSDMSlideHandle inSlide,
                                 qt3dsdm::Qt3DSDMInstanceHandle inOwner)
{
    Q_UNUSED(inSlide);
    Q_UNUSED(inOwner);

    m_actionsModel->removeAction(inAction);
}

void ActionView::OnActionModified(qt3dsdm::Qt3DSDMActionHandle inAction)
{
    if (!m_itemHandle.Valid())
        return;

    if (GetDoc()->GetStudioSystem()->GetActionCore()->HandleValid(inAction)) {
        m_actionsModel->updateAction(inAction);
        emitActionChanged();
    }
}

void ActionView::OnHandlerArgumentModified(qt3dsdm::Qt3DSDMHandlerArgHandle inHandlerArgument)
{
    if (!m_itemHandle.Valid())
        return;

    emitActionChanged();
}

void ActionView::OnInstancePropertyValueChanged(qt3dsdm::Qt3DSDMInstanceHandle inInstance,
                                                qt3dsdm::Qt3DSDMPropertyHandle inProperty)
{
    if (!m_itemHandle.Valid() || m_itemHandle != inInstance)
        return;

    auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()->GetClientDataModelBridge();
    if (inProperty == bridge->GetNameProperty())
        Q_EMIT itemTextChanged();

    emitActionChanged();
}

void ActionView::OnInstanceDeleted(qt3dsdm::Qt3DSDMInstanceHandle inInstance)
{
    // Clear the model on instance deletion
    if (inInstance == m_itemHandle) {
        qt3dsdm::Qt3DSDMInstanceHandle noInstance;
        setItem(noInstance);
    }
}

void ActionView::copyAction()
{
    if (!m_itemHandle.Valid())
        return;

    auto theTempAPFile =
            GetDoc()->GetDocumentReader().CopyAction(m_actionsModel->actionAt(m_currentActionIndex),
                                                     GetDoc()->GetActiveSlide());
    Qt3DSFile theFile(theTempAPFile);
    CStudioClipboard::CopyActionToClipboard(theFile);
    updateActionStates();
}

void ActionView::cutAction()
{
    if (!m_itemHandle.Valid())
        return;

    copyAction();
    auto action = m_actionsModel->actionAt(m_currentActionIndex);
    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*GetDoc(), QObject::tr("Cut Action"))->DeleteAction(action);
    updateActionStates();
}

void ActionView::pasteAction()
{
    if (!m_itemHandle.Valid())
        return;

    Qt3DSFile theTempAPFile = CStudioClipboard::GetActionFromClipboard();
    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*GetDoc(), QObject::tr("Paste Action"))
            ->PasteAction(theTempAPFile.GetAbsolutePath(), m_itemHandle);
    updateActionStates();
}

void ActionView::setTriggerObject(const qt3dsdm::SObjectRefType &object)
{
    auto action = m_actionsModel->actionAt(m_currentActionIndex);
    if (!action.Valid())
        return;

    auto core = g_StudioApp.GetCore();
    auto theBridge = GetBridge();

    auto theCmd = new CCmdDataModelActionSetTriggerObject(GetDoc(), action, object);
    const SActionInfo &theActionInfo
            = GetDoc()->GetStudioSystem()->GetActionCore()->GetActionInfo(action);

    Qt3DSDMInstanceHandle theBaseInstance = theActionInfo.m_Owner;
    Qt3DSDMInstanceHandle theObjectInstance = theBridge->GetInstance(theBaseInstance, object);
    Qt3DSDMInstanceHandle theOldInstance = theBridge->GetInstance(theBaseInstance,
                                                                  theActionInfo.m_TargetObject);
    // old instance and object instance could be the same, for example if user changes the type
    // from Absolute to Path. In this case we don't need to reset handler or event.
    if (theOldInstance != theObjectInstance) {
        theCmd->ResetEvent(
                    theBridge->GetDefaultEvent(theObjectInstance, theActionInfo.m_Event));
    }

    core->ExecuteCommand(theCmd);
    emitActionChanged();
}

void ActionView::setTargetObject(const qt3dsdm::SObjectRefType &object)
{
    auto action = m_actionsModel->actionAt(m_currentActionIndex);
    if (!action.Valid())
        return;

    auto core = g_StudioApp.GetCore();
    auto doc = GetDoc();
    auto theBridge = GetBridge();

    auto theCmd = new CCmdDataModelActionSetTargetObject(doc, action, object);
    const SActionInfo &theActionInfo = doc->GetStudioSystem()->GetActionCore()->GetActionInfo(
                action);

    Qt3DSDMInstanceHandle theBaseInstance = theActionInfo.m_Owner;
    Qt3DSDMInstanceHandle theObjectInstance = theBridge->GetInstance(theBaseInstance, object);
    Qt3DSDMInstanceHandle theOldInstance = theBridge->GetInstance(theBaseInstance,
                                                                  theActionInfo.m_TargetObject);
    // old instance and object instance could be the same, for example if user changes the type
    // from Absolute to Path. In this case we don't need to reset handler or event.
    if (theOldInstance != theObjectInstance) {
        theCmd->ResetHandler(
                    theBridge->GetDefaultHandler(theObjectInstance, theActionInfo.m_Handler));
    }

    core->ExecuteCommand(theCmd);
    emitActionChanged();
}

void ActionView::setEvent(const Qt3DSDMEventHandle &event)
{
    if (!event.Valid())
        return;

    auto doc = GetDoc();
    const auto action = m_actionsModel->actionAt(m_currentActionIndex);
    CCmd *theCmd = new CCmdDataModelActionSetEvent(doc, action,
                                                   doc->GetStudioSystem()
                                                   ->GetActionMetaData()
                                                   ->GetEventInfo(event)
                                                   ->m_Name.wide_str());
    g_StudioApp.GetCore()->ExecuteCommand(theCmd);
}

void ActionView::setHandler(const Qt3DSDMHandlerHandle &handler)
{
    if (!handler.Valid())
        return;

    auto doc = GetDoc();
    const auto action = m_actionsModel->actionAt(m_currentActionIndex);
    wstring handlerName(doc->GetStudioSystem()->GetActionMetaData()->GetHandlerInfo(handler)
                        ->m_Name.wide_str());
    CCmdDataModelActionSetHandler *theCmd =
            new CCmdDataModelActionSetHandler(doc, action, handlerName);
    theCmd->ResetHandler(handlerName); // reset the handler args

    g_StudioApp.GetCore()->ExecuteCommand(theCmd);
}

QVariant ActionView::handlerArgumentValue(int handle) const
{
    qt3dsdm::SValue value;
    GetDoc()->GetStudioSystem()->GetActionCore()->GetHandlerArgumentValue(handle, value);
    return value.toQVariant();
}

void ActionView::updateHandlerArguments()
{
    m_currentPropertyValueHandle = 0;
    m_currentPropertyNameHandle = 0;
    m_handlerArguments.clear();
    const auto doc = GetDoc();
    if (!doc->IsValid() || !m_itemHandle.Valid())
        return;

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    const auto bridge = GetBridge();
    const auto handlerHandle = bridge->ResolveHandler(actionInfo);
    IActionCore *actionCore = doc->GetStudioSystem()->GetActionCore();

    if (handlerHandle.Valid()) {
        auto newMetaData = doc->GetStudioSystem()->GetActionMetaData();

        for (const auto &argHandle: actionInfo.m_HandlerArgs) {
            const auto &argumentInfo = actionCore->GetHandlerArgumentInfo(argHandle);
            Option<SMetaDataHandlerArgumentInfo> argMetaData(
                        newMetaData->FindHandlerArgumentByName(handlerHandle, argumentInfo.m_Name));

            HandlerArgument argument;
            argument.m_handle = argHandle;
            argument.m_type = argMetaData->m_ArgType;
            argument.m_name = QString::fromWCharArray(argumentInfo.m_Name.wide_str());
            argument.m_value = argumentInfo.m_Value.toQVariant();
            argument.m_completeType = argMetaData->m_CompleteType;
            m_handlerArguments.append(QVariant::fromValue(argument));
        }
    }
}

void ActionView::emitActionChanged()
{
    m_actionChangedCompressionTimer.start();
}

void ActionView::setArgumentValue(int handle, const QVariant &value)
{
    if (!m_itemHandle.Valid())
        return;

    if (handle == 0)
        return;

    qt3dsdm::SValue sValue(value);
    qt3dsdm::SValue oldValue;
    GetDoc()->GetStudioSystem()->GetActionCore()->GetHandlerArgumentValue(handle, oldValue);

    if (!Equals(oldValue, sValue)) {
        CCmd *theCmd =
                new CCmdDataModelActionSetArgumentValue(GetDoc(), handle, sValue);
        g_StudioApp.GetCore()->ExecuteCommand(theCmd);
    }

    const auto actionInfo = m_actionsModel->actionInfoAt(m_currentActionIndex);
    if (actionInfo.m_Handler == L"Fire Event") {
        if (value.toInt())
            updateFiredEventFromHandle(value.toInt());
    }
}

CDoc *ActionView::GetDoc()
{
    return g_StudioApp.GetCore()->GetDoc();
}

CClientDataModelBridge *ActionView::GetBridge()
{
    return GetDoc()->GetStudioSystem()->GetClientDataModelBridge();
}

void ActionView::initialize()
{
    CStudioPreferences::setQmlContextProperties(rootContext());
    rootContext()->setContextProperty(QStringLiteral("_parentView"), this);
    rootContext()->setContextProperty(QStringLiteral("_resDir"), StudioUtils::resourceImageUrl());
    rootContext()->setContextProperty(QStringLiteral("_tabOrderHandler"), tabOrderHandler());
    rootContext()->setContextProperty(QStringLiteral("_mouseHelper"), &m_mouseHelper);
    QString shiftKey(QStringLiteral("Shift+"));
#ifdef Q_OS_MACOS
    shiftKey = "⇧";
#endif
    rootContext()->setContextProperty(QStringLiteral("_shiftKey"), shiftKey);
    qmlRegisterUncreatableType<qt3dsdm::HandlerArgumentType>(
                "Qt3DStudio", 1, 0, "HandlerArgumentType",
                QStringLiteral("HandlerArgumentType is an enum container"));
    qmlRegisterUncreatableType<qt3dsdm::DataModelDataType>(
                "Qt3DStudio", 1, 0, "DataModelDataType",
                QStringLiteral("DataModelDataType is an enum container"));
    qmlRegisterUncreatableType<qt3dsdm::AdditionalMetaDataType>(
                "Qt3DStudio", 1, 0, "AdditionalMetaDataType",
                QStringLiteral("AdditionalMetaDataType is an enum container"));
    qmlRegisterUncreatableType<PropertyInfo>(
                "Qt3DStudio", 1, 0, "PropertyInfo",
                QStringLiteral("PropertyInfo is not creatable in QML"));
    qmlRegisterUncreatableType<qt3dsdm::CompleteMetaDataType>(
                "Qt3DStudio", 1, 0, "CompleteMetaDataType",
                QStringLiteral("CompleteMetaDataType is an enum container"));
    engine()->addImportPath(StudioUtils::qmlImportPath());
    setSource(QUrl(QStringLiteral("qrc:/Palettes/Action/ActionView.qml")));
}

QStringList ActionView::slideNames()
{
    if (!m_itemHandle.Valid())
        return {};

    std::list<Q3DStudio::CString> outSlideNames;
    QStringList slideNames;
    CClientDataModelBridge *theBridge = GetBridge();
    const auto action = m_actionsModel->actionAt(m_currentActionIndex);

    theBridge->GetSlideNamesOfAction(action, outSlideNames);

    for (auto slideName : outSlideNames)
        slideNames.append(slideName.toQString());

    return slideNames;
}

int ActionView::slideNameToIndex(const QString &name)
{
    const auto slides = slideNames(); // KDAB_TODO cache it
    return slides.indexOf(name);
}

bool ActionView::toolTipsEnabled()
{
    return CStudioPreferences::ShouldShowTooltips();
}

QColor ActionView::showColorDialog(const QColor &color)
{
    m_currentColor = color;
    CDialogs *dialogs = g_StudioApp.GetDialogs();
    connect(dialogs, &CDialogs::onColorChanged, this, &ActionView::dialogCurrentColorChanged);
    QColor currentColor = dialogs->displayColorDialog(color);
    disconnect(dialogs, &CDialogs::onColorChanged, this, &ActionView::dialogCurrentColorChanged);
    return currentColor;
}

void ActionView::updateActionStates()
{
    bool hasValidAction = (m_currentActionIndex != -1) && m_itemHandle.Valid();
    m_actionCopy->setEnabled(hasValidAction);
    m_actionCut->setEnabled(hasValidAction);
    m_actionDel->setEnabled(hasValidAction);
    // Allow paste action even if item is not valid (list of actions is empty)
    m_actionPaste->setEnabled(CStudioClipboard::CanPasteAction());
}

// m_propertyValueInvalid flag indicates that property value is changing and
// may not be valid if queried at the moment. It is used to prevent QML errors
// about invalid value types when changing property handlers.
void ActionView::setPropertyValueInvalid(bool invalid)
{
    if (invalid != m_propertyValueInvalid) {
        m_propertyValueInvalid = invalid;
        Q_EMIT propertyValueInvalidChanged();
    }
}

// This is used to set m_propertyValueInvalid to false asynchronously
void ActionView::clearPropertyValueInvalid()
{
    setPropertyValueInvalid(false);
}