summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Palettes/Inspector/InspectorControlModel.cpp
blob: 2335ba2d01125f6a6392ef9427fe4d6257dd6b0a (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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
/****************************************************************************
**
** 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 <QFileInfo>
#include <QtCore/qurl.h>

#include <functional>

#include "InspectorControlModel.h"
#include "Core.h"
#include "Doc.h"
#include "ControlGraphIterators.h"
#include "InspectorGroup.h"
#include "Qt3DSDMInspectorGroup.h"
#include "Qt3DSDMInspectorRow.h"
#include "Qt3DSDMStudioSystem.h"
#include "Qt3DSDMInspectable.h"
#include "Qt3DSDMDataCore.h"
#include "StudioApp.h"
#include "IDocumentEditor.h"
#include "Control.h"
#include "ControlData.h"
#include "Qt3DSDMMetaData.h"
#include "Qt3DSDMSignals.h"
#include "CmdDataModelDeanimate.h"
#include "GuideInspectable.h"
#include "Qt3DSDMDataTypes.h"
#include "IObjectReferenceHelper.h"
#include "Qt3DSDMXML.h"
#include "Qt3DSDMStringTable.h"
#include "Qt3DSFileTools.h"
#include "Qt3DSDMSlideCore.h"
#include "SlideSystem.h"
#include "Qt3DSDMMaterialInspectable.h"
#include "ClientDataModelBridge.h"
#include "IDocumentReader.h"
#include "IStudioRenderer.h"
#include "foundation/Qt3DSLogging.h"
#include "Dialogs.h"
#include "Dispatch.h"

static QStringList renderableItems()
{
    QStringList renderables;
    renderables.push_back(QObject::tr("No renderable item"));
    const CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    Q3DStudio::CString docDir = doc->GetDocumentDirectory();

    for (SubPresentationRecord r : qAsConst(g_StudioApp.m_subpresentations))
        renderables.push_back(r.m_id);

    // second step, find the renderable plugins.
    {
        Q3DStudio::CFilePath pluginDir
                = Q3DStudio::CFilePath::CombineBaseAndRelative(docDir, "plugins");
        if (pluginDir.Exists() && pluginDir.IsDirectory()) {
            std::vector<Q3DStudio::CFilePath> dirFiles;
            pluginDir.ListFilesAndDirectories(dirFiles);
            for (size_t idx = 0, end = dirFiles.size(); idx < end; ++idx) {
                if (dirFiles[idx].IsFile()) {
                    Q3DStudio::CFilePath relPath =
                        Q3DStudio::CFilePath::GetRelativePathFromBase(docDir, dirFiles[idx]);
                    renderables.push_back(relPath.toQString());
                }
            }
        }
    }
    std::sort(renderables.begin() + 1, renderables.end());
    return renderables;
}

static std::pair<bool, bool> getSlideCharacteristics(qt3dsdm::Qt3DSDMInstanceHandle instance,
                                                     const qt3dsdm::ISlideCore &slideCore,
                                                     const qt3dsdm::ISlideSystem &slideSystem)
{
    // Get the slide from the instance.
    qt3dsdm::Qt3DSDMSlideHandle slide = slideCore.GetSlideByInstance(instance);
    qt3dsdm::Qt3DSDMSlideHandle master = slideSystem.GetMasterSlide(slide);
    int index = (int)slideSystem.GetSlideIndex(slide);
    int count = (int)slideSystem.GetSlideCount(master);
    bool hasNextSlide = index > 0 && index < count - 1;
    bool hasPreviousSlide = index > 1;
    return std::make_pair(hasNextSlide, hasPreviousSlide);
}

InspectorControlModel::InspectorControlModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_UpdatableEditor(*g_StudioApp.GetCore()->GetDoc())
{
    m_modifiedProperty.first = 0;
    m_modifiedProperty.second = 0;
}

void InspectorControlModel::setInspectable(CInspectableBase *inInspectable)
{
    // Commit any pending transactions on selection change
    m_UpdatableEditor.CommitEditor();
    m_modifiedProperty.first = 0;
    m_modifiedProperty.second = 0;
    m_previouslyCommittedValue = {};

    const auto signalProvider
            = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()->GetFullSystemSignalProvider();

    if (m_notifier.get() == nullptr) {
        m_notifier = signalProvider->ConnectInstancePropertyValue(
                    std::bind(&InspectorControlModel::notifyInstancePropertyValue,
                              this, std::placeholders::_1, std::placeholders::_2));
    }
    if (m_slideNotifier.get() == nullptr) {
        m_slideNotifier = signalProvider->ConnectSlideRearranged(
                    std::bind(&InspectorControlModel::onSlideRearranged, this,
                              std::placeholders::_1, std::placeholders::_2,
                              std::placeholders::_3));
    }

    if (m_inspectableBase != inInspectable) {
        m_inspectableBase = inInspectable;
        rebuildTree();
    }
}

CInspectableBase *InspectorControlModel::inspectable() const
{
    return m_inspectableBase;
}

qt3dsdm::Qt3DSDMInstanceHandle getReferenceMaterial(CInspectableBase *inspectBase)
{
    const auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()
            ->GetClientDataModelBridge();
    qt3dsdm::Qt3DSDMInstanceHandle refMaterial;
    if (const auto cdmInspectable = dynamic_cast<Qt3DSDMInspectable *>(inspectBase))
        refMaterial = bridge->getMaterialReference(cdmInspectable->GetGroupInstance(0));
    return refMaterial;
}

CInspectableBase *getReferenceMaterialInspectable(CInspectableBase *inspectBase)
{
    const auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()
            ->GetClientDataModelBridge();
    if (const auto cdmInspectable = dynamic_cast<Qt3DSDMInspectable *>(inspectBase)) {
        auto refMaterial = bridge->getMaterialReference(cdmInspectable->GetGroupInstance(0));
        if (refMaterial.Valid())
            return g_StudioApp.getInspectableFromInstance(refMaterial);
    }
    return nullptr;
}

void InspectorControlModel::notifyInstancePropertyValue(qt3dsdm::Qt3DSDMInstanceHandle inHandle,
                                                        qt3dsdm::Qt3DSDMPropertyHandle inProperty)
{
    auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()
            ->GetClientDataModelBridge();
    if (!bridge->IsSceneGraphInstance(inHandle))
        return;
    bool changed = false;
    for (int row = 0; row < m_groupElements.count(); ++row) {
        auto group = m_groupElements[row];
        for (int p = 0; p < group.controlElements.count(); ++p) {
            QVariant& element = group.controlElements[p];
            InspectorControlBase *property = element.value<InspectorControlBase *>();
            qt3dsdm::Qt3DSDMInstanceHandle imageInstance;
            if (property->m_dataType == qt3dsdm::DataModelDataType::Long4
                && property->m_property.Valid()) {
                imageInstance = doc->GetDocumentReader().GetImageInstanceForProperty(
                                                property->m_instance, property->m_property);
            }
            if (property->m_property == inProperty || imageInstance == inHandle) {
                updatePropertyValue(property);
                changed = true;
            }
        }
    }
    if (changed)
        Q_EMIT dataChanged(index(0), index(rowCount() - 1));
}

bool InspectorControlModel::hasInstanceProperty(long instance, int handle)
{
    for (const auto &group : qAsConst(m_groupElements)) {
        for (const auto &element : qAsConst(group.controlElements)) {
            InspectorControlBase *property = element.value<InspectorControlBase *>();
            if (property->m_property == qt3dsdm::CDataModelHandle(handle)
                    && property->m_instance == qt3dsdm::CDataModelHandle(instance)) {
                return true;
            }
        }
    }
    return false;
}

bool InspectorControlModel::isInsideMaterialContainer() const
{
    return isInsideMaterialContainer(dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase));
}

bool InspectorControlModel::isInsideMaterialContainer(Qt3DSDMInspectable *inspectable) const
{
    if (!inspectable)
        return false;

    const auto instance = inspectable->GetGroupInstance(0);

    if (!instance.Valid())
        return false;

    const auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()
            ->GetClientDataModelBridge();
    return bridge->isInsideMaterialContainer(instance);
}

bool InspectorControlModel::isDefaultMaterial() const
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();

    qt3dsdm::Qt3DSDMInstanceHandle instance;
    if (const auto inspectable = dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase))
        instance = inspectable->GetGroupInstance(0);

    if (!instance.Valid() || !bridge->IsSceneGraphInstance(instance))
        return false;

    return bridge->GetObjectType(instance) == OBJTYPE_REFERENCEDMATERIAL
            && bridge->GetSourcePath(instance) == Q3DStudio::CString::fromQString(
                bridge->getDefaultMaterialName());
}

bool InspectorControlModel::isAnimatableMaterial() const
{
    return isAnimatableMaterial(dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase));
}

bool InspectorControlModel::isAnimatableMaterial(Qt3DSDMInspectable *inspectable) const
{
    if (!inspectable)
        return false;

    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();

    const auto instance = inspectable->GetGroupInstance(0);
    if (!instance.Valid())
        return false;

    const auto type = bridge->GetObjectType(instance);

    return type == OBJTYPE_CUSTOMMATERIAL || type == OBJTYPE_MATERIAL;
}

bool InspectorControlModel::isBasicMaterial() const
{
    return isBasicMaterial(dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase));
}

bool InspectorControlModel::isBasicMaterial(Qt3DSDMInspectable *inspectable) const
{
    if (!inspectable)
        return false;

    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();

    const auto instance = inspectable->GetGroupInstance(0);
    if (!instance.Valid())
        return false;

    const auto type = bridge->GetObjectType(instance);

    if (type == OBJTYPE_REFERENCEDMATERIAL) {
        const auto refMaterial = bridge->getMaterialReference(instance);
        if (refMaterial.Valid() && bridge->isInsideMaterialContainer(refMaterial))
            return true;
    }

    return false;
}

bool InspectorControlModel::isMaterial() const
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();

    qt3dsdm::Qt3DSDMInstanceHandle instance;
    if (const auto inspectable = dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase))
        instance = inspectable->GetGroupInstance(0);

    if (!instance.Valid())
        return false;

    const auto type = bridge->GetObjectType(instance);

    return type == OBJTYPE_CUSTOMMATERIAL || type == OBJTYPE_MATERIAL
            || type == OBJTYPE_REFERENCEDMATERIAL;
}

void InspectorControlModel::addMaterial()
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    qt3dsdm::Qt3DSDMInstanceHandle instance;
    if (const auto inspectable = dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase))
        instance = inspectable->GetGroupInstance(0);

    if (!instance.Valid())
        return;

    const auto studio = doc->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();

    QString path = doc->getSceneEditor()->getMaterialDirectoryPath()
            + QStringLiteral("/Material");
    QString extension = QStringLiteral(".materialdef");

    auto absPath = path + extension;
    int i = 1;
    while (QFileInfo(absPath).exists()) {
        i++;
        absPath = path + QString::number(i) + extension;
    }

    qt3dsdm::Qt3DSDMInstanceHandle newMaterial;
    {
        newMaterial = Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, QString())
                ->getOrCreateMaterial(absPath, false);
    }
    // Several aspects of the editor are not updated correctly
    // if the data core is changed without a transaction
    // The above scope completes the transaction for creating a new material
    // Next the added undo has to be popped from the stack
    // TODO: Find a way to update the editor fully without a transaction
    g_StudioApp.GetCore()->GetCmdStack()->RemoveLastUndo();

    saveIfMaterial(newMaterial);

    Q3DStudio::ScopedDocumentEditor sceneEditor(
                Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, tr("Set Material Type")));
    doc->SelectDataModelObject(newMaterial);

    const auto type = bridge->GetObjectType(instance);
    if (type == OBJTYPE_REFERENCEDMATERIAL) {
        sceneEditor->setMaterialReferenceByPath(instance, absPath);
        const auto relPath = QDir(doc->GetDocumentDirectory().toQString())
                .relativeFilePath(absPath);
        sceneEditor->setMaterialSourcePath(instance, Q3DStudio::CString::fromQString(relPath));
        sceneEditor->SetName(instance, bridge->GetName(newMaterial, true));
        studio->GetFullSystemSignalSender()->SendInstancePropertyValue(
                    instance, bridge->GetNameProperty());
    }
}

void InspectorControlModel::duplicateMaterial()
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();

    qt3dsdm::Qt3DSDMInstanceHandle instance;
    if (const auto inspectable = dynamic_cast<Qt3DSDMInspectable *>(m_inspectableBase))
        instance = inspectable->GetGroupInstance(0);

    if (!instance.Valid())
        return;

    const auto studio = doc->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();
    const auto type = bridge->GetObjectType(instance);

    if (type != OBJTYPE_MATERIAL && type != OBJTYPE_CUSTOMMATERIAL
            && type != OBJTYPE_REFERENCEDMATERIAL) {
        return;
    }

    auto material = instance;
    if (type == OBJTYPE_REFERENCEDMATERIAL)
        material = getReferenceMaterial(m_inspectableBase);

    if (material.Valid()) {
        const auto sceneEditor = doc->getSceneEditor();
        auto originalMaterialName = sceneEditor->GetName(material).toQString()
                + QStringLiteral(" Copy");
        int slashIndex = originalMaterialName.lastIndexOf(QLatin1Char('/'));
        if (slashIndex != -1)
            originalMaterialName = originalMaterialName.mid(slashIndex + 1);
        auto materialName = originalMaterialName;
        int i = 1;
        auto absPath = sceneEditor->getMaterialFilePath(materialName);
        while (QFileInfo(absPath).exists()) {
            i++;
            materialName = originalMaterialName + QString::number(i);
            absPath = sceneEditor->getMaterialFilePath(materialName);
        }

        qt3dsdm::Qt3DSDMInstanceHandle duplicate;
        {
            Q3DStudio::ScopedDocumentEditor scopedEditor(
                        Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, QString()));
            duplicate = scopedEditor->getOrCreateMaterial(materialName, false);
            scopedEditor->copyMaterialProperties(material, duplicate);
        }
        // Several aspects of the editor are not updated correctly
        // if the data core is changed without a transaction
        // The above scope completes the transaction for creating a new material
        // Next the added undo has to be popped from the stack
        // TODO: Find a way to update the editor fully without a transaction
        g_StudioApp.GetCore()->GetCmdStack()->RemoveLastUndo();

        saveIfMaterial(duplicate);

        Q3DStudio::ScopedDocumentEditor scopedEditor(
                    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, tr("Set Material Type")));
        doc->SelectDataModelObject(duplicate);

        if (type == OBJTYPE_REFERENCEDMATERIAL) {
            scopedEditor->setMaterialReferenceByPath(instance, absPath);
            const auto relPath = QDir(doc->GetDocumentDirectory().toQString())
                    .relativeFilePath(absPath);
            scopedEditor->setMaterialSourcePath(instance, Q3DStudio::CString::fromQString(relPath));
            scopedEditor->SetName(instance, bridge->GetName(duplicate, true));
            studio->GetFullSystemSignalSender()->SendInstancePropertyValue(
                        instance, bridge->GetNameProperty());
        }
    }
}

void InspectorControlModel::updateMaterialValues(const QStringList &values, int elementIndex,
                                                 bool updatingShaders)
{
    // Find if there are any material items and update the values of those
    int startIndex = 0;
    bool isReferenced = !isAnimatableMaterial() && updatingShaders;
    if (isReferenced && m_groupElements.count() > 0)
        startIndex = m_groupElements.count() - 1; // Update the last group for referenced materials
    for (int row = startIndex; row < m_groupElements.count(); ++row) {
        const CInspectorGroup *inspectorGroup = m_inspectableBase->GetGroup(row);
        const auto group = dynamic_cast<const Qt3DSDMInspectorGroup *>(inspectorGroup);
        const auto materialGroup = dynamic_cast<const Qt3DSDMMaterialInspectorGroup *>(group);
        if (materialGroup && (materialGroup->isMaterialGroup() || isReferenced)) {
            if (m_groupElements[row].controlElements.size()) {
                auto item = m_groupElements[row].controlElements[elementIndex]
                        .value<InspectorControlBase *>();
                item->m_values = values;
                Q_EMIT item->valuesChanged();
                // Changing values resets the selected index, so pretend the value has also changed
                Q_EMIT item->valueChanged();
            }
        }
    }
}

void InspectorControlModel::updateShaderValues()
{
    int index = 0;
    if (isAnimatableMaterial() && !isInsideMaterialContainer())
        index = 1;
    updateMaterialValues(shaderValues(), index, true);
}

void InspectorControlModel::updateMatDataValues()
{
    int index = 0;
    if (!isInsideMaterialContainer())
        index = 1;
    updateMaterialValues(matDataValues(), index);
}

void InspectorControlModel::setMaterials(std::vector<Q3DStudio::CFilePath> &materials)
{
    m_materials.clear();
    const Q3DStudio::CString base = g_StudioApp.GetCore()->GetDoc()->GetDocumentDirectory();

    for (Q3DStudio::CFilePath path : materials) {

        const QString relativePath = path.toQString();
        const Q3DStudio::CFilePath absolutePath
            = Q3DStudio::CFilePath::CombineBaseAndRelative(base, path);

        const QString name = g_StudioApp.GetCore()->GetDoc()->GetDocumentReader()
                                  .GetCustomMaterialName(
                                        absolutePath.toCString()).toQString();

        m_materials.push_back({name, relativePath});
    }

    if (!isDefaultMaterial())
        updateShaderValues();
}

void InspectorControlModel::setMatDatas(const std::vector<Q3DStudio::CFilePath> &matDatas)
{
    m_matDatas.clear();

    const auto doc = g_StudioApp.GetCore()->GetDoc();
    bool isDocModified = doc->IsModified();
    const auto sceneEditor = doc->getSceneEditor();
    if (!sceneEditor)
        return;

    bool newMaterialSelected = false;
    for (const Q3DStudio::CFilePath &path : matDatas) {
        bool isNewFile = true;
        for (auto &oldPath : m_cachedMatDatas) {
            if (path.toQString() == oldPath.toQString()) {
                isNewFile = false;
                break;
            }
        }

        const QString relativePath = path.toQString();
        const Q3DStudio::CFilePath absolutePath
            = Q3DStudio::CFilePath::CombineBaseAndRelative(doc->GetDocumentDirectory(), path);

        QString name;
        QMap<QString, QString> values;
        QMap<QString, QMap<QString, QString>> textureValues;
        sceneEditor->getMaterialInfo(
                    absolutePath.toQString(), name, values, textureValues);

        m_matDatas.push_back({name, relativePath, values, textureValues});

        bool needRewrite = false;
        if (values.contains(QStringLiteral("path"))) {
            const QString oldPath = values[QStringLiteral("path")];
            needRewrite = oldPath != absolutePath.toQString();
            if (!QFileInfo(oldPath).exists()) {
                const auto instance = sceneEditor->getMaterial(oldPath);
                if (instance.Valid()) {
                    const QString oldName = sceneEditor->GetName(instance).toQString();
                    const QString newName = sceneEditor
                            ->getMaterialNameFromFilePath(relativePath);
                    const QString actualPath = sceneEditor
                            ->getFilePathFromMaterialName(oldName);
                    if (actualPath == oldPath) {
                        doc->queueMaterialRename(oldName, newName);
                        Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, tr("Set Name"))
                                ->setMaterialNameByPath(instance, relativePath);
                    }
                }
            }
        }

        auto material = sceneEditor->getMaterial(relativePath);
        if (isNewFile && !newMaterialSelected && !material.Valid()) {
            {
                material = Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, QString())
                        ->getOrCreateMaterial(relativePath, false);
            }
            // Several aspects of the editor are not updated correctly
            // if the data core is changed without a transaction
            // The above scope completes the transaction for creating a new material
            // Next the added undo has to be popped from the stack
            // TODO: Find a way to update the editor fully without a transaction
            g_StudioApp.GetCore()->GetCmdStack()->RemoveLastUndo();
        }

        if (material.Valid())
            sceneEditor->setMaterialValues(relativePath, values, textureValues);

        if (isNewFile && !newMaterialSelected) {
            doc->SelectDataModelObject(material);
            newMaterialSelected = true;
        }

        if (needRewrite && material.Valid())
            sceneEditor->writeMaterialFile(material, name, false, absolutePath.toQString());
    }

    if (isBasicMaterial())
        updateMatDataValues();

    sceneEditor->removeDeletedFromMaterialContainer();
    // Modified flag has to be restored because of the hidden transaction
    doc->SetModifiedFlag(isDocModified);

    m_cachedMatDatas = matDatas;
}

QString InspectorControlModel::getBasicMaterialString() const
{
    return QObject::tr("Basic Material");
}

QString InspectorControlModel::getAnimatableMaterialString() const
{
    return QObject::tr("Animatable Material");
}

QString InspectorControlModel::getReferencedMaterialString() const
{
    return QObject::tr("Referenced Material");
}

QString InspectorControlModel::getStandardMaterialString() const
{
    return QObject::tr("Standard");
}

QString InspectorControlModel::getDefaultMaterialString() const
{
    return QObject::tr("Default");
}

void InspectorControlModel::updateFontValues(InspectorControlBase *element) const
{
    // Find if there are any font items and update the values of those
    QVector<InspectorControlBase *> fontElements;
    if (element) {
        fontElements.append(element);
    } else {
        for (int row = 0; row < m_groupElements.count(); ++row) {
            auto group = m_groupElements[row];
            for (int p = 0; p < group.controlElements.count(); ++p) {
                QVariant &element = group.controlElements[p];
                InspectorControlBase *property = element.value<InspectorControlBase *>();
                if (property->m_propertyType == qt3dsdm::AdditionalMetaDataType::Font)
                    fontElements.append(property);
            }
        }
    }

    if (fontElements.size()) {
        std::vector<Q3DStudio::CString> fontNames;
        g_StudioApp.GetCore()->GetDoc()->GetProjectFonts(fontNames);
        QStringList possibleValues;
        for (const auto &fontName : fontNames)
            possibleValues.append(fontName.toQString());
        for (auto fontElement : qAsConst(fontElements)) {
            fontElement->m_values = possibleValues;
            Q_EMIT fontElement->valuesChanged();
            // Changing values resets the selected index, so pretend the value has also changed
            Q_EMIT fontElement->valueChanged();
        }
    }
}


QStringList InspectorControlModel::materialTypeValues() const
{
    QStringList values;
    values.push_back(getBasicMaterialString());
    values.push_back(getAnimatableMaterialString());
    values.push_back(getReferencedMaterialString());
    return values;
}

QStringList InspectorControlModel::shaderValues() const
{
    QStringList values;
    values.push_back(getStandardMaterialString());
    for (size_t matIdx = 0, end = m_materials.size(); matIdx < end; ++matIdx)
        values.push_back(m_materials[matIdx].m_name);
    return values;
}

QStringList InspectorControlModel::matDataValues() const
{
    QStringList values;
    QStringList names;
    const QString defaultMaterialShownName = getDefaultMaterialString();
    values.push_back(defaultMaterialShownName);
    names.push_back(defaultMaterialShownName);
    for (size_t matIdx = 0, end = m_matDatas.size(); matIdx < end; ++matIdx) {
        QString shownName = m_matDatas[matIdx].m_name;
        int slashIndex = shownName.lastIndexOf(QLatin1Char('/'));
        if (slashIndex != -1)
            shownName = shownName.mid(slashIndex + 1);
        if (names.contains(shownName))
            shownName += QLatin1String(" (") + m_matDatas[matIdx].m_relativePath + QLatin1Char(')');
        else
            names.push_back(shownName);
        values.push_back(shownName);
    }
    return values;
}

InspectorControlBase *InspectorControlModel::createMaterialTypeItem(
        Qt3DSDMInspectable *inspectable, int groupIndex)
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto instance = inspectable->GetGroupInstance(groupIndex);
    const auto bridge = studio->GetClientDataModelBridge();
    const auto type = bridge->GetObjectType(instance);

    InspectorControlBase *item = new InspectorControlBase;
    item->m_instance = instance;

    item->m_title = tr("Material Type");
    item->m_dataType = qt3dsdm::DataModelDataType::StringRef;
    item->m_propertyType = qt3dsdm::AdditionalMetaDataType::None;
    item->m_tooltip = tr("Type of material being used");

    item->m_animatable = false;

    const QStringList values = materialTypeValues();
    item->m_values = values;

    QString sourcePath = bridge->GetSourcePath(item->m_instance).toQString();

    switch (type) {
    case OBJTYPE_MATERIAL:
    case OBJTYPE_CUSTOMMATERIAL:
        item->m_value = getAnimatableMaterialString();
        break;

    case OBJTYPE_REFERENCEDMATERIAL:
        item->m_value = getReferencedMaterialString();
        if (sourcePath == bridge->getDefaultMaterialName())
            item->m_value = getBasicMaterialString();
        for (int matIdx = 0, end = int(m_matDatas.size()); matIdx < end; ++matIdx) {
            if (QString::compare(m_matDatas[matIdx].m_relativePath,
                                 sourcePath, Qt::CaseInsensitive) == 0) {
                item->m_value = getBasicMaterialString();
            }
        }
        break;
    }

    return item;
}

InspectorControlBase *InspectorControlModel::createShaderItem(
        Qt3DSDMInspectable *inspectable, int groupIndex)
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto instance = inspectable->GetGroupInstance(groupIndex);
    const auto bridge = studio->GetClientDataModelBridge();

    InspectorControlBase *item = new InspectorControlBase;
    item->m_instance = instance;

    item->m_title = tr("Shader");
    item->m_dataType = qt3dsdm::DataModelDataType::StringRef;
    item->m_propertyType = qt3dsdm::AdditionalMetaDataType::Renderable;
    item->m_tooltip = tr("Shader being used");

    item->m_animatable = false;

    const QStringList values = shaderValues();
    item->m_values = values;

    QString sourcePath = bridge->GetSourcePath(item->m_instance).toQString();

    item->m_value = values[0];
    for (int matIdx = 0, end = int(m_materials.size()); matIdx < end; ++matIdx) {
        if (m_materials[matIdx].m_relativePath == sourcePath)
            item->m_value = values[matIdx + 1];
    }

    return item;
}

InspectorControlBase *InspectorControlModel::createMatDataItem(
        Qt3DSDMInspectable *inspectable, int groupIndex)
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    const auto instance = inspectable->GetGroupInstance(groupIndex);
    const auto bridge = studio->GetClientDataModelBridge();

    InspectorControlBase *item = new InspectorControlBase;
    item->m_instance = instance;

    item->m_title = tr("Source Material");
    item->m_dataType = qt3dsdm::DataModelDataType::StringRef;
    item->m_propertyType = qt3dsdm::AdditionalMetaDataType::ObjectRef;
    item->m_tooltip = tr("Source material definitions used");

    item->m_animatable = false;

    const QStringList values = matDataValues();
    item->m_values = values;

    QString sourcePath = bridge->GetSourcePath(item->m_instance).toQString();

    item->m_value = getDefaultMaterialString();
    for (int matIdx = 0, end = int(m_matDatas.size()); matIdx < end; ++matIdx) {
        if (QString::compare(m_matDatas[matIdx].m_relativePath,
                             sourcePath, Qt::CaseInsensitive) == 0) {
            item->m_value = values[matIdx + 1]; // + 1 for Default basic material
        }
    }

    return item;
}

InspectorControlBase* InspectorControlModel::createItem(Qt3DSDMInspectable *inspectable,
                                                        Q3DStudio::Qt3DSDMInspectorRow *row,
                                                        int groupIndex)
{
    return createItem(inspectable, row->GetMetaDataPropertyInfo(), groupIndex);
}

InspectorControlBase* InspectorControlModel::createItem(Qt3DSDMInspectable *inspectable,
                                                        const qt3dsdm::SMetaDataPropertyInfo &metaProperty,
                                                        int groupIndex)
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    if (metaProperty.m_IsHidden)
        return nullptr;

    Q3DStudio::CString title;
    title.Assign(metaProperty.m_FormalName.c_str());
    if (title.IsEmpty())
        title.Assign(metaProperty.m_Name.c_str());

    // Hide name for basic materials
    if (title == "Name" && isBasicMaterial())
        return nullptr;

    InspectorControlBase *item = new InspectorControlBase;
    item->m_property = metaProperty.m_Property;
    item->m_instance = inspectable->GetGroupInstance(groupIndex);
    item->m_metaProperty = metaProperty;

    item->m_title = title.toQString();

    const auto propertySystem = studio->GetPropertySystem();
    item->m_dataType = propertySystem->GetDataType(metaProperty.m_Property);
    item->m_propertyType = static_cast<qt3dsdm::AdditionalMetaDataType::Value>
            (propertySystem->GetAdditionalMetaDataType(item->m_instance, metaProperty.m_Property));
    item->m_tooltip = Q3DStudio::CString(metaProperty.m_Description.c_str()).toQString();
    // \n is parsed as \\n from the material and effect files. Replace them to fix multi-line
    // tooltips
    item->m_tooltip.replace(QStringLiteral("\\n"), QStringLiteral("\n"));

    item->m_animatable = metaProperty.m_Animatable &&
            studio->GetAnimationSystem()->IsPropertyAnimatable(item->m_instance,
                                                               metaProperty.m_Property);
    // If a property is animatable, it should be controllable in addition to
    // properties explicitly set as controllable in metadata
    item->m_controllable = item->m_animatable || metaProperty.m_Controllable;

    // disable IBL Override for reference materials
    if (item->m_title == QLatin1String("IBL Override") && studio->GetClientDataModelBridge()
                                ->GetObjectType(item->m_instance) == OBJTYPE_REFERENCEDMATERIAL) {
        item->m_enabled = false;
    }
    auto signalProvider = studio->GetFullSystemSignalProvider();
    if (item->m_animatable) {
        item->m_animated = studio->GetAnimationSystem()->IsPropertyAnimated(item->m_instance,
                                                                            metaProperty.m_Property);

        // Update the Animate Toggle on undo/redo
        item->m_connections.push_back(signalProvider->ConnectAnimationCreated(
                                          std::bind(&InspectorControlModel::updateAnimateToggleState,
                                                    this, item)));

        item->m_connections.push_back(signalProvider->ConnectAnimationDeleted(
                                          std::bind(&InspectorControlModel::updateAnimateToggleState,
                                                    this, item)));
    }

    if (item->m_controllable) {
        // Set the name of current controller
        item->m_controller = currentControllerValue(item->m_instance, item->m_property);
        // Update UI icon state and tooltip
        updateControlledToggleState(item);
        item->m_connections.push_back(signalProvider->ConnectControlledToggled(
            std::bind(&InspectorControlModel::updateControlledToggleState,
                      this, item)));
    }

    // synchronize the value itself
    updatePropertyValue(item);
    return item;
}

qt3dsdm::SValue InspectorControlModel::currentPropertyValue(long instance, int handle) const
{
    qt3dsdm::SValue value;
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    auto studioSystem = doc->GetStudioSystem();
    const auto propertySystem = studioSystem->GetPropertySystem();
    propertySystem->GetInstancePropertyValue(instance, handle,  value);

    return  value;
}

QString InspectorControlModel::currentControllerValue(long instance, int handle) const
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    auto studio = doc->GetStudioSystem();

    qt3dsdm::SValue currPropVal = currentPropertyValue(
                instance, studio->GetPropertySystem()->GetAggregateInstancePropertyByName(
                    instance, qt3dsdm::TCharStr(L"controlledproperty")));
    if (!currPropVal.empty()) {
        Q3DStudio::CString currPropValStr
                = qt3dsdm::get<qt3dsdm::TDataStrPtr>(currPropVal)->GetData();

        Q3DStudio::CString propName
                = studio->GetPropertySystem()->GetName(handle).c_str();

        // Datainput controller name is always prepended with "$". Differentiate
        // between datainput and property that has the same name by searching specifically
        // for whitespace followed by property name.
        long propNamePos = currPropValStr.find(" " + propName);
        if ((propNamePos != currPropValStr.ENDOFSTRING) && (propNamePos != 0)) {
            long posCtrlr = currPropValStr.substr(0, propNamePos).ReverseFind("$");

            // adjust pos if this is the first controller - property pair
            // in controlledproperty
            if (posCtrlr < 0)
                posCtrlr = 0;

            // remove $
            posCtrlr++;
            return currPropValStr.substr(posCtrlr, propNamePos - posCtrlr).toQString();
        }
        else
            return {};
    } else {
        return {};
    }
}

void InspectorControlModel::updateControlledToggleState(InspectorControlBase* inItem) const
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    // toggle if controlledproperty contains the name of this property
    qt3dsdm::SValue currPropVal = currentPropertyValue(
        inItem->m_instance, studio->GetPropertySystem()->GetAggregateInstancePropertyByName(
            inItem->m_instance, qt3dsdm::TCharStr(L"controlledproperty")));
    Q3DStudio::CString currPropValStr;
    if (!currPropVal.empty())
        currPropValStr = qt3dsdm::get<qt3dsdm::TDataStrPtr>(currPropVal)->GetData();
    // Restore original tool tip from metadata when turning control off
    if (!currPropValStr.size()) {
        inItem->m_controlled = false;
        inItem->m_controller = "";
    } else {
       Q3DStudio::CString propName
           = studio->GetPropertySystem()->GetName(inItem->m_property).c_str();
       // Search specifically for whitespace followed with registered property name.
       // This avoids finding datainput with same name as the property, as datainput
       // name is always prepended with "$"
       long propNamePos = currPropValStr.find(" " + propName);
       if ((propNamePos == currPropValStr.ENDOFSTRING)
           && (propNamePos != 0)) {
           inItem->m_controlled = false;
           inItem->m_controller = "";
       } else {
           inItem->m_controlled = true;
           // controller name is prepended with "$" to differentiate from property
           // with same name. Reverse find specifically for $.
           long posCtrlr = currPropValStr.substr(0, propNamePos).ReverseFind("$");

           // this is the first controller - property pair in controlledproperty
           if (posCtrlr < 0)
               posCtrlr = 0;

           // remove $ from controller name for showing it in UI
           posCtrlr++;
           const QString ctrlName = currPropValStr.substr(
               posCtrlr, propNamePos - posCtrlr).toQString();

           inItem->m_controller = ctrlName;
       }
    }

    Q_EMIT inItem->tooltipChanged();
    // Emit signal always to trigger updating of controller name in UI
    // also when user switches from one controller to another
    Q_EMIT inItem->controlledChanged();
}

void InspectorControlModel::updateAnimateToggleState(InspectorControlBase* inItem)
{
    const auto studio = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem();
    bool animated = studio->GetAnimationSystem()->IsPropertyAnimated(inItem->m_instance,
                                                                     inItem->m_property);
    if (animated != inItem->m_animated) {
        inItem->m_animated = animated;
        Q_EMIT inItem->animatedChanged();
    }
}

bool InspectorControlModel::isTreeRebuildRequired(CInspectableBase* inspectBase)
{
    if (inspectBase != m_inspectableBase || !inspectBase)
        return true;

    long theCount = m_inspectableBase->GetGroupCount();
    auto refMaterial = getReferenceMaterial(inspectBase);
    if (refMaterial != m_refMaterial) {
        m_refMaterial = refMaterial;
        return true;
    }
    long refMaterialGroupCount = 0;
    if (refMaterial.Valid())
        refMaterialGroupCount = 1; // Only the last group of the refMaterial is used

    if (m_groupElements.size() != theCount + refMaterialGroupCount)
        return true;

    for (long theIndex = 0; theIndex < theCount; ++theIndex) {
        const CInspectorGroup *theInspectorGroup = m_inspectableBase->GetGroup(theIndex);
        if (m_groupElements.at(theIndex).groupTitle != theInspectorGroup->GetName())
            return true;
    }

    return false;
}

bool InspectorControlModel::isGroupRebuildRequired(CInspectableBase* inspectable, int theIndex) const
{
    Q_ASSERT(theIndex < m_groupElements.size());
    const CInspectorGroup *theInspectorGroup = inspectable->GetGroup(theIndex);
    const auto existingGroup = m_groupElements.at(theIndex);
    if (existingGroup.groupTitle != theInspectorGroup->GetName())
        return true;

    if (const auto cdmInspectable = dynamic_cast<Qt3DSDMInspectable *>(inspectable)) {
        int existingIndex = 0;
        if (const auto group = dynamic_cast<const Qt3DSDMInspectorGroup *>(theInspectorGroup)) {
            const auto materialGroup
                    = dynamic_cast<const Qt3DSDMMaterialInspectorGroup *>(group);
            if (materialGroup && materialGroup->isMaterialGroup()) {
                auto i = existingGroup.controlElements.at(existingIndex++).value<InspectorControlBase*>();
                if (i->m_instance != cdmInspectable->GetGroupInstance(theIndex))
                    return true;
                if (!isInsideMaterialContainer())
                    existingIndex++; // Add material type dropdown to existing elements
            }

            if ((existingGroup.controlElements.size() - existingIndex) != group->GetRows().size())
                return true;

            for (const auto row : group->GetRows()) {
                auto i = existingGroup.controlElements.at(existingIndex++).value<InspectorControlBase*>();
                if (i->m_instance != cdmInspectable->GetGroupInstance(theIndex))
                    return true;

                if (i->m_property != row->GetMetaDataPropertyInfo().m_Property)
                    return true;
            }
        }
    }

    return false;
}

auto InspectorControlModel::computeTree(CInspectableBase* inspectBase)
    -> QVector<GroupInspectorControl>
{
    QVector<GroupInspectorControl> result;

    if (inspectBase) {
        bool isMaterialFromFile = false;

        const auto bridge = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()
                ->GetClientDataModelBridge();;

        qt3dsdm::Qt3DSDMInstanceHandle instance;
        if (const auto inspectable = dynamic_cast<Qt3DSDMInspectable *>(inspectBase))
            instance = inspectable->GetGroupInstance(0);

        if (instance.Valid())
            isMaterialFromFile = bridge->isInsideMaterialContainer(instance);

        long theCount = inspectBase->GetGroupCount();
        for (long theIndex = 0; theIndex < theCount; ++theIndex) {
            result.append(computeGroup(inspectBase, theIndex, isMaterialFromFile, false));
        }

        if (isDefaultMaterial() && result.size() > 0) {
            result[result.size() - 1].groupInfo = tr("\nDefault material cannot be edited.\n\n"
                                                     "Create new or import material, then apply.");
        }

        //Show original material properties for referenced materials
        auto refMaterial = getReferenceMaterial(inspectBase);
        if (refMaterial.Valid()) {
            auto refMaterialInspectable = g_StudioApp.getInspectableFromInstance(refMaterial);
            if (refMaterialInspectable) {
                QString materialSrcPath;
                if (instance.Valid())
                    materialSrcPath = bridge->GetSourcePath(instance).toQString();

                if (materialSrcPath != bridge->getDefaultMaterialName()
                        && bridge->GetSourcePath(refMaterial) != Q3DStudio::CString::fromQString(
                            bridge->getDefaultMaterialName())) {
                    result.append(computeGroup(refMaterialInspectable,
                                               refMaterialInspectable->GetGroupCount() - 1,
                                               true, true));
                }
            }
        }
    }

    return result;
}

auto InspectorControlModel::computeGroup(CInspectableBase* inspectable,
                                         int theIndex, bool disableAnimation, bool isReference)
    -> GroupInspectorControl
{
    CInspectorGroup* theInspectorGroup = inspectable->GetGroup(theIndex);
    GroupInspectorControl result;
    result.groupTitle = theInspectorGroup->GetName();
    result.groupInfo.clear();

    if (isReference)
        result.groupTitle += tr(" (Reference)");

    if (const auto cdmInspectable = dynamic_cast<Qt3DSDMInspectable *>(inspectable)) {
        if (const auto group = dynamic_cast<Qt3DSDMInspectorGroup *>(theInspectorGroup)) {
            const auto materialGroup
                    = dynamic_cast<Qt3DSDMMaterialInspectorGroup *>(group);
            bool isMatData = isBasicMaterial(cdmInspectable);
            if (materialGroup && materialGroup->isMaterialGroup()) {
                InspectorControlBase *item = nullptr;

                if (!isInsideMaterialContainer(cdmInspectable) && !isReference) {
                    item = createMaterialTypeItem(cdmInspectable, theIndex);
                    if (item)
                        result.controlElements.push_back(QVariant::fromValue(item));
                }

                if (isAnimatableMaterial(cdmInspectable)) {
                    item = createShaderItem(cdmInspectable, theIndex);
                    if (item)
                        result.controlElements.push_back(QVariant::fromValue(item));
                } else if (isMatData) {
                    item = createMatDataItem(cdmInspectable, theIndex);
                    if (item)
                        result.controlElements.push_back(QVariant::fromValue(item));
                }
            }

            const auto sceneEditor = g_StudioApp.GetCore()->GetDoc()->getSceneEditor();
            for (const auto row : group->GetRows()) {
                InspectorControlBase *item = createItem(cdmInspectable, row, theIndex);
                if (!item)
                    continue;

                if (disableAnimation)
                    item->m_animatable = false;

                if (!isMatData || item->m_title != getReferencedMaterialString())
                    result.controlElements.push_back(QVariant::fromValue(item));
            }
        }
    } else if (dynamic_cast<SGuideInspectableImpl *>(inspectable)) {
        //KDAB_FIXME: load row element (How ?)
    }

    return result;
}

void InspectorControlModel::rebuildTree()
{
    beginResetModel();
    QVector<QObject *> deleteVector;
    for (int i = 0; i < m_groupElements.count(); ++i) {
        auto group = m_groupElements[i];
        for (int p = 0; p < group.controlElements.count(); ++p)
            deleteVector.append(group.controlElements[p].value<QObject *>());
    }
    m_groupElements = computeTree(m_inspectableBase);
    endResetModel();

    // Clean the old objects after reset is done so that qml will not freak out about null pointers
    for (int i = 0; i < deleteVector.count(); ++i)
        deleteVector[i]->deleteLater();
}

int InspectorControlModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return m_groupElements.count();
}

void InspectorControlModel::updatePropertyValue(InspectorControlBase *element) const
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    auto studioSystem = doc->GetStudioSystem();
    const auto propertySystem = studioSystem->GetPropertySystem();
    auto bridge = studioSystem->GetClientDataModelBridge();
    qt3dsdm::SValue value;
    const auto instance = element->m_instance;
    if (!propertySystem->HandleValid(instance))
        return;
    propertySystem->GetInstancePropertyValue(instance, element->m_property, value);

    if (value.getType() == qt3dsdm::DataModelDataType::None)
        return;

    const auto metaDataProvider = doc->GetStudioSystem()->GetActionMetaData();
    const auto info = metaDataProvider->GetMetaDataPropertyInfo(
                metaDataProvider->GetMetaDataProperty(instance, element->m_property));
    bool skipEmits = false;
    switch (element->m_dataType) {
    case qt3dsdm::DataModelDataType::String: {
        QString stringValue = qt3dsdm::get<QString>(value);
        if (bridge->isInsideMaterialContainer(element->m_instance)) {
            int index = stringValue.lastIndexOf(QLatin1Char('/'));
            if (index != -1)
                stringValue = stringValue.mid(index + 1);
        }
        element->m_value = stringValue;
    } // intentional fall-through for other String-derived datatypes
    case qt3dsdm::DataModelDataType::StringOrInt:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::StringList) {
            QStringList stringlist = qt3dsdm::get<QStringList>(info->m_MetaDataData);
            auto slideSystem = studioSystem->GetSlideSystem();

            if (element->m_title == QStringLiteral("Play Mode")) {
                std::pair<bool, bool> slideData(
                    getSlideCharacteristics(element->m_instance, *studioSystem->GetSlideCore(),
                                            *slideSystem));
                bool hasNextSlide(slideData.first);
                bool hasPreviousSlide(slideData.second);
                if (!hasNextSlide && !hasPreviousSlide)
                    stringlist.removeAll("Play Through To...");
            } else if (element->m_title == QStringLiteral("Play Through To")) {
                // the code duplication is intentional as we may ask for slide characteristics
                // only if the property refers to slides
                std::pair<bool, bool> slideData(
                    getSlideCharacteristics(element->m_instance, *studioSystem->GetSlideCore(),
                                            *slideSystem));
                bool hasNextSlide(slideData.first);
                bool hasPreviousSlide(slideData.second);
                if (!hasNextSlide)
                    stringlist.removeAll("Next");
                if (!hasPreviousSlide)
                    stringlist.removeAll("Previous");

                auto itemCount = stringlist.count();
                QString listOpt;
                int selectedSlideHandle = 0;
                int selectedIndex = -1;
                qt3dsdm::SStringOrInt stringOrInt = qt3dsdm::get<qt3dsdm::SStringOrInt>(value);
                if (stringOrInt.GetType() == qt3dsdm::SStringOrIntTypes::String)
                    listOpt = QString::fromWCharArray(qt3dsdm::get<qt3dsdm::TDataStrPtr>
                                                      (stringOrInt.m_Value)->GetData());
                else
                    selectedSlideHandle = qt3dsdm::get<long>(stringOrInt.m_Value);

                selectedIndex = stringlist.indexOf(listOpt);
                // Add the slide names (exclude the master slide)
                auto slideHandle = slideSystem->GetSlideByInstance(instance);
                auto masterSlide = slideSystem->GetMasterSlide(slideHandle);
                long slideCount = (long)slideSystem->GetSlideCount(masterSlide);
                for (long slideIndex = 1; slideIndex < slideCount; ++slideIndex) {
                    auto currentSlide = slideSystem->GetSlideByIndex(masterSlide, slideIndex);
                    auto currentInstance = slideSystem->GetSlideInstance(currentSlide);

                    QString slideName = bridge->GetName(currentInstance).toQString();
                    //hack to add a separator before the item
                    if (slideIndex == 1 && itemCount > 0)
                        slideName += "|separator";
                    stringlist.append(slideName);

                    if (currentSlide.GetHandleValue() == selectedSlideHandle)
                        selectedIndex = slideIndex + itemCount - 1;
                }

                element->m_value = QString(selectedIndex > 0 ? stringlist[selectedIndex]
                                   : stringlist.first()).replace("|separator", "");
            }
            element->m_values = stringlist;
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Import) {
            QStringList stringlist = qt3dsdm::get<QStringList>(info->m_MetaDataData);
            element->m_values = stringlist;
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Renderable) {
            element->m_values = renderableItems();
            if (element->m_value.toString().isEmpty())
                element->m_value = element->m_values.toStringList().at(0);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::MultiLine) {
            element->m_value = qt3dsdm::get<QString>(value);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Font) {
            updateFontValues(element);
            skipEmits = true; // updateFontValues handles emits in correct order
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Mesh) {
            QString meshValue = qt3dsdm::get<QString>(value);
            Q3DStudio::CFilePath theSelectionItem(Q3DStudio::CString::fromQString(meshValue));
            Q3DStudio::CFilePath theSelectionWithoutId(theSelectionItem.filePath());
            QString theSelectionWithoutIdName = theSelectionWithoutId.GetFileName().toQString();
            if (theSelectionWithoutIdName.size())
                element->m_value = theSelectionWithoutIdName;
            else
                element->m_value = theSelectionItem.GetIdentifier().toQString();
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Texture) {
            QFileInfo fileInfo(qt3dsdm::get<QString>(value));
            element->m_value = fileInfo.fileName();
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::PathBuffer) {
            element->m_value = qt3dsdm::get<QString>(value);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::String) {
            // Basic string already handled, do not warn about that.
            // If we hit any other datatypes then give a warning
        } else {
            qWarning() << "KDAB_TODO: InspectorControlModel::updatePropertyValue: need to implement:"
                       << element->m_dataType << " element->m_propertyType : "
                       << element->m_propertyType;
        }
        break;
    case qt3dsdm::DataModelDataType::StringRef:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::None) {
            element->m_value = qt3dsdm::get<QString>(value);
        }
        break;
    case qt3dsdm::DataModelDataType::Bool:
        element->m_value = qt3dsdm::get<bool>(value);
        break;
    case qt3dsdm::DataModelDataType::Long4:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Image) {
            qt3dsdm::Option<qt3dsdm::SLong4> guid = qt3dsdm::get<qt3dsdm::SLong4>(value);
            qt3dsdm::Qt3DSDMInstanceHandle imageInstance = doc->GetDocumentReader()
                    .GetInstanceForGuid(guid);
            if (imageInstance.Valid()) {
                Q3DStudio::CString path = doc->GetDocumentReader().GetSourcePath(imageInstance);
                Q3DStudio::CFilePath relPath(path);
                element->m_value = QVariant(relPath.GetFileName().toQString());
            } else {
                element->m_value = QVariant(QString());
            }
        } else {
            qWarning() << "KDAB_TODO: InspectorControlModel::updatePropertyValue: need to implement:"
                       << element->m_dataType << " " << element->m_title;
        }
        break;
    case qt3dsdm::DataModelDataType::Long:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Range) {
            element->m_value = qt3dsdm::get<int>(value);
            const qt3dsdm::SMetaDataRange ranges = qt3dsdm::get<qt3dsdm::SMetaDataRange>(info->m_MetaDataData);
            const QList<double> rangesValues{ranges.m_Min, ranges.m_Max};
            element->m_values = QVariant::fromValue<QList<double> >(rangesValues);
        }
        else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::ShadowMapResolution) {
            element->m_value = qt3dsdm::get<int>(value);
        } else {
            qWarning() << "KDAB_TODO: InspectorControlModel::updatePropertyValue: need to implement:"
                       << element->m_dataType;
        }
        break;
    case qt3dsdm::DataModelDataType::Float3:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Color) {
            element->m_value = qt3dsdm::get<QColor>(value);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Rotation) {
            const QVector3D theFloat3 = qt3dsdm::get<QVector3D>(value);
            const QList<double> float3Values{theFloat3.x(), theFloat3.y(), theFloat3.z()};
            element->m_values = QVariant::fromValue<QList<double> >(float3Values);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::None) {
            const QVector3D theFloat3 = qt3dsdm::get<QVector3D>(value);
            const QList<double> float3Values{theFloat3.x(), theFloat3.y(), theFloat3.z()};
            element->m_values = QVariant::fromValue<QList<double> >(float3Values);
        }
        break;
    case qt3dsdm::DataModelDataType::Float2:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::None) {
            const QVector2D theFloat2 = qt3dsdm::get<QVector2D>(value);
            const QList<double> float2Values{theFloat2.x(), theFloat2.y()};
            element->m_values = QVariant::fromValue<QList<double> >(float2Values);
        } else {
            qWarning() << "TODO: InspectorControlModel::updatePropertyValue: need to implement:"
                       << element->m_dataType << element->m_propertyType;
        }
        break;
    case qt3dsdm::DataModelDataType::Float:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::None) {
            element->m_value = qt3dsdm::get<float>(value);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::Range) {
            element->m_value = qt3dsdm::get<float>(value);
            const qt3dsdm::SMetaDataRange ranges = qt3dsdm::get<qt3dsdm::SMetaDataRange>(info->m_MetaDataData);
            const QList<double> rangesValues{ranges.m_Min, ranges.m_Max};
            element->m_values = QVariant::fromValue<QList<double> >(rangesValues);
        } else if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::FontSize) {
            element->m_value = qt3dsdm::get<float>(value);
        }
        break;
    case qt3dsdm::DataModelDataType::ObjectRef:
        if (element->m_propertyType == qt3dsdm::AdditionalMetaDataType::ObjectRef) {
            IObjectReferenceHelper *objRefHelper = doc->GetDataModelObjectReferenceHelper();
            if (objRefHelper) {
                qt3dsdm::Qt3DSDMInstanceHandle refInstance = objRefHelper->Resolve(value, instance);
                QString refName = objRefHelper->LookupObjectFormalName(refInstance).toQString();
                if (bridge->IsReferencedMaterialInstance(instance) && !refName.isEmpty()) {
                    // get the material's object name (parent)
                    auto parentInstance = bridge->GetParentInstance(refInstance);
                    qt3dsdm::SValue vParent;
                    propertySystem->GetInstancePropertyValue(parentInstance,
                                        bridge->GetObjectDefinitions().m_Named.m_NameProp, vParent);
                    QString parentName = qt3dsdm::get<QString>(vParent);
                    refName.append(QLatin1String(" (") + parentName + QLatin1String(")"));
                }
                element->m_value = refName;
            }
        }
        break;
    default:
        qWarning() << "TODO: InspectorControlModel::updatePropertyValue: I've no idea how to handle this datatype"
                   << element->m_dataType;
        break;
    }

    if (!skipEmits) {
        Q_EMIT element->valueChanged();
        Q_EMIT element->valuesChanged();
    }

    // Controlled state must be manually set after undo operations,
    // as only the "controlledproperty" is restored in undo,
    // not the controlled flag nor the tooltip
    if (element->m_controllable)
          updateControlledToggleState(element);
}

void InspectorControlModel::refreshRenderables()
{
    for (int row = 0; row < m_groupElements.count(); ++row) {
        auto group = m_groupElements[row];
        for (int p = 0; p < group.controlElements.count(); ++p) {
            QVariant& element = group.controlElements[p];
            InspectorControlBase *property = element.value<InspectorControlBase *>();
            if (property->m_property.Valid()
                    && property->m_propertyType == qt3dsdm::AdditionalMetaDataType::Renderable) {
                updatePropertyValue(property);
            }
        }
    }
}

void InspectorControlModel::refreshTree()
{
    //check if the structure has changed
    if (isTreeRebuildRequired(m_inspectableBase)) {
        rebuildTree();
    } else {
        // group structure is intact, let's walk to see which rows changed
        QVector<QObject *> deleteVector;
        long theCount = m_inspectableBase->GetGroupCount();
        for (long theIndex = 0; theIndex < theCount; ++theIndex) {
            if (isGroupRebuildRequired(m_inspectableBase, theIndex)) {
                auto group = m_groupElements[theIndex];
                for (int p = 0; p < group.controlElements.count(); ++p)
                    deleteVector.append(group.controlElements[p].value<QObject *>());
                m_groupElements[theIndex] = computeGroup(m_inspectableBase, theIndex);
                Q_EMIT dataChanged(index(theIndex), index(theIndex));
            }
        }
    }
}

void InspectorControlModel::refresh()
{
    refreshTree();
    // update values
    for (int row = 0; row < m_groupElements.count(); ++row) {
        auto group = m_groupElements[row];
        for (int p = 0; p < group.controlElements.count(); ++p) {
            QVariant& element = group.controlElements[p];
            InspectorControlBase *property = element.value<InspectorControlBase *>();
            if (property->m_property.Valid()) {
                updatePropertyValue(property);
                updateControlledToggleState(property);
            }
        }
    }
    Q_EMIT dataChanged(index(0), index(rowCount() - 1));
}

void InspectorControlModel::saveIfMaterial(qt3dsdm::Qt3DSDMInstanceHandle instance)
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto sceneEditor = doc->getSceneEditor();

    const auto studio = doc->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();
    EStudioObjectType type = bridge->GetObjectType(instance);

    auto material = instance;
    if (type == EStudioObjectType::OBJTYPE_IMAGE)
        material = sceneEditor->GetParent(instance);

    if (!material.Valid())
        return;

    const auto refMaterial = bridge->getMaterialReference(material);
    if (refMaterial.Valid())
        material = refMaterial;

    if (!bridge->isInsideMaterialContainer(material))
        return;

    type = bridge->GetObjectType(material);

    if (type == EStudioObjectType::OBJTYPE_MATERIAL
        || type == EStudioObjectType::OBJTYPE_CUSTOMMATERIAL) {
        qt3dsdm::SValue value;
        studio->GetPropertySystem()->GetInstancePropertyValue(
            material, bridge->GetObjectDefinitions().m_Named.m_NameProp, value);
        qt3dsdm::TDataStrPtr namePtr(qt3dsdm::get<qt3dsdm::TDataStrPtr>(value));
        QString materialName = QString::fromWCharArray(namePtr->GetData(), namePtr->GetLength());
        QString sourcePath;
        for (int i = 0; i < m_matDatas.size(); ++i) {
            if (QString::compare(m_matDatas[i].m_name, materialName, Qt::CaseInsensitive) == 0) {
                sourcePath = doc->GetDocumentDirectory().toQString() + QLatin1Char('/')
                        + m_matDatas[i].m_relativePath;
            }
        }

        sceneEditor->writeMaterialFile(material, materialName,
                                       sourcePath.isEmpty(), sourcePath);
    }
}

void InspectorControlModel::setMaterialTypeValue(long instance, int handle, const QVariant &value)
{
    Q_UNUSED(handle)

    const QString typeValue = value.toString();
    Q3DStudio::CString v;

    const auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
    const auto sceneEditor = doc->getSceneEditor();
    const Q3DStudio::CString oldType = sceneEditor->GetObjectTypeName(instance);
    qt3dsdm::Qt3DSDMInstanceHandle refMaterial;
    if (oldType == "ReferencedMaterial")
        refMaterial = bridge->getMaterialReference(instance);

    bool changeMaterialFile = false;
    bool canCopyProperties = false;
    if (typeValue == getAnimatableMaterialString()) {
        v = Q3DStudio::CString("Standard Material");
        if (refMaterial.Valid()) {
            const auto refSourcePath = bridge->GetSourcePath(refMaterial);
            for (auto &material : m_materials) {
                if (refSourcePath.toQString() == material.m_relativePath) {
                    v = Q3DStudio::CString::fromQString(material.m_relativePath);
                    break;
                }
            }
        }
        canCopyProperties = true;
    } else if (typeValue == getBasicMaterialString()) {
        v = Q3DStudio::CString("Referenced Material");
        changeMaterialFile = true;
    } else if (typeValue == getReferencedMaterialString()) {
        v = Q3DStudio::CString("Referenced Material");
    }

    Q3DStudio::ScopedDocumentEditor scopedEditor(
                Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, tr("Set Material Type")));

    scopedEditor->SetMaterialType(instance, v);

    if (refMaterial.Valid() && canCopyProperties) {
        const Q3DStudio::CString newType = sceneEditor->GetObjectTypeName(instance);
        const Q3DStudio::CString refType = sceneEditor->GetObjectTypeName(refMaterial);
        if (refType == newType)
            scopedEditor->copyMaterialProperties(refMaterial, instance);

        if (bridge->isInsideMaterialContainer(refMaterial)) {
            const auto name = scopedEditor->GetName(instance);
            if (!name.toQString().endsWith(QLatin1String("_animatable")))
                scopedEditor->SetName(instance, name + "_animatable");
        }
    }

    if (changeMaterialFile) {
        scopedEditor->setMaterialProperties(instance, Q3DStudio::CString::fromQString(
                                                bridge->getDefaultMaterialName()), {}, {});

        // Select the original instance again since potentially creating a material selects the
        // created one
        doc->SelectDataModelObject(instance);

        rebuildTree(); // Hack to mimic value changing behavior of the type selector
    }

    saveIfMaterial(instance);
}

void InspectorControlModel::setShaderValue(long instance, int handle, const QVariant &value)
{
    const QString typeValue = value.toString();
    Q3DStudio::CString v("Standard Material");
    for (size_t matIdx = 0, end = m_materials.size(); matIdx < end; ++matIdx) {
        if (m_materials[matIdx].m_name == typeValue)
            v = Q3DStudio::CString::fromQString(m_materials[matIdx].m_relativePath);
    }

    const auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, QObject::tr("Set Material Type"))
            ->SetMaterialType(instance, v);

    const auto dispatch = g_StudioApp.GetCore()->GetDispatch();
    QVector<qt3dsdm::Qt3DSDMInstanceHandle> refMats;
    doc->getSceneReferencedMaterials(doc->GetSceneInstance(), refMats);
    for (auto &refMat : qAsConst(refMats)) {
        const auto origMat = bridge->getMaterialReference(refMat);
        if (origMat.Valid() && (long)origMat == instance)
            dispatch->FireImmediateRefreshInstance(refMat);
    }

    saveIfMaterial(instance);
}

void InspectorControlModel::setMatDataValue(long instance, int handle, const QVariant &value)
{
    Q_UNUSED(handle);
    const QString typeValue = value.toString();
    Q3DStudio::CString v;
    QString name;
    Q3DStudio::CString srcPath;
    QMap<QString, QString> values;
    QMap<QString, QMap<QString, QString>> textureValues;

    const auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();

    bool changeMaterialFile = false;
    if (typeValue == getDefaultMaterialString()) {
        v = Q3DStudio::CString("Referenced Material");
        name = bridge->getDefaultMaterialName();
        srcPath = Q3DStudio::CString::fromQString(name);
        changeMaterialFile = true;
    } else {
        const auto sceneEditor = doc->getSceneEditor();
        for (size_t matIdx = 0, end = m_matDatas.size(); matIdx < end; ++matIdx) {
            QString shownName = m_matDatas[matIdx].m_name;
            int slashIndex = shownName.lastIndexOf(QLatin1Char('/'));
            if (slashIndex != -1)
                shownName = shownName.mid(slashIndex + 1);
            if (QString::compare(shownName + QLatin1String(" (")
                    + m_matDatas[matIdx].m_relativePath + QLatin1Char(')'),
                                 typeValue, Qt::CaseInsensitive) == 0
                    || QString::compare(shownName, typeValue, Qt::CaseInsensitive) == 0) {
                v = Q3DStudio::CString("Referenced Material");
                changeMaterialFile = true;
                name = m_matDatas[matIdx].m_name;
                srcPath = Q3DStudio::CString::fromQString(m_matDatas[matIdx].m_relativePath);
                const auto material = sceneEditor->getMaterial(srcPath.toQString());
                if (material.Valid()) {
                    // Get the correct case source path
                    const auto absPath = sceneEditor->getFilePathFromMaterialName(
                                sceneEditor->GetName(material).toQString());
                    const auto relPath = QDir(doc->GetDocumentDirectory().toQString())
                            .relativeFilePath(absPath);
                    srcPath = Q3DStudio::CString::fromQString(relPath);
                }
                values = m_matDatas[matIdx].m_values;
                textureValues = m_matDatas[matIdx].m_textureValues;
                break;
            }
        }
    }

    if (changeMaterialFile) {
        {
            Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, QString())
                    ->setMaterialValues(srcPath.toQString(), values, textureValues);
        }
        // Several aspects of the editor are not updated correctly
        // if the data core is changed without a transaction
        // The above scope completes the transaction for creating a new material
        // Next the added undo has to be popped from the stack
        // TODO: Find a way to update the editor fully without a transaction
        g_StudioApp.GetCore()->GetCmdStack()->RemoveLastUndo();
    }

    Q3DStudio::ScopedDocumentEditor scopedEditor(
                Q3DStudio::SCOPED_DOCUMENT_EDITOR(*doc, tr("Set Material Type")));
    scopedEditor->SetMaterialType(instance, v);

    if (changeMaterialFile) {
        scopedEditor->setMaterialSourcePath(instance, srcPath);
        scopedEditor->setMaterialReferenceByPath(instance, srcPath.toQString());

        // Select original instance again since potentially
        // creating a material selects the created one
        doc->SelectDataModelObject(instance);

        rebuildTree(); // Hack to mimic value changing behavior of the type selector
    }

    saveIfMaterial(instance);
}

void InspectorControlModel::setRenderableValue(long instance, int handle, const QVariant &value)
{
    qt3dsdm::SValue oldValue = currentPropertyValue(instance, handle);

    QString v = value.toString();
    if (v == QObject::tr("No renderable item"))
        v = QString();

    if (v == qt3dsdm::get<QString>(oldValue))
        return;

    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*g_StudioApp.GetCore()->GetDoc(), QObject::tr("Set Property"))
            ->SetInstancePropertyValueAsRenderable(instance, handle,
                                                   Q3DStudio::CString::fromQString(v));
}

void InspectorControlModel::setPropertyValue(long instance, int handle, const QVariant &value,
                                             bool commit)
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    const auto studio = doc->GetStudioSystem();
    const auto bridge = studio->GetClientDataModelBridge();
    // Name property needs special handling
    if (handle == bridge->GetNameProperty()) {
        // Ignore preview of name property change
        if (!commit)
            return;

        m_modifiedProperty.first = 0;
        m_modifiedProperty.second = 0;
        m_previouslyCommittedValue = {};

        Q3DStudio::CString currentName = bridge->GetName(instance, true);
        Q3DStudio::CString newName = Q3DStudio::CString::fromQString(value.toString());
        if (!newName.IsEmpty()) {
            if (bridge->isInsideMaterialContainer(instance)
                    && (newName.Find('/') != Q3DStudio::CString::ENDOFSTRING
                        || newName.Find('#') != Q3DStudio::CString::ENDOFSTRING)) {
                return;
            }
            qt3dsdm::Qt3DSDMInstanceHandle parentInstance = bridge->GetParentInstance(instance);

            if (parentInstance == doc->GetSceneInstance()
                    && newName.toQString() == bridge->getMaterialContainerName()) {
                QString theTitle = QObject::tr("Rename Object Error");
                QString theString = bridge->getMaterialContainerName()
                        + QObject::tr(" is a reserved name.");
                // Display error message box asynchronously so focus loss won't trigger setting
                // the name again
                g_StudioApp.GetDialogs()->asyncDisplayMessageBox(theTitle, theString,
                                                                 Qt3DSMessageBox::ICON_ERROR);
                return;
            }

            Q3DStudio::CString realNewName = newName;
            if (bridge->isInsideMaterialContainer(instance)) {
                Q3DStudio::CString realName = bridge->GetName(instance);
                int slashIndex = realName.rfind('/');
                if (slashIndex != Q3DStudio::CString::ENDOFSTRING)
                    realNewName = realName.Left(slashIndex + 1) + newName;
            }

            if (!bridge->CheckNameUnique(parentInstance, instance, realNewName)) {
                QString origNewName = newName.toQString();
                realNewName = bridge->GetUniqueChildName(parentInstance, instance, realNewName);
                newName = realNewName;
                if (bridge->isInsideMaterialContainer(instance)) {
                    int slashIndex = newName.rfind('/');
                    if (slashIndex != Q3DStudio::CString::ENDOFSTRING)
                        newName = newName.substr(slashIndex + 1);
                }
                // Display rename message box asynchronously so focus loss won't trigger setting
                // the name again
                g_StudioApp.GetDialogs()->DisplayObjectRenamed(origNewName, newName.toQString(),
                                                               true);
            }

            const auto sceneEditor = doc->getSceneEditor();

            // A materialdef with the same name might exists as a file but not in the container,
            // so an additional check is needed for that case
            if (bridge->isInsideMaterialContainer(instance)) {
                int i = 1;
                while (QFileInfo(sceneEditor->getFilePathFromMaterialName(
                                     realNewName.toQString())).exists()) {
                    ++i;
                    realNewName = Q3DStudio::CString::fromQString(
                                realNewName.toQString() + QString::number(i));
                    if (!bridge->CheckNameUnique(parentInstance, instance, realNewName)) {
                        realNewName = bridge->GetUniqueChildName(
                                    parentInstance, instance, realNewName);
                    }
                }
                newName = realNewName;
                int slashIndex = newName.rfind('/');
                if (slashIndex != Q3DStudio::CString::ENDOFSTRING)
                    newName = newName.substr(slashIndex + 1);
            }

            if (newName != currentName) {
                if (bridge->isInsideMaterialContainer(instance)) {
                    const auto properOldName = sceneEditor->GetName(instance).toQString();
                    const auto dirPath = doc->GetDocumentDirectory().toQString();
                    for (size_t matIdx = 0, end = m_matDatas.size(); matIdx < end; ++matIdx) {
                        if (m_matDatas[matIdx].m_name == properOldName) {
                            QFileInfo fileInfo(dirPath + QLatin1Char('/')
                                               + m_matDatas[matIdx].m_relativePath);
                            const QString newFile = fileInfo.absolutePath()
                                    + QLatin1Char('/')
                                    + newName.toQString()
                                    + QStringLiteral(".materialdef");
                            const auto properNewName
                                    = sceneEditor->getMaterialNameFromFilePath(newFile);
                            newName = Q3DStudio::CString::fromQString(properNewName);
                            doc->queueMaterialRename(properOldName, properNewName);
                        }
                    }
                }
                Q3DStudio::SCOPED_DOCUMENT_EDITOR(
                            *g_StudioApp.GetCore()->GetDoc(),
                            QObject::tr("Set Name"))->SetName(instance, newName, false);
            }
        }
        return;
    }

    qt3dsdm::SValue oldValue = currentPropertyValue(instance, handle);
    qt3dsdm::SValue v = value;

    const bool hasPreview = (m_modifiedProperty.first == instance
            && m_modifiedProperty.second == handle);

    // If this set is a commit for property that was previously changed without
    // committing, we must let the set go through even if the value hasn't changed
    // to finish the transaction.
    if (v == oldValue && !(commit && hasPreview))
        return;

    if (!commit && !hasPreview) {
        m_previouslyCommittedValue = oldValue;
        m_modifiedProperty.first = instance;
        m_modifiedProperty.second = handle;
    }

    // If the user enters 0.0 to any (x, y, z) values of camera scale,
    // we reset the value back to original, because zero scale factor will crash
    // camera-specific inverse matrix math. (Additionally, scale of zero for a camera
    // is generally not useful anyway.) We could silently discard zero values also deeper in the
    // value setter code, but then the inspector panel value would not be updated as opposed
    // to both rejecting invalid and resetting the original value here.
    EStudioObjectType theType = bridge->GetObjectType(instance);
    qt3dsdm::AdditionalMetaDataType::Value additionalType
            = studio->GetPropertySystem()->GetAdditionalMetaDataType(instance, handle);

    if (theType == EStudioObjectType::OBJTYPE_CAMERA &&
            studio->GetPropertySystem()->GetName(handle) == Q3DStudio::CString("scale")) {
        const QVector3D theFloat3 = qt3dsdm::get<QVector3D>(v);
        if (theFloat3.x() == 0.0f || theFloat3.y() == 0.0f || theFloat3.z() == 0.0f )
            v = oldValue;
    }

    // some properties may initialize OpenGL resources (e.g. loading meshes will
    // initialize vertex buffers), so the renderer's OpenGL context must be current
    Q3DStudio::IStudioRenderer &theRenderer(g_StudioApp.getRenderer());
    theRenderer.MakeContextCurrent();

    m_UpdatableEditor.EnsureEditor(QObject::tr("Set Property"), __FILE__, __LINE__)
            .SetInstancePropertyValue(instance, handle, v);

    theRenderer.ReleaseContext();

    m_UpdatableEditor.FireImmediateRefresh(instance);

    if (commit) {
        m_modifiedProperty.first = 0;
        m_modifiedProperty.second = 0;
        if (m_previouslyCommittedValue == v)
            m_UpdatableEditor.RollbackEditor();
        else
            m_UpdatableEditor.CommitEditor();

        m_previouslyCommittedValue = {};
        refreshTree();

        saveIfMaterial(instance);
    }
}

void InspectorControlModel::setSlideSelection(long instance, int handle, int index,
                                              const QStringList &list)
{
    const auto doc = g_StudioApp.GetCore()->GetDoc();
    auto studioSystem = doc->GetStudioSystem();
    const auto metaDataProvider = doc->GetStudioSystem()->GetActionMetaData();
    const auto info = metaDataProvider->GetMetaDataPropertyInfo(
                metaDataProvider->GetMetaDataProperty(instance, handle));
    QStringList stringlist = qt3dsdm::get<QStringList>(info->m_MetaDataData);

    auto slideSystem = studioSystem->GetSlideSystem();
    std::pair<bool, bool> slideData(
        getSlideCharacteristics(instance, *studioSystem->GetSlideCore(),
                                *slideSystem));
    bool hasNextSlide(slideData.first);
    bool hasPreviousSlide(slideData.second);
    qt3dsdm::SStringOrInt newSelectedData;
    if (!hasNextSlide)
        stringlist.removeAll("Next");
    if (!hasPreviousSlide)
        stringlist.removeAll("Previous");

    auto itemCount = stringlist.count();
    if (index < itemCount) {
        newSelectedData = qt3dsdm::SStringOrInt(std::make_shared<qt3dsdm::CDataStr>
                                              (Q3DStudio::CString::fromQString(list[index]).c_str()));
    } else {
        auto slideHandle = slideSystem->GetSlideByInstance(instance);
        auto masterSlide = slideSystem->GetMasterSlide(slideHandle);
        long slideIndex = index - itemCount + 1;
        auto newSelectedSlide = slideSystem->GetSlideByIndex(masterSlide, slideIndex);
        newSelectedData = qt3dsdm::SStringOrInt((long)newSelectedSlide);
    }

    Q3DStudio::SCOPED_DOCUMENT_EDITOR(*g_StudioApp.GetCore()->GetDoc(), QObject::tr("Set Property"))
            ->SetInstancePropertyValue(instance, handle, newSelectedData);
}

void InspectorControlModel::setPropertyControllerInstance(
    long instance,int property, Q3DStudio::CString controllerInstance, bool controlled)
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    IObjectReferenceHelper *objRefHelper = doc->GetDataModelObjectReferenceHelper();

    Q3DStudio::CString instancepath = Q3DStudio::CString(
        objRefHelper->GetObjectReferenceString(doc->GetSceneInstance(),
                                               CRelativePathTools::EPATHTYPE_GUID, instance));
    Q_ASSERT(instancepath.size());

    doc->SetInstancePropertyControlled(instance, instancepath, property,
                                       controllerInstance, controlled);
}

void InspectorControlModel::setPropertyControlled(long instance, int property)
{
    const auto signalSender
        = g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()->GetFullSystemSignalSender();

    signalSender->SendControlledToggled(instance, property);
}

bool InspectorControlModel::isLayer(long instance) const
{
    return g_StudioApp.GetCore()->GetDoc()->GetStudioSystem()->GetClientDataModelBridge()
            ->GetObjectType(instance) == EStudioObjectType::OBJTYPE_LAYER;
}

QString InspectorControlModel::renderableId(const QString &filePath) const
{
    return g_StudioApp.getRenderableId(filePath);
}

void InspectorControlModel::setPropertyAnimated(long instance, int handle, bool animated)
{
    CCmd* cmd = nullptr;
    auto doc = g_StudioApp.GetCore()->GetDoc();
    if (animated)
        cmd = new CCmdDataModelAnimate(doc, instance, handle);
    else
        cmd = new CCmdDataModelDeanimate(doc, instance, handle);

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

void InspectorControlModel::onSlideRearranged(const qt3dsdm::Qt3DSDMSlideHandle &inMaster,
                                              int inOldIndex, int inNewIndex)
{
    Q_UNUSED(inMaster);
    Q_UNUSED(inOldIndex);
    Q_UNUSED(inNewIndex);
    rebuildTree();
}

QVariant InspectorControlModel::data(const QModelIndex &index, int role) const
{
    if (!hasIndex(index.row(), index.column(),index.parent()))
        return {};

    const auto row = index.row();

    switch (role) {
    case GroupValuesRole:
        return m_groupElements.at(row).controlElements;
    case GroupTitleRole:
        return m_groupElements.at(row).groupTitle;
    case GroupInfoRole:
        return m_groupElements.at(row).groupInfo;
    }
    return {};
}

QHash<int, QByteArray> InspectorControlModel::roleNames() const
{
    auto names = QAbstractListModel::roleNames();
    names.insert(GroupValuesRole, "values");
    names.insert(GroupTitleRole, "title");
    names.insert(GroupInfoRole, "info");
    return names;
}

InspectorControlBase::~InspectorControlBase()
{
}