summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Client/Code/Core/Doc/DocumentEditor.cpp
blob: e8883a86d4ff33e20bb60674890bc551f49fd495 (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
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
/****************************************************************************
**
** Copyright (C) 1999-2002 NVIDIA Corporation.
** 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 "Qt3DSCommonPrecompile.h"
#include "qtAuthoring-config.h"
#include "IDocumentEditor.h"
#include "Doc.h"
#include "Qt3DSFileTools.h"
#include "StudioFullSystem.h"
#include "foundation/Qt3DS.h"
#include "foundation/Qt3DSAssert.h"
#include "StudioCoreSystem.h"
#include "StudioFullSystem.h"
#include "CmdDataModel.h"
#include "Qt3DSDMStudioSystem.h"
#include "SlideSystem.h"
#include "Qt3DSDMAnimation.h"
#include "ClientDataModelBridge.h"
#include "Cmd.h"
#include "Core.h"
#include "Dispatch.h"
#include "Qt3DSImportPerformImport.h"
#include "Qt3DSImportTranslation.h"
#include "Qt3DSImport.h"
#include "Qt3DSFileTools.h"
#include "StudioFullSystem.h"
#include "foundation/Qt3DS.h"
#include "foundation/Qt3DSAssert.h"
#include "StudioCoreSystem.h"
#include "IDocumentBufferCache.h"
#include "Qt3DSImportMesh.h"
#include "Qt3DSDMSlideGraphCore.h"
#include "IComposerEditorInterface.h"
#include "Qt3DSDMXML.h"
#include "foundation/IOStreams.h"
#include "IComposerSerializer.h"
#include "Qt3DSDMWStrOpsImpl.h"
#include "Qt3DSDMMetaData.h"
#include "DocumentResourceManagerScriptParser.h"
#include "DocumentResourceManagerRenderPluginParser.h"
#include "DocumentResourceManagerCustomMaterialParser.h"
#include "foundation/Qt3DSMemoryBuffer.h"
#include "IDirectoryWatchingSystem.h"
#include "Qt3DSDMActionCore.h"
#include "PresentationFile.h"
#include "ActionSystem.h"
#include "StandardExtensions.h"
#include "Qt3DSRenderMesh.h"
#include "Qt3DSRenderImage.h"
#include "IDocSceneGraph.h"
#include "Qt3DSTextRenderer.h"
#include "foundation/Qt3DSFoundation.h"
#include "Q3DStudioNVFoundation.h"
#include "Qt3DSDMGuides.h"
#include "Qt3DSRenderPathManager.h"
#include "Qt3DSImportPath.h"
#include "Dialogs.h"
#include "foundation/Qt3DSLogging.h"
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcomponent.h>
#include <QtCore/qdir.h>
#include <unordered_set>
#include "Runtime/Include/q3dsqmlbehavior.h"
#include "Qt3DSFileToolsSeekableMeshBufIOStream.h"
#include "IObjectReferenceHelper.h"
#include "StudioProjectSettings.h"
#include "StudioApp.h"
#include "StudioUtils.h"

namespace {

using namespace Q3DStudio;
using namespace qt3dsdm;
using namespace qt3dsimp;
using namespace Q3DStudio::ComposerImport;
using namespace qt3ds;
using namespace qt3ds::foundation;
using std::unordered_map;

inline SFloat2 ToDataModel(QT3DSVec2 inData)
{
    return SFloat2(inData.x, inData.y);
}

inline QT3DSVec2 ToFnd(SFloat2 value)
{
    return QT3DSVec2(value.m_Floats[0], value.m_Floats[1]);
}

struct ScopedBoolean
{
    bool &m_Value;
    ScopedBoolean(bool &val)
        : m_Value(val)
    {
        m_Value = !m_Value;
    }
    ~ScopedBoolean() { m_Value = !m_Value; }
};

typedef qt3ds::foundation::NVScopedRefCounted<qt3ds::render::IInputStreamFactory> TStreamFactoryPtr;

struct SImportXmlErrorHandler : public CXmlErrorHandler
{
    std::shared_ptr<IImportFailedHandler> m_handler;
    QString m_fullPathToDocument;
    SImportXmlErrorHandler(std::shared_ptr<IImportFailedHandler> hdl,
                           const Q3DStudio::CString &inFullPathToDocument)
        : m_handler(hdl)
        , m_fullPathToDocument(inFullPathToDocument.toQString())
    {
    }
    void OnXmlError(const QString &errorName, int line, int) override
    {
        if (m_handler) {
            const QString str = QObject::tr("Failed to parse XML data.\nLine %1: %2\n")
                    .arg(line).arg(errorName);
            m_handler->DisplayImportFailed(m_fullPathToDocument, str, false);
        }
    }
};

class CDocEditor : public Q3DStudio::IInternalDocumentEditor
{
    CDoc &m_Doc;
    Q3DStudio::CGraph &m_AssetGraph;
    CStudioSystem &m_StudioSystem;
    IDataCore &m_DataCore;
    ISlideSystem &m_SlideSystem;
    ISlideCore &m_SlideCore;
    ISlideGraphCore &m_SlideGraphCore;
    IAnimationCore &m_AnimationCore;
    CClientDataModelBridge &m_Bridge;
    IPropertySystem &m_PropertySystem;
    IMetaData &m_MetaData;
    IActionSystem &m_ActionSystem;
    IActionCore &m_ActionCore;
    IStudioAnimationSystem &m_AnimationSystem;
    IGuideSystem &m_GuideSystem;
    // Items should be added to every slide the parent object exists in.
    std::shared_ptr<ISignalConnection> m_ProjectDirWatcher;
    bool m_IgnoreDirChange;
    TCharPtrToSlideInstanceMap m_SourcePathInstanceMap;
    unordered_map<TCharPtr, TCharPtr> m_ImportFileToDAEMap;
    qt3dsdm::IStringTable &m_StringTable;
    Q3DStudio::Foundation::SStudioFoundation m_Foundation;
    TStreamFactoryPtr m_InputStreamFactory;
    std::unordered_map<long, QT3DSU32> m_GraphOrderMap;

public:
    CDocEditor(CDoc &inDoc)
        : m_Doc(inDoc)
        , m_AssetGraph(*m_Doc.GetAssetGraph())
        , m_StudioSystem(*m_Doc.GetStudioSystem())
        , m_DataCore(*m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetDataCore())
        , m_SlideSystem(*m_StudioSystem.GetFullSystem()->GetSlideSystem())
        , m_SlideCore(*m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetSlideCore())
        , m_SlideGraphCore(*m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetSlideGraphCore())
        , m_AnimationCore(*m_StudioSystem.GetFullSystem()->GetAnimationCore())
        , m_Bridge(*m_StudioSystem.GetClientDataModelBridge())
        , m_PropertySystem(*m_StudioSystem.GetPropertySystem())
        , m_MetaData(*m_StudioSystem.GetActionMetaData())
        , m_ActionSystem(*m_StudioSystem.GetActionSystem())
        , m_ActionCore(*m_StudioSystem.GetFullSystem()->GetActionCore())
        , m_AnimationSystem(*m_StudioSystem.GetAnimationSystem())
        , m_GuideSystem(*m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetGuideSystem())
        , m_IgnoreDirChange(false)
        , m_StringTable(m_DataCore.GetStringTable())
        , m_Foundation(Q3DStudio::Foundation::SStudioFoundation::Create())
        , m_InputStreamFactory(qt3ds::render::IInputStreamFactory::Create(*m_Foundation.m_Foundation))
    {
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        IDirectoryWatchingSystem *theSystem(m_Doc.GetDirectoryWatchingSystem());
        if (theSystem) {
            m_ProjectDirWatcher = theSystem->AddDirectory(m_Doc.GetCore()->getProjectFile()
                                                          .getProjectPath(),
                                        std::bind(&CDocEditor::OnProjectDirChanged, this,
                                                  std::placeholders::_1));
        }

        qmlRegisterType<Q3DSQmlBehavior>("QtStudio3D.Behavior", 1, 0, "Behavior");
        qmlRegisterType<Q3DSQmlBehavior, 1>("QtStudio3D.Behavior", 1, 1, "Behavior");
    }
    virtual ~CDocEditor()
    {
    }
    ///////////////////////////////////////////////////////////////////
    // IDocumentReader
    //////////////////////////////////////////////////////////////////

    bool IsInstance(Qt3DSDMInstanceHandle instance) const override
    {
        return m_DataCore.IsInstance(instance);
    }

    bool IsCurrentlyActive(TInstanceHandle inInstance) const override
    {
        SValue startTime, endTime, eyeball;
        IPropertySystem &thePropertySystem(m_PropertySystem);
        ISlideSystem &theSlideSystem(m_SlideSystem);
        if (IsInstance(inInstance)
            && thePropertySystem.GetInstancePropertyValue(
                   inInstance, m_Bridge.GetSceneAsset().m_StartTime, startTime)
            && thePropertySystem.GetInstancePropertyValue(
                   inInstance, m_Bridge.GetSceneAsset().m_EndTime, endTime)
            && thePropertySystem.GetInstancePropertyValue(
                   inInstance, m_Bridge.GetSceneAsset().m_Eyeball, eyeball)) {
            bool eyeballVal = qt3dsdm::get<bool>(eyeball);
            long theStart = qt3dsdm::get<qt3ds::QT3DSI32>(startTime);
            long theEnd = qt3dsdm::get<qt3ds::QT3DSI32>(endTime);
            Qt3DSDMInstanceHandle theInstance(inInstance);
            SInstanceSlideInformation theSlideInfo(
                theSlideSystem.GetInstanceSlideInformation(theInstance));
            Qt3DSDMSlideHandle theAssociatedSlide = theSlideInfo.m_AssociatedSlide;
            Qt3DSDMSlideHandle theMaster = theSlideInfo.m_MasterSlide;
            Qt3DSDMSlideHandle theActiveSlide = theSlideInfo.m_ActiveSlide;
            if (theAssociatedSlide == theMaster || theAssociatedSlide == theActiveSlide) {
                long theViewTime = theSlideInfo.m_ComponentMilliseconds;
                return eyeballVal && theStart <= theViewTime && theEnd > 0 && theEnd >= theViewTime;
            }
        }
        return false;
    }

    TPropertyHandle FindProperty(Qt3DSDMInstanceHandle instance,
                                         const wchar_t *inPropName) const override
    {
        return m_DataCore.GetAggregateInstancePropertyByName(instance, inPropName);
    }

    Option<SValue> GetRawInstancePropertyValue(TInstanceHandle instance,
                                                       TPropertyHandle inProperty) const override
    {
        SValue theValue;
        if (m_PropertySystem.GetInstancePropertyValue(instance, inProperty, theValue))
            return theValue.toOldSkool();
        return Empty();
    }

    Option<SValue> GetInstancePropertyValue(TInstanceHandle instance,
                                                    TPropertyHandle inProperty) const override
    {
        AdditionalMetaDataType::Value thePropertyMetaData =
            m_PropertySystem.GetAdditionalMetaDataType(instance, inProperty);
        if (thePropertyMetaData == AdditionalMetaDataType::Image) {
            TInstanceHandle theImageInstance = GetImageInstanceForProperty(instance, inProperty);
            if (theImageInstance)
                return GetRawInstancePropertyValue(theImageInstance,
                                                   m_Bridge.GetSourcePathProperty());
        } else {
            return GetRawInstancePropertyValue(instance, inProperty);
        }
        return Empty();
    }

    TInstanceHandle GetImageInstanceForProperty(TInstanceHandle instance,
                                                        TPropertyHandle inProperty) const override
    {
        qt3dsdm::Qt3DSDMSlideHandle theAssociatedSlide(m_SlideSystem.GetAssociatedSlide(instance));
        SValue theGuid;
        if (m_SlideCore.GetSpecificInstancePropertyValue(theAssociatedSlide, instance, inProperty,
                                                         theGuid)
            || m_DataCore.GetInstancePropertyValue(instance, inProperty, theGuid)) {
            return m_Bridge.GetInstanceByGUID(get<SLong4>(theGuid));
        }
        return TInstanceHandle();
    }

    Option<SValue> GetSpecificInstancePropertyValue(TSlideHandle inSlide,
                                                            TInstanceHandle instance,
                                                            TPropertyHandle inProperty) const override
    {
        SValue theValue;
        SValue theTempValue;
        if (inSlide.Valid()) {
            if (m_SlideCore.GetSpecificInstancePropertyValue(inSlide, instance, inProperty,
                                                             theValue))
                return theValue;
        } else if (m_DataCore.GetInstancePropertyValue(instance, inProperty, theTempValue))
            return theTempValue.toOldSkool();
        return Empty();
    }

    Q3DStudio::CString GetObjectTypeName(TInstanceHandle instance) const override
    {
        if (IsInstance(instance)) {
            Option<TCharStr> theTypeName = m_MetaData.GetTypeForInstance(instance);
            if (theTypeName.hasValue())
                return CString(theTypeName->wide_str());
        }
        return Q3DStudio::CString();
    }

    // Get every property value associated with this instance, from the data core up.  The
    // associated slide will be NULL for the
    // data core.
    void GetAllPropertyValues(TInstanceHandle instance, TPropertyHandle inProperty,
                                      TSlideValuePairList &outValues) const override
    {
        TSlideHandle theSlide(GetAssociatedSlide(instance));
        SValue theValue;
        if (m_DataCore.GetInstancePropertyValue(instance, inProperty, theValue))
            outValues.push_back(make_pair(0, theValue.toOldSkool()));

        if (theSlide.Valid()) {
            SValue theSlideValue;
            if (m_SlideCore.GetSpecificInstancePropertyValue(theSlide, instance, inProperty,
                                                             theSlideValue))
                outValues.push_back(make_pair(theSlide, theSlideValue));

            TSlideHandleList theChildren;
            m_SlideCore.GetChildSlides(theSlide, theChildren);
            for (size_t idx = 0, end = theChildren.size(); idx < end; ++idx) {
                if (m_SlideCore.GetSpecificInstancePropertyValue(theChildren[idx], instance,
                                                                 inProperty, theSlideValue))
                    outValues.push_back(make_pair(theChildren[idx], theSlideValue));
            }
        }
    }

    TSlideHandle GetAssociatedSlide(TInstanceHandle inInstance) const override
    {
        TSlideHandle retval = m_SlideSystem.GetAssociatedSlide(inInstance);
        return retval;
    }

    bool IsMasterSlide(TSlideHandle inSlide) const override
    {
        return m_SlideSystem.IsMasterSlide(inSlide);
    }

    TInstanceHandle GetAssociatedComponent(TInstanceHandle inInstance) const override
    {
        return GetComponentForSlide(GetAssociatedSlide(inInstance));
    }

    TSlideHandle GetActiveSlide(TInstanceHandle /*inInstance*/) const override
    {
        return m_Doc.GetActiveSlide();
    }

    TSlideHandle GetComponentActiveSlide(TInstanceHandle inInstance) const override
    {
        return m_Bridge.GetComponentActiveSlide(inInstance);
    }

    TInstanceHandle GetComponentForSlide(TSlideHandle inSlide) const override
    {
        return m_Bridge.GetOwningComponentInstance(inSlide);
    }

    void GetAllAssociatedSlides(TInstanceHandle inInstance, TSlideList &outList) const override
    {
        TSlideHandle retval = m_SlideSystem.GetAssociatedSlide(inInstance);
        if (retval.Valid()) {
            m_SlideCore.GetChildSlides(retval, outList);
            outList.insert(outList.begin(), retval);
        }
    }

    void GetAllPaths(Qt3DSDMInstanceHandle inInstance, Qt3DSDMPropertyHandle inProperty,
                     TSlideStringList &outPaths) const
    {
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        if (!m_DataCore.IsInstanceOrDerivedFrom(inInstance, theDefinitions.m_Asset.m_Instance)) {
            QT3DS_ASSERT(false);
            return;
        }

        SValue theValue;
        if (m_DataCore.GetInstancePropertyValue(inInstance, inProperty, theValue)) {
            TDataStrPtr theStr(get<TDataStrPtr>(theValue));
            if (theStr && theStr->GetLength())
                outPaths.push_back(make_pair(Qt3DSDMSlideHandle(0), CString(theStr->GetData())));
        }

        TSlideHandleList theSlides;
        GetAllAssociatedSlides(inInstance, theSlides);

        SValue theSlideValue;
        for (size_t idx = 0, end = theSlides.size(); idx < end; ++idx) {
            Qt3DSDMSlideHandle theSlide(theSlides[idx]);
            if (m_SlideCore.GetSpecificInstancePropertyValue(theSlide, inInstance, inProperty,
                                                             theSlideValue)) {
                TDataStrPtr theStr(get<TDataStrPtr>(theSlideValue));
                if (theStr && theStr->GetLength())
                    outPaths.push_back(make_pair(theSlide, CString(theStr->GetData())));
            }
        }
    }

    void GetAllSourcePaths(Qt3DSDMInstanceHandle inInstance, TSlideStringList &outPaths) const override
    {
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        GetAllPaths(inInstance, theDefinitions.m_Asset.m_SourcePath, outPaths);
    }

    void GetPathToInstanceMap(TCharPtrToSlideInstanceMap &outInstanceMap,
                              qt3dsdm::Qt3DSDMPropertyHandle inProperty,
                              bool inIncludeIdentifiers = true) const
    {
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        TInstanceHandleList existing;
        TSlideStringList thePaths;
        m_DataCore.GetInstancesDerivedFrom(existing, theDefinitions.m_Asset.m_Instance);
        outInstanceMap.clear();
        for (size_t idx = 0, end = existing.size(); idx < end; ++idx) {
            Qt3DSDMInstanceHandle theAsset(existing[idx]);

            if (m_Bridge.isInsideMaterialContainer(theAsset))
                continue;

            thePaths.clear();
            GetAllPaths(theAsset, inProperty, thePaths);

            for (size_t pathIdx = 0, pathEnd = thePaths.size(); pathIdx < pathEnd; ++pathIdx) {
                const pair<qt3dsdm::Qt3DSDMSlideHandle, Q3DStudio::CString> &theSlideStr(
                    thePaths[pathIdx]);
                CFilePath thePath(theSlideStr.second);
                if (inIncludeIdentifiers == false)
                    thePath = thePath.filePath();
                const wchar_t *theString = m_DataCore.GetStringTable().RegisterStr(
                    thePath.toCString());
                pair<TCharPtrToSlideInstanceMap::iterator, bool> theInsertResult(
                    outInstanceMap.insert(make_pair(theString, TSlideInstanceList())));
                insert_unique(theInsertResult.first->second,
                              make_pair(theSlideStr.first, theAsset));
            }
        }
    }

    void GetSourcePathToInstanceMap(TCharPtrToSlideInstanceMap &outInstanceMap,
                                            bool inIncludeIdentifiers = true) const override
    {
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        GetPathToInstanceMap(outInstanceMap, theDefinitions.m_Asset.m_SourcePath,
                             inIncludeIdentifiers);
    }

    void GetImportPathToInstanceMap(TCharPtrToSlideInstanceMap &outInstanceMap) const override
    {
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        GetPathToInstanceMap(outInstanceMap, theDefinitions.m_Asset.m_ImportFile, false);
    }

    bool CanPropertyBeLinked(TInstanceHandle inInstance, TPropertyHandle inProperty) const override
    {
        if (inProperty == m_Bridge.GetAlias().m_ReferencedNode.m_Property)
            return false;
        return m_SlideSystem.CanPropertyBeLinked(inInstance, inProperty);
    }

    // Return true if a property is linked (exists only on the associated slide && the slide is a
    // master slide).
    bool IsPropertyLinked(TInstanceHandle inInstance, TPropertyHandle inProperty) const override
    {
        if (IsInstance(inInstance)) {
            Qt3DSDMSlideHandle theAssociatedSlide = m_SlideSystem.GetAssociatedSlide(inInstance);
            if (theAssociatedSlide.Valid() && m_SlideSystem.IsMasterSlide(theAssociatedSlide)) {
                if (inProperty.Valid()) {
                    AdditionalMetaDataType::Value thePropertyMetaData =
                        m_PropertySystem.GetAdditionalMetaDataType(inInstance, inProperty);
                    if (thePropertyMetaData == AdditionalMetaDataType::Image) {
                        qt3dsdm::Qt3DSDMInstanceHandle theInstance =
                            GetImageInstanceForProperty(inInstance, inProperty);
                        if (theInstance)
                            return IsPropertyLinked(theInstance, m_Bridge.GetSourcePathProperty());
                        return true; // No image means the property is linked.
                    }
                }
                return m_SlideSystem.IsPropertyLinked(inInstance, inProperty);
            }
        }
        return false;
    }

    TSlideHandle GetSlideForProperty(TInstanceHandle inInstance,
                                             TPropertyHandle inProperty) const override
    {
        TSlideHandle associatedSlide = m_SlideSystem.GetAssociatedSlide(inInstance);
        if (associatedSlide.Valid()) {
            TSlideHandle theMaster = m_SlideCore.GetParentSlide(associatedSlide);
            bool isMaster = true;
            if (theMaster.Valid() == false || associatedSlide != theMaster)
                isMaster = false;
            if (isMaster && m_SlideSystem.IsPropertyLinked(inInstance, inProperty))
                return theMaster;
            return GetActiveSlide(inInstance);
        }
        return 0;
    }

    bool IsImported(TInstanceHandle instance) const override
    {
        SValue theValue;
        if (IsInstance(instance)
            && m_PropertySystem.GetInstancePropertyValue(instance, m_Bridge.GetImportId(),
                                                         theValue)) {
            return get<TDataStrPtr>(theValue)->GetLength() > 0;
        }
        return false;
    }

    CString GetImportId(TInstanceHandle inInstance) const override
    {
        SValue theValue;
        if (m_DataCore.GetInstancePropertyValue(
                inInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_ImportId, theValue)) {
            TDataStrPtr theStr(get<TDataStrPtr>(theValue));
            if (theStr)
                return m_StringTable.RegisterStr(theStr->GetData());
        }
        return m_StringTable.RegisterStr(L"");
    }

    CString GetFileId(TInstanceHandle inInstance) const override
    {
        SValue theValue;
        if (m_DataCore.GetInstancePropertyValue(
                inInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_FileId, theValue)) {
            TDataStrPtr theStr(get<TDataStrPtr>(theValue));
            if (theStr)
                return m_StringTable.RegisterStr(theStr->GetData());
        }
        return m_StringTable.RegisterStr(L"");
    }

    std::pair<long, long> GetTimeRange(TInstanceHandle instance) const override
    {
        SValue theStart, theEnd;
        bool result = m_PropertySystem.GetInstancePropertyValue(
                          instance, m_Bridge.GetSceneAsset().m_StartTime, theStart)
            && m_PropertySystem.GetInstancePropertyValue(
                   instance, m_Bridge.GetSceneAsset().m_EndTime, theEnd);
        if (result) {
            return std::make_pair(static_cast<long>(get<qt3ds::QT3DSI32>(theStart)),
                                  static_cast<long>(get<qt3ds::QT3DSI32>(theEnd)));
        }
        assert(0);
        return std::make_pair(0L, 0L);
    }

    std::pair<long, long> GetTimeRangeInSlide(Qt3DSDMSlideHandle inSlide,
                                              TInstanceHandle instance) const override
    {
        SValue theStart, theEnd;
        bool result = m_SlideCore.GetSpecificInstancePropertyValue(
                          inSlide, instance, m_Bridge.GetSceneAsset().m_StartTime, theStart)
            && m_SlideCore.GetSpecificInstancePropertyValue(
                   inSlide, instance, m_Bridge.GetSceneAsset().m_EndTime, theEnd);
        if (result) {
            return std::make_pair(static_cast<long>(get<qt3ds::QT3DSI32>(theStart)),
                                  static_cast<long>(get<qt3ds::QT3DSI32>(theEnd)));
        }
        assert(0);
        return std::make_pair((long)0, (long)0);
    }

    qt3dsdm::SLong4 GetGuidForInstance(Qt3DSDMInstanceHandle instance) const override
    {
        if (IsInstance(instance)) {
            Q3DStudio::CId theId(m_Bridge.GetGUID(instance));
            TGUIDPacked thePackedGUID(theId);
            return qt3dsdm::SLong4(thePackedGUID.Data1, thePackedGUID.Data2, thePackedGUID.Data3,
                                 thePackedGUID.Data4);
        }
        return qt3dsdm::SLong4();
    }
    TInstanceHandle GetInstanceForGuid(const qt3dsdm::SLong4 &inGuid) const override
    {
        return m_Bridge.GetInstanceByGUID(inGuid);
    }
    TInstanceHandle GetInstanceForObjectRef(TInstanceHandle inRoot,
                                                    const qt3dsdm::SObjectRefType &inReference) const override
    {
        return m_Bridge.GetInstance(inRoot, inReference);
    }
    Qt3DSDMInstanceHandle GetParent(Qt3DSDMInstanceHandle child) const override
    {
        return m_AssetGraph.GetParent(child);
    }

    // Get all the children if this instance in this slide.  If the slide is invalid,
    // the get all the children of this parent in all slides.
    void GetChildren(TSlideHandle inSlide, TInstanceHandle inParent,
                             TInstanceList &outChildren) const override
    {
        for (long theChildIdx = 0, theChildCount = m_AssetGraph.GetChildCount(inParent);
             theChildIdx < theChildCount; ++theChildIdx) {
            TInstanceHandle theChild(m_AssetGraph.GetChild(inParent, theChildIdx));
            if (inSlide.Valid()) {
                if (m_SlideSystem.GetAssociatedSlide(theChild) == inSlide)
                    outChildren.push_back(theChild);
            } else
                outChildren.push_back(theChild);
        }
    }

    bool IsInSceneGraph(TInstanceHandle child) const override { return m_AssetGraph.IsExist(child); }

    // If the path has any sub-path children, then yes it is externalizeable.
    bool IsPathExternalizeable(TInstanceHandle path) const override
    {
        for (QT3DSI32 idx = 0, end = m_AssetGraph.GetChildCount(path); idx < end; ++idx) {
            TInstanceHandle theChild = m_AssetGraph.GetChild(path, idx);
            if (GetObjectTypeName(theChild) == L"SubPath")
                return true;
        }
        return false;
    }

    bool IsPathInternalizeable(TInstanceHandle path) const override
    {
        Option<TDataStrPtr> theStr =
            const_cast<CDocEditor *>(this)->GetTypedInstancePropertyValue<TDataStrPtr>(
                path, m_Bridge.GetSourcePathProperty());
        if (theStr.hasValue() && (*theStr) && (*theStr)->GetLength())
            return true;
        return false;
    }

    bool AnimationExists(TSlideHandle inSlide, TInstanceHandle instance,
                                 const wchar_t *propName, long subIndex) override
    {
        Qt3DSDMPropertyHandle propHdl =
            m_DataCore.GetAggregateInstancePropertyByName(instance, propName);
        if (propHdl.Valid() == false) {
            QT3DS_ASSERT(false);
            return false;
        }
        if (inSlide.Valid() == false) {
            Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetAssociatedSlide(instance);
            if (theSlide.Valid() == false) {
                assert(0);
                return false;
            }
            if (m_SlideSystem.IsPropertyLinked(instance, propHdl))
                theSlide = m_SlideSystem.GetMasterSlide(theSlide);
            inSlide = theSlide;
        }
        return m_AnimationCore.GetAnimation(inSlide, instance, propHdl, subIndex).Valid();
    }

    bool IsAnimationArtistEdited(TSlideHandle inSlide, Qt3DSDMInstanceHandle instance,
                                         const wchar_t *propName, long subIndex) override
    {
        Qt3DSDMPropertyHandle propHdl =
            m_DataCore.GetAggregateInstancePropertyByName(instance, propName);
        if (propHdl.Valid() == false) {
            QT3DS_ASSERT(false);
            return false;
        }
        if (inSlide.Valid() == false) {
            Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetAssociatedSlide(instance);
            if (theSlide.Valid() == false) {
                assert(0);
                return false;
            }
            if (m_SlideSystem.IsPropertyLinked(instance, propHdl))
                theSlide = m_SlideSystem.GetMasterSlide(theSlide);
            inSlide = theSlide;
        }

        Qt3DSDMAnimationHandle animHandle =
            m_AnimationCore.GetAnimation(inSlide, instance, propHdl, subIndex);
        if (animHandle.Valid() == false)
            return false;
        return m_AnimationCore.IsArtistEdited(animHandle);
    }

    pair<std::shared_ptr<qt3dsdm::IDOMWriter>, CFilePath>
    DoCopySceneGraphObject(const TInstanceHandleList &inInstances)
    {
        if (inInstances.empty())
            return pair<std::shared_ptr<qt3dsdm::IDOMWriter>, CFilePath>();

        std::shared_ptr<IDOMWriter> theWriter(m_Doc.CreateDOMWriter());
        TInstanceHandleList theInstances = ToGraphOrdering(inInstances);
        m_Doc.CreateSerializer()->SerializeSceneGraphObjects(*theWriter, theInstances,
                                                             GetActiveSlide(inInstances[0]));
        CFilePath theFile = WriteWriterToFile(*theWriter, L"SceneGraph");
        return make_pair(theWriter, theFile);
    }

    // Not exposed through public interface yet
    std::shared_ptr<qt3dsdm::IDOMReader>
    CopySceneGraphObjectsToMemory(const qt3dsdm::TInstanceHandleList &instanceList)
    {
        return DoCopySceneGraphObject(instanceList).first->CreateDOMReader();
    }

    // Exposed through document reader interface
    virtual std::shared_ptr<qt3dsdm::IDOMReader>
    CopySceneGraphObjectToMemory(Qt3DSDMInstanceHandle inInstance) override
    {
        TInstanceHandleList instanceList;
        instanceList.push_back(inInstance);
        return CopySceneGraphObjectsToMemory(instanceList);
    }

    struct SFilePtrOutStream : public IOutStream
    {
        TFilePtr m_File;
        SFilePtrOutStream(TFilePtr f)
            : m_File(f)
        {
        }

        bool Write(NVConstDataRef<QT3DSU8> data) override
        {
            return m_File->Write(data.begin(), data.size()) == data.size();
        }
    };

    CFilePath WriteWriterToFile(IDOMWriter &inWriter, const CString &inStem)
    {
        CFilePath theTempFileDir = CFilePath::CombineBaseAndRelative(
            CFilePath::GetUserApplicationDirectory(), CFilePath(L"Qt3DStudio/temp_files"));
        theTempFileDir.CreateDir(true);
        CFilePath theFinalPath;
        {
            TFilePtr theFile = SFileTools::FindUniqueDestFile(theTempFileDir, inStem, L"uip", true);

            theFinalPath = theFile->m_Path;

            Qt3DSFile::AddTempFile(theFile->m_Path);

            SFilePtrOutStream theFileStream(theFile);

            CDOMSerializer::Write(*inWriter.GetTopElement(), theFileStream);
        }
        return theFinalPath;
    }

    CFilePath CopySceneGraphObjects(TInstanceHandleList inInstances) override
    {
        if (inInstances.empty())
            return L"";
        bool shouldCopy = true;
        for (size_t idx = 0, end = inInstances.size(); idx < end && shouldCopy; ++idx)
            shouldCopy = IsInstance(inInstances[idx]);

        if (!shouldCopy)
            return L"";

        return DoCopySceneGraphObject(inInstances).second;
    }

    CFilePath CopyAction(Qt3DSDMActionHandle inAction, Qt3DSDMSlideHandle inSlide) override
    {
        std::shared_ptr<IComposerSerializer> theSerializer(m_Doc.CreateSerializer());
        std::shared_ptr<qt3dsdm::IDOMWriter> theWriter(
            IDOMWriter::CreateDOMWriter(L"UIPActionFragment", m_DataCore.GetStringTablePtr())
                .first);
        theSerializer->SerializeAction(*theWriter, inSlide, inAction);
        return WriteWriterToFile(*theWriter, L"Action");
    }

    std::shared_ptr<qt3dsdm::IDOMReader> CopySlide(Qt3DSDMSlideHandle inSlide) override
    {
        if (m_SlideSystem.IsMasterSlide(inSlide)) {
            QT3DS_ASSERT(false);
            return std::shared_ptr<qt3dsdm::IDOMReader>();
        }
        std::shared_ptr<IComposerSerializer> theSerializer(m_Doc.CreateSerializer());
        std::shared_ptr<qt3dsdm::IDOMWriter> theWriter(
            IDOMWriter::CreateDOMWriter(L"UIPSlideFragment", m_DataCore.GetStringTablePtr()).first);
        theSerializer->SerializeSlide(*theWriter, inSlide);
#ifdef _DEBUG
        WriteWriterToFile(*theWriter, L"Slide");
#endif
        return theWriter->CreateDOMReader();
    }

    qt3ds::NVFoundationBase &GetFoundation() override { return *m_Foundation.m_Foundation; }

    /**
        Parses an effect, material (they use the same syntax) or material definition file
        for dependent assets and returns them in outPathMap parameter.

        @param inFile The file to parse. Can be absolute or relative to current directory.
        @param projectPath The absolute path of the project root the inFile belongs to, if any.
                           Can be left empty for files that are not in any project.
        @param recurseSourceMaterial If true, parsing .materialdef files will recursively also
                                     parse the shader .material file.
        @param outPathMap A map to return the parsed assets.
                          The key is the destination path parsed from the file. It is assumed to be
                          relative to the project root rather than the asset file itself.
                          The value is absolute source path of the asset.
                          The map is only inserted into in this function, never cleared.
                          Assets that are referred by inFile but don't actually exist are not added
                          to this map.
        @param outPropertySet A set to return material/effect texture properties
    */
    void ParseSourcePathsOutOfEffectFile(const QString &inFile,
                                         const QString &projectPath,
                                         bool recurseSourceMaterial,
                                         QHash<QString, QString> &outPathMap,
                                         QSet<QString> &outPropertySet) override
    {
        QDomDocument domDocMat;
        QDir projDir(projectPath);
        QDir fileDir(QFileInfo(inFile).dir());
        if (StudioUtils::readFileToDomDocument(inFile, domDocMat)) {
            QVector<QDomNodeList> nodeLists;
            QVector<bool> isMatDefs;
            // Read properties from custom materials and effects
            nodeLists.append(domDocMat.documentElement()
                    .firstChildElement(QStringLiteral("MetaData")).childNodes());
            isMatDefs.append(false);
            // Read properties from material definitions
            nodeLists.append(domDocMat.firstChildElement(
                                 QStringLiteral("MaterialData")).childNodes());
            isMatDefs.append(true);
            // Read properties from each texture from the material definition
            QDomNodeList textureDataElems = domDocMat.documentElement()
                    .elementsByTagName(QStringLiteral("TextureData"));
            for (int i = 0, c = textureDataElems.count(); i < c; ++i) {
                nodeLists.append(textureDataElems.at(i).childNodes());
                isMatDefs.append(true);
            }

            for (int j = 0; j < nodeLists.count(); ++j) {
                for (int i = 0, c = nodeLists[j].count(); i < c; ++i) {
                    auto elem = nodeLists[j].at(i).toElement();
                    QString path;
                    if (isMatDefs[j]) {
                        if (elem.attribute(QStringLiteral("name")) == QLatin1String("sourcepath")
                            || elem.attribute(QStringLiteral("type")) == QLatin1String("Texture")) {
                            path = elem.text();
                        }
                    } else if (elem.attribute(QStringLiteral("type")) == QLatin1String("Texture")) {
                        path = elem.attribute(QStringLiteral("default"));
                        outPropertySet.insert(elem.attribute(QStringLiteral("name")));
                    }

                    if (!path.isEmpty() && !outPathMap.contains(path)) {
                        QString absAssetPath;
                        if (projectPath.isEmpty()) {
                            // Importing from library, assume relative path to file itself
                            absAssetPath = QDir::cleanPath(fileDir.absoluteFilePath(path));
                        } else {
                            // When importing from project, all paths are relative to project
                            absAssetPath = QDir::cleanPath(projDir.absoluteFilePath(path));
                        }
                        if (recurseSourceMaterial
                                && (absAssetPath.endsWith(QLatin1String(".material"))
                                    || absAssetPath.endsWith(QLatin1String(".shader")))
                                && !outPathMap.contains(path)) {
                            ParseSourcePathsOutOfEffectFile(absAssetPath, projectPath,
                                                            false, outPathMap, outPropertySet);
                        }
                        outPathMap.insert(path, absAssetPath);
                    }
                }
            }
        } else {
            qWarning() << __FUNCTION__ << "Couldn't open file:" << inFile;
        }
    }

    Q3DStudio::CString GetCustomMaterialName(const Q3DStudio::CString &inFullPathToFile) const override
    {
        Q3DStudio::CString retval;
        qt3ds::foundation::CFileSeekableIOStream theStream(inFullPathToFile,
                                                           qt3ds::foundation::FileReadFlags());
        if (theStream.IsOpen()) {
            std::shared_ptr<IDOMFactory> theFactory =
                IDOMFactory::CreateDOMFactory(m_DataCore.GetStringTablePtr());
            SImportXmlErrorHandler theImportHandler(m_Doc.GetImportFailedHandler(),
                                                    inFullPathToFile);
            qt3dsdm::SDOMElement *theElem =
                CDOMSerializer::Read(*theFactory, theStream, &theImportHandler);
            if (theElem) {
                // OK, then this just may be a valid material file.  Get the file stem of the path.
                Q3DStudio::CFilePath thePath(inFullPathToFile);
                retval = thePath.GetFileStem();
                std::shared_ptr<IDOMReader> theReader = IDOMReader::CreateDOMReader(
                    *theElem, m_DataCore.GetStringTablePtr(), theFactory);
                const char8_t *attValue;
                if (theReader->UnregisteredAtt("formalName", attValue) && !isTrivial(attValue)) {
                    retval.assign(attValue);
                }
            }
        }
        return retval;
    }

    void getMaterialInfo(const QString &inAbsoluteFilePath,
                         QString &outName, QMap<QString, QString> &outValues,
                         QMap<QString, QMap<QString, QString>> &outTextureValues) override
    {
        if (!QFileInfo(inAbsoluteFilePath).exists())
            return;

        qt3ds::foundation::CFileSeekableIOStream theStream(inAbsoluteFilePath,
                                                           qt3ds::foundation::FileReadFlags());
        if (theStream.IsOpen()) {
            const QDir docDir(m_Doc.GetDocumentDirectory().toQString());
            const QDir projDir = g_StudioApp.GetCore()->getProjectFile().getProjectPath();

            std::shared_ptr<IDOMFactory> theFactory =
                IDOMFactory::CreateDOMFactory(m_DataCore.GetStringTablePtr());
            SImportXmlErrorHandler theImportHandler(m_Doc.GetImportFailedHandler(),
                                                    Q3DStudio::CString::fromQString(
                                                        inAbsoluteFilePath));
            qt3dsdm::SDOMElement *theElem =
                CDOMSerializer::Read(*theFactory, theStream, &theImportHandler);
            if (theElem) {
                outName = getMaterialNameFromFilePath(inAbsoluteFilePath);
                std::shared_ptr<IDOMReader> theReader = IDOMReader::CreateDOMReader(
                    *theElem, m_DataCore.GetStringTablePtr(), theFactory);

                const QString sourcePath = QStringLiteral("sourcepath");
                QStringList convertPaths;
                for (bool success = theReader->MoveToFirstChild("Property"); success;
                     success = theReader->MoveToNextSibling("Property")) {
                    const char8_t *name = "";
                    const char8_t *value = "";
                    const char8_t *type = "";
                    theReader->Att("name", name);
                    theReader->Att("type", type);
                    theReader->Value(value);
                    const QString nameStr = QString::fromUtf8(name);
                    const QString valueStr = QString::fromUtf8(value);
                    if (nameStr == sourcePath) {
                        // Check if the custom material still exists
                        const auto absSourcePath = projDir.absoluteFilePath(valueStr);
                        if (!QFileInfo(absSourcePath).exists()) {
                            outValues.clear();
                            outTextureValues.clear();
                            return;
                        }
                    }
                    if (!valueStr.isEmpty() && (QString::fromUtf8(type) == QLatin1String("Texture")
                            || nameStr == sourcePath)) {
                        convertPaths.append(nameStr);
                    }
                    outValues[nameStr] = valueStr;
                }

                for (const auto &prop : qAsConst(convertPaths)) {
                    // Change paths to be relative to the presentation
                    const QString origPath = outValues[prop];
                    outValues[prop] = docDir.relativeFilePath(projDir.absoluteFilePath(origPath));
                }

                if (AreEqual(theReader->GetElementName(), L"Property"))
                    theReader->Leave();

                for (bool texSuccess = theReader->MoveToFirstChild("TextureData"); texSuccess;
                     texSuccess = theReader->MoveToNextSibling("TextureData")) {
                    QMap<QString, QString> texValues;
                    const char8_t *texName = "";
                    theReader->Att("name", texName);
                    for (bool success = theReader->MoveToFirstChild("Property"); success;
                         success = theReader->MoveToNextSibling("Property")) {
                        const char8_t *name = "";
                        const char8_t *value = "";
                        theReader->Att("name", name);
                        theReader->Value(value);
                        texValues[name] = value;
                    }

                    if (texValues.contains(sourcePath) && !texValues[sourcePath].isEmpty()) {
                        // Change path to be relative to the presentation
                        texValues[sourcePath] = docDir.relativeFilePath(
                                    projDir.absoluteFilePath(texValues[sourcePath]));
                    }

                    outTextureValues[texName] = texValues;

                    if (AreEqual(theReader->GetElementName(), L"Property"))
                        theReader->Leave();
                }

                outValues[QStringLiteral("name")] = outName;
            }
        }
    }

    ///////////////////////////////////////////////////////////////////
    // IDocumentEditor
    //////////////////////////////////////////////////////////////////

    void BeginAggregateOperation() override
    {
        m_StudioSystem.GetFullSystem()->BeginAggregateOperation();
    }
    void EndAggregateOperation() override
    {
        m_StudioSystem.GetFullSystem()->EndAggregateOperation();
    }
    void Rollback() override { m_Doc.RollbackTransaction(); }
    // Release when finished editing
    void Release() override { m_Doc.CloseTransaction(); }

    bool FilterForNotInSlideAndNotInstance(Q3DStudio::TIdentifier inInstance,
                                           Qt3DSDMSlideHandle inSlide,
                                           Qt3DSDMInstanceHandle inTargetInstance)
    {
        Qt3DSDMSlideHandle theAssociatedSlide = m_SlideSystem.GetAssociatedSlide(inInstance);
        Qt3DSDMSlideHandle theParentSlide = m_SlideSystem.GetMasterSlide(theAssociatedSlide);
        if (inTargetInstance == Qt3DSDMInstanceHandle(inInstance)
            || (theAssociatedSlide != inSlide && theAssociatedSlide != theParentSlide))
            return true; // The object is *not* in present in this slide or is the target instance
        // the object *is* present in this slide.
        return false;
    }

    void SetTimeRangeToParent(Qt3DSDMInstanceHandle inInstance)
    {
        Qt3DSDMSlideHandle theAssociatedSlide = m_SlideSystem.GetAssociatedSlide(inInstance);
        if (theAssociatedSlide.Valid() == false)
            return;

        TSlideHandleList theChildSlides;
        m_SlideCore.GetChildSlides(theAssociatedSlide, theChildSlides);
        theChildSlides.insert(theChildSlides.begin(), theAssociatedSlide);
        Qt3DSDMInstanceHandle theParent = m_AssetGraph.GetParent(inInstance);

        Qt3DSDMPropertyHandle theStartProp = m_Bridge.GetObjectDefinitions().m_Asset.m_StartTime;
        Qt3DSDMPropertyHandle theEndProp = m_Bridge.GetObjectDefinitions().m_Asset.m_EndTime;
        bool isParentSlideOwner =
            m_Bridge.GetObjectDefinitions().IsA(theParent, ComposerObjectTypes::SlideOwner);

        for (size_t slideIdx = 0, slideEnd = theChildSlides.size(); slideIdx < slideEnd;
             ++slideIdx) {
            Qt3DSDMSlideHandle theChildSlide(theChildSlides[slideIdx]);
            pair<long, long> destTimeRange(0, 0);
            if (isParentSlideOwner) {
                // Get the previous item in the current slide.
                CGraphIterator theIterator;
                theIterator +=
                    Q3DStudio::TFilter(std::bind(&CDocEditor::FilterForNotInSlideAndNotInstance,
                                                 this, std::placeholders::_1, theChildSlide,
                                                 inInstance));
                m_AssetGraph.GetChildren(theIterator, theParent);
                Qt3DSDMInstanceHandle thePreviousItem;
                if (theIterator.IsDone())
                    continue;

                // Perform max/min of sibing times.
                for (; theIterator.IsDone() == false; ++theIterator) {
                    pair<long, long> theSiblingTime =
                        GetTimeRangeInSlide(theChildSlide, theIterator.GetCurrent());
                    destTimeRange.first = min(destTimeRange.first, theSiblingTime.first);
                    destTimeRange.second = max(destTimeRange.second, theSiblingTime.second);
                }
            } else {
                destTimeRange = GetTimeRangeInSlide(theChildSlide, theParent);
            }
            // ensure the time range is sane.
            destTimeRange.first = min(destTimeRange.first, destTimeRange.second);
            SetTimeRangeInSlide(theChildSlide, inInstance, destTimeRange.first,
                                destTimeRange.second);
        }
    }

    virtual Qt3DSDMInstanceHandle
    CreateSceneGraphInstance(ComposerObjectTypes::Enum inType, TInstanceHandle inParent,
                             TSlideHandle inSlide, TInstanceHandle inTargetId = TInstanceHandle(),
                             bool setTimeRange = true, bool selectCreatedInstance = true) override
    {
        Qt3DSDMInstanceHandle retval = IDocumentEditor::CreateSceneGraphInstance(
                    ComposerObjectTypes::Convert(inType), inParent, inSlide, m_DataCore,
                    m_SlideSystem, m_Bridge.GetObjectDefinitions(), m_AssetGraph, m_MetaData,
                    inTargetId, setTimeRange, selectCreatedInstance);
        if (setTimeRange)
            SetTimeRangeToParent(retval);
        return retval;
    }

    TInstanceHandle CreateSceneGraphInstance(ComposerObjectTypes::Enum inType,
                                             TInstanceHandle inParent, TSlideHandle inSlide,
                                             DocumentEditorInsertType::Enum inInsertType,
                                             const CPt &inPosition, EPrimitiveType inPrimitiveType,
                                             long inStartTime, bool setTimeRange = true,
                                             bool selectCreatedInstance = true) override
    {
        TInstanceHandle retval(CreateSceneGraphInstance(inType, inParent, inSlide,
                                                        TInstanceHandle(), setTimeRange));
        Q3DStudio::CString theName;
        if (inType == ComposerObjectTypes::Model) {
            const wchar_t *theSourcePath = m_Doc.GetBufferCache().GetPrimitiveName(inPrimitiveType);
            if (!IsTrivial(theSourcePath)) {
                // Trigger material generation.
                SetInstancePropertyValue(retval,
                                         m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath,
                                         std::make_shared<CDataStr>(theSourcePath));

                theName = Q3DStudio::CString(theSourcePath + 1);
            } else {
                theName = GetName(retval);
            }
        } else {
            theName = ComposerObjectTypes::Convert(inType);
            // TODO: This should work (QT3DS-2278). The line above is a quick fix in case
            // the actual reason for this to have stopped working is not found in time for 2.1
            // release.
            //theName = GetName(retval);
        }
        if (setTimeRange)
            SetTimeRangeToParent(retval);

        if (inType == ComposerObjectTypes::Layer) {
            CreateSceneGraphInstance(ComposerObjectTypes::Camera, retval, inSlide);
            CreateSceneGraphInstance(ComposerObjectTypes::Light, retval, inSlide);
        }

        if (inStartTime != -1)
            SetStartTime(retval, inStartTime);

        if (m_DataCore.IsInstanceOrDerivedFrom(
                retval, m_Bridge.GetObjectDefinitions().m_SlideOwner.m_Instance)) {
            m_Bridge.GetOrCreateGraphRoot(retval);
        }

        // if we did not set time range earlier, let's set it now to match parent
        TInstanceHandle handle = FinalizeAddOrDrop(retval, inParent, inInsertType, inPosition,
                                                   !setTimeRange, selectCreatedInstance, false);
        SetName(retval, theName, true);

        return handle;
    }

    TCharPtr GetSourcePath(Qt3DSDMInstanceHandle inInstance)
    {
        Option<SValue> theValue = GetInstancePropertyValue(
            inInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath);
        if (theValue.hasValue()) {
            TDataStrPtr theStr(get<TDataStrPtr>(*theValue));
            if (theStr)
                return theStr->GetData();
        }
        return L"";
    }

    void DoDeleteInstance(Qt3DSDMInstanceHandle instance)
    {
        // For delete, the metadata needs to participate in the undo/redo system.
        m_MetaData.SetConsumer(m_StudioSystem.GetFullSystem()->GetConsumer());
        TInstanceHandleList theDeleteDependentInstances;
        if (instance == m_Doc.GetSceneInstance()) {
            // Something is really really wrong here. Scene should never be deleted.
            QT3DS_ASSERT(false);
            return;
        }
        if (m_Bridge.IsMaterialInstance(instance)) {
            // Go through all slides this material is involved in and
            // its root properties and eliminate any image references
            // found
            std::vector<Q3DStudio::CId> imageIdList;
            m_Doc.IterateImageInstances(instance, &imageIdList);
            for (size_t idx = 0, end = imageIdList.size(); idx < end; ++idx) {
                qt3dsdm::Qt3DSDMInstanceHandle theInstance =
                    m_Bridge.GetInstanceByGUID(imageIdList[idx]);
                if (IsInstance(theInstance))
                    m_DataCore.DeleteInstance(theInstance);
            }
        }
        if (m_Bridge.IsMaterialBaseInstance(instance)
            && !m_Bridge.IsCustomMaterialInstance(instance)) {
            // Find all material instances that may reference this instance.
            // Ensure they are marked as dirty at this point but do not change their reference
            // target
            // because a material type operation may have happened.
            TInstanceHandleList derivedInstances;
            m_DataCore.GetInstancesDerivedFrom(
                derivedInstances,
                this->m_Bridge.GetObjectDefinitions().m_ReferencedMaterial.m_Instance);
            for (size_t idx = 0, end = derivedInstances.size(); idx < end; ++idx) {
                TInstanceHandle theInstance = derivedInstances[idx];
                TPropertyHandle theProperty =
                    this->m_Bridge.GetObjectDefinitions()
                        .m_ReferencedMaterial.m_ReferencedMaterial.m_Property;
                // Find all instances of this reference type.
                std::vector<std::pair<TSlideHandle, qt3dsdm::SObjectRefType>> slideValues;
                SValue theValue;
                if (m_DataCore.GetInstancePropertyValue(theInstance, theProperty, theValue)) {
                    slideValues.push_back(
                        std::make_pair(TSlideHandle(), theValue.getData<qt3dsdm::SObjectRefType>()));
                }

                TSlideHandleList theSlides;
                GetAllAssociatedSlides(theInstance, theSlides);

                SValue theSlideValue;
                for (size_t idx = 0, end = theSlides.size(); idx < end; ++idx) {
                    Qt3DSDMSlideHandle theSlide(theSlides[idx]);
                    if (m_SlideCore.GetSpecificInstancePropertyValue(theSlide, theInstance,
                                                                     theProperty, theSlideValue))
                        slideValues.push_back(std::make_pair(
                            TSlideHandle(), theSlideValue.getData<qt3dsdm::SObjectRefType>()));
                }

                for (size_t valueIdx = 0, valueEnd = slideValues.size(); valueIdx < valueEnd;
                     ++valueIdx) {
                    std::pair<TSlideHandle, qt3dsdm::SObjectRefType> &theEntry(slideValues[valueIdx]);
                    TInstanceHandle theResolvedInstance =
                        GetInstanceForObjectRef(theInstance, theEntry.second);
                    if (theResolvedInstance == instance) {
                        if (theEntry.first.Valid())
                            m_SlideCore.SetInstancePropertyValue(theEntry.first, theInstance,
                                                                 theProperty, theEntry.second);
                        else
                            m_DataCore.SetInstancePropertyValue(theInstance, theProperty,
                                                                theEntry.second);
                    }
                }
            }
        } else if (m_Bridge.IsImageInstance(instance)) {
            // Unassign the image property from material
            Qt3DSDMInstanceHandle theParent;
            Qt3DSDMPropertyHandle theProperty;

            if (!m_Bridge.GetMaterialFromImageInstance(instance, theParent, theProperty))
                m_Bridge.GetLayerFromImageProbeInstance(instance, theParent, theProperty);
            if (theParent.Valid())
                m_PropertySystem.SetInstancePropertyValue(theParent, theProperty, SLong4());
        } else if (m_Bridge.IsBehaviorInstance(instance) || m_Bridge.IsEffectInstance(instance)
                   || m_Bridge.IsCustomMaterialInstance(instance)) {
            // Check if this is the last instance that uses the same sourcepath property
            // If yes, delete the parent as well
            Qt3DSDMInstanceHandle theObjectDefInstance;
            if (m_Bridge.IsBehaviorInstance(instance))
                theObjectDefInstance = m_Bridge.GetObjectDefinitions().m_Behavior.m_Instance;
            else if (m_Bridge.IsEffectInstance(instance))
                theObjectDefInstance = m_Bridge.GetObjectDefinitions().m_Effect.m_Instance;
            else if (m_Bridge.IsCustomMaterialInstance(instance))
                theObjectDefInstance = m_Bridge.GetObjectDefinitions().m_CustomMaterial.m_Instance;
            else
                QT3DS_ASSERT(false);

            // First, we need to get the parent instance that has the same sourcepath property
            CFilePath theSourcePath(GetSourcePath(instance));
            TInstanceHandleList theParents;
            Qt3DSDMInstanceHandle theInstanceParent;
            m_DataCore.GetInstanceParents(instance, theParents);
            for (size_t idx = 0; idx < theParents.size(); ++idx) {
                Qt3DSDMInstanceHandle theParent(theParents[idx]);
                if (m_DataCore.IsInstanceOrDerivedFrom(theParent, theObjectDefInstance)
                    && theParent != theObjectDefInstance
                    && theSourcePath.toCString() == GetSourcePath(theParent)) {
                    theInstanceParent = theParent;
                    break;
                }
            }

            // Now that we got the parent, we check how many children the parent has
            TInstanceHandleList theInstanceChildren;
            m_DataCore.GetInstancesDerivedFrom(
                theInstanceChildren,
                theInstanceParent); // this will return theInstanceParent as well
            if (theInstanceChildren.size() == 2) {
                // if there are only 2 children: theInstanceParent and instance
                // delete theInstanceParent as well
                QT3DS_ASSERT((theInstanceChildren[0] == theInstanceParent
                           && theInstanceChildren[1] == instance)
                          || (theInstanceChildren[1] == theInstanceParent
                              && theInstanceChildren[0] == instance));
                theDeleteDependentInstances.push_back(theInstanceParent);
            }
        }

        // Note that the instance and its parents are still valid.
        // we delete from the bottom of the asset graph upwards.
        m_DataCore.DeleteInstance(instance);

        if (m_AssetGraph.IsExist(instance))
            m_AssetGraph.RemoveNode(instance);

        for (size_t idx = 0; idx < theDeleteDependentInstances.size(); ++idx) {
            QT3DS_ASSERT(!m_AssetGraph.IsExist(theDeleteDependentInstances[idx]));
            m_DataCore.DeleteInstance(theDeleteDependentInstances[idx]);
        }
    }

    void RecursiveDeleteInstanceInSceneGraph(Qt3DSDMInstanceHandle instance)
    {
        while (m_AssetGraph.GetChildCount(instance))
            RecursiveDeleteInstanceInSceneGraph(m_AssetGraph.GetChild(instance, 0));
        DoDeleteInstance(instance);
    }

    void DeleteInstances(const qt3dsdm::TInstanceHandleList &instances) override
    {
        for (size_t idx = 0, end = instances.size(); idx < end; ++idx) {
            qt3dsdm::Qt3DSDMInstanceHandle theInstance(instances[idx]);
            if (theInstance == m_Doc.GetSceneInstance()) {
                // Something is really really wrong here. Scene should never be deleted.
                QT3DS_ASSERT(false);
                return;
            }
            if (m_AssetGraph.IsExist(theInstance)) {
                RecursiveDeleteInstanceInSceneGraph(theInstance);
            } else if (IsInstance(theInstance)) {
                // When deleting multiple instances that have a parent-descendant
                // relationship, it is possible that an instance not in asset graph
                // has already been recursively deleted in this loop.
                // We cannot do blind delete for out-of-graph items without checking
                // if they exist.
                DoDeleteInstance(theInstance);
            }
        }
    }

    void SetSpecificInstancePropertyValue(Qt3DSDMSlideHandle inSlide,
                                                  Qt3DSDMInstanceHandle instance,
                                                  TPropertyHandle propName, const SValue &value) override
    {
        if (inSlide.Valid() == false)
            m_DataCore.SetInstancePropertyValue(instance, propName, value);
        else
            m_SlideCore.ForceSetInstancePropertyValue(inSlide, instance, propName, value);

        IInstancePropertyCoreSignalSender *theSender =
            dynamic_cast<CStudioPropertySystem &>(m_PropertySystem).GetPropertyCoreSignalSender();
        theSender->SignalInstancePropertyValue(instance, propName, value);
    }

    void CheckMeshSubsets(TInstanceHandle instance, TPropertyHandle propName,
                          Option<pair<Qt3DSDMSlideHandle, SValue>> inValue = Empty())
    {
        // Simply ensure we have enough materials for all the subsets.
        TSlideValuePairList theValues;
        GetAllPropertyValues(instance, propName, theValues);
        if (inValue.hasValue()) {
            size_t idx = 0;
            for (size_t end = theValues.size(); idx < end; ++idx) {
                if (theValues[idx].first == inValue->first) {
                    theValues[idx].second = inValue->second;
                    break;
                }
            }
            if (idx == theValues.size())
                theValues.push_back(*inValue);
        }

        QT3DSU32 numSubsets = 0;
        for (size_t propIdx = 0, propEnd = theValues.size(); propIdx < propEnd; ++propIdx) {
            TDataStrPtr newValue(get<TDataStrPtr>(theValues[propIdx].second));
            SRenderMesh *theBuffer = m_Doc.GetBufferCache().GetOrCreateModelBuffer(
                Q3DStudio::CFilePath(newValue->GetData()));
            if (theBuffer)
                numSubsets = qMax(numSubsets, (QT3DSU32)theBuffer->m_Subsets.size());
        }

        TInstanceHandleList theMaterials;
        // Child count is required in the loop on purpose.
        for (long child = 0; child < m_AssetGraph.GetChildCount(instance); ++child) {
            Qt3DSDMInstanceHandle theMaterial(m_AssetGraph.GetChild(instance, child));
            if (m_Bridge.IsMaterialBaseInstance(theMaterial)) {
                if (theMaterials.size() < numSubsets)
                    theMaterials.push_back(theMaterial);
                else {
                    // One less material
                    DeleteInstance(theMaterial);
                    --child;
                }
            }
        }

        QT3DSU32 numMaterials = (QT3DSU32)theMaterials.size();
        // Note that I create the materials in the associated slide of the instance,
        // not the active slide at this time.  This is because materials
        // need to be with the asset at all times and aren't attached via slides
        // but are assumed to be there.
        for (; numMaterials < numSubsets; ++numMaterials) {
            theMaterials.push_back(
                        CreateSceneGraphInstance(ComposerObjectTypes::ReferencedMaterial, instance,
                                                 GetAssociatedSlide(instance)));
            setMaterialReferenceByPath(theMaterials.back(), m_Bridge.getDefaultMaterialName());
            setMaterialSourcePath(theMaterials.back(),
                                  CString::fromQString(m_Bridge.getDefaultMaterialName()));
        }

        // Now go through and if possible ensure that on each slide the name of the material matches
        // the subset name.
        for (size_t propIdx = 0, propEnd = theValues.size(); propIdx < propEnd; ++propIdx) {
            TDataStrPtr newValue(get<TDataStrPtr>(theValues[propIdx].second));
            SRenderMesh *theBuffer = m_Doc.GetBufferCache().GetOrCreateModelBuffer(
                Q3DStudio::CFilePath(newValue->GetData()));
            if (theBuffer == NULL)
                continue;
            for (long subsetIdx = 0, subsetEnd = theBuffer->m_Subsets.size(); subsetIdx < subsetEnd;
                 ++subsetIdx) {
#ifdef KDAB_TEMPORARILY_REMOVED
                StaticAssert<sizeof(wchar_t) == sizeof(char16_t)>::valid_expression();
#endif
                const wstring &theSubsetName =
                    Q3DStudio::CString(theBuffer->m_Subsets[subsetIdx].m_Name.c_str()).c_str();
                if (theSubsetName.size()) {
                    Qt3DSDMInstanceHandle theMaterial(theMaterials[subsetIdx]);
                    SValue theValue;
                    Qt3DSDMSlideHandle theSlide(theValues[propIdx].first);
                    Qt3DSDMPropertyHandle theNameProp(
                        m_Bridge.GetObjectDefinitions().m_Named.m_NameProp);
                    SValue theDMValue;
                    if (theSlide.Valid()) {
                        if (m_SlideCore.GetSpecificInstancePropertyValue(theSlide, theMaterial,
                                                                         theNameProp, theValue)
                                == true
                            && AreEqual(get<TDataStrPtr>(theValue)->GetData(),
                                        theSubsetName.c_str())
                                == false)
                            m_SlideCore.ForceSetInstancePropertyValue(
                                theSlide, theMaterial, theNameProp,
                                std::make_shared<CDataStr>(theSubsetName.c_str()));
                    } else if (m_DataCore.GetInstancePropertyValue(theMaterial, theNameProp,
                                                                   theDMValue)
                                   == false
                               || AreEqual(get<TDataStrPtr>(theDMValue)->GetData(),
                                           theSubsetName.c_str())
                                   == false) {
                        m_DataCore.SetInstancePropertyValue(
                            theMaterial, theNameProp,
                            std::make_shared<CDataStr>(theSubsetName.c_str()));
                    }
                }
            }
        }
    }

    struct PathMaterialSlots
    {
        enum Enum {
            Stroke = 1,
            Fill = 1 << 1,
            FillAndStroke = Stroke | Fill,
        };
    };

    static PathMaterialSlots::Enum GetPathMaterialSlots(const wchar_t *inPathType,
                                                        const wchar_t *inPaintStyle)
    {
        if (AreEqual(inPathType, L"Geometry"))
            return PathMaterialSlots::Stroke;
        if (AreEqual(inPaintStyle, L"Filled and Stroked"))
            return PathMaterialSlots::FillAndStroke;
        if (AreEqual(inPaintStyle, L"Filled"))
            return PathMaterialSlots::Fill;
        return PathMaterialSlots::Stroke;
    }

    eastl::pair<TInstanceHandle, Q3DStudio::DocumentEditorInsertType::Enum>
    GetInsertTypeForFirstChild(TInstanceHandle instance)
    {
        if (m_AssetGraph.GetChildCount(instance))
            return eastl::make_pair(TInstanceHandle(m_AssetGraph.GetChild(instance, 0)),
                                    Q3DStudio::DocumentEditorInsertType::PreviousSibling);
        return eastl::make_pair(instance, Q3DStudio::DocumentEditorInsertType::LastChild);
    }

    void CreatePathMaterial(TInstanceHandle instance, bool isStroke, bool hasStroke)
    {
        const wchar_t *materialName = isStroke ? L"Stroke" : L"Fill";
        TInstanceHandle firstChild;
        if (m_AssetGraph.GetChildCount(instance))
            firstChild = m_AssetGraph.GetChild(instance, 0);
        TInstanceHandle theMaterial = CreateSceneGraphInstance(
            ComposerObjectTypes::Material, instance, GetAssociatedSlide(instance));
        if (firstChild.Valid()) {
            if (isStroke)
                m_AssetGraph.MoveBefore(theMaterial, firstChild);
            else {
                if (!hasStroke)
                    m_AssetGraph.MoveBefore(theMaterial, firstChild);
                else
                    m_AssetGraph.MoveAfter(theMaterial, firstChild);
            }
        }
        SetName(theMaterial, materialName);
    }

    // Normal way in to the system.
    void SetInstancePropertyValue(TInstanceHandle instance, TPropertyHandle propName,
                                          const SValue &value, bool inAutoDelete = true) override
    {
        IPropertySystem &thePropertySystem(m_PropertySystem);
        AdditionalMetaDataType::Value theProperytMetaData =
            thePropertySystem.GetAdditionalMetaDataType(instance, propName);
        TSlideHandle theNewSlide(GetSlideForProperty(instance, propName));
        if (theProperytMetaData == AdditionalMetaDataType::Image) {
            TDataStrPtr theImageSourcePath = get<TDataStrPtr>(value);
            bool hasValue = theImageSourcePath && theImageSourcePath->GetLength() > 0;
            qt3dsdm::Qt3DSDMInstanceHandle theImageInstance =
                GetImageInstanceForProperty(instance, propName);
            if (hasValue) {
                if (theImageInstance.Valid() == false)
                    theImageInstance = CreateImageInstanceForMaterialOrLayer(instance, propName);

                if (theImageInstance) {
                    SetInstancePropertyValue(theImageInstance, m_Bridge.GetSourcePathProperty(),
                                             value, inAutoDelete);
                    // Clear subpresentation value
                    SetInstancePropertyValue(theImageInstance,
                                             m_Bridge.GetSceneImage().m_SubPresentation,
                                             std::make_shared<CDataStr>(Q3DStudio::CString()),
                                             inAutoDelete);
                }

            } else {
                if (theImageInstance.Valid()) {
                    TSlideHandle theInstanceSlide = GetAssociatedSlide(instance);
                    if (m_SlideSystem.IsMasterSlide(theInstanceSlide)) {
                        if (IsPropertyLinked(instance, propName) && inAutoDelete) {
                            DeleteImageInstanceFromMaterialOrLayer(instance, propName);
                        } else {
                            SetInstancePropertyValue(theImageInstance,
                                                     m_Bridge.GetSourcePathProperty(), value,
                                                     inAutoDelete);
                            // Clear subpresentation value
                            SetInstancePropertyValue(theImageInstance,
                                                     m_Bridge.GetSceneImage().m_SubPresentation,
                                                     std::make_shared<CDataStr>(Q3DStudio::CString()),
                                                     inAutoDelete);
                        }
                    } else {
                        DeleteImageInstanceFromMaterialOrLayer(instance, propName);
                    }
                }
            }
        } else if (theProperytMetaData == AdditionalMetaDataType::Mesh) {
            CheckMeshSubsets(instance, propName, make_pair(theNewSlide, value));
            thePropertySystem.SetInstancePropertyValue(instance, propName, value);
        } else if (theProperytMetaData == AdditionalMetaDataType::PathBuffer) {
            if (inAutoDelete) {
                TDataStrPtr newValue(get<TDataStrPtr>(value));
                if (newValue->GetLength()) {
                    eastl::vector<TInstanceHandle> subPathChildren;
                    for (QT3DSI32 idx = 0, end = m_AssetGraph.GetChildCount(instance); idx < end;
                         ++idx) {
                        TInstanceHandle child = m_AssetGraph.GetChild(instance, idx);
                        if (GetObjectTypeName(child) == L"SubPath")
                            subPathChildren.push_back(child);
                    }
                    for (QT3DSU32 idx = 0, end = subPathChildren.size(); idx < end; ++idx) {
                        DeleteInstance(subPathChildren[idx]);
                    }
                }
            }
            thePropertySystem.SetInstancePropertyValue(instance, propName, value);
        } else if (theProperytMetaData == AdditionalMetaDataType::Import && inAutoDelete) {
            TInstanceList childList;
            GetChildren(theNewSlide, instance, childList);
            for (size_t idx = 0, end = childList.size(); idx < end; ++idx) {
                if (IsImported(childList[idx]))
                    DeleteInstance(childList[idx]);
            }
            // Run import operation with no handler for errors is the best I can do right now.

            TDataStrPtr newValue(get<TDataStrPtr>(value));

            CFilePath docPath(m_Doc.GetDocumentPath());
            CFilePath docDir(docPath.GetDirectory());
            STranslationLog log;
            CFilePath theFullPathToDocument(
                m_Doc.GetResolvedPathToDoc(CFilePath(newValue->GetData())));
            if (newValue && *newValue->GetData() && theFullPathToDocument.Exists()) {
                std::pair<long, long> times = GetTimeRange(instance);
                DoImport(theFullPathToDocument, theFullPathToDocument,
                         m_AssetGraph.GetParent(instance), instance, theNewSlide, docDir, log,
                         std::bind(CPerformImport::ImportToComposerFromImportFile,
                                   std::placeholders::_1, std::placeholders::_2),
                         DocumentEditorInsertType::Unknown, CPt(), times.first);
            }
            thePropertySystem.SetInstancePropertyValue(instance, propName, value);
        } else if (propName == m_Bridge.GetObjectDefinitions().m_Path.m_PathType
                   || propName == m_Bridge.GetObjectDefinitions().m_Path.m_PaintStyle) {
            TDataStrPtr oldPathType = GetTypedInstancePropertyValue<TDataStrPtr>(
                instance, m_Bridge.GetObjectDefinitions().m_Path.m_PathType);
            TDataStrPtr oldPaintStyle = GetTypedInstancePropertyValue<TDataStrPtr>(
                instance, m_Bridge.GetObjectDefinitions().m_Path.m_PaintStyle);
            TDataStrPtr newPathType;
            TDataStrPtr newPaintStyle;
            if (propName == m_Bridge.GetObjectDefinitions().m_Path.m_PathType) {
                newPaintStyle = oldPaintStyle;
                newPathType = get<TDataStrPtr>(value);
            } else {
                newPathType = oldPathType;
                newPaintStyle = get<TDataStrPtr>(value);
            }
            PathMaterialSlots::Enum oldMaterialSlot =
                GetPathMaterialSlots(oldPathType->GetData(), oldPaintStyle->GetData());
            PathMaterialSlots::Enum newMaterialSlot =
                GetPathMaterialSlots(newPathType->GetData(), newPaintStyle->GetData());
            if (oldMaterialSlot != newMaterialSlot) {
                bool hasStroke = (((int)oldMaterialSlot) & PathMaterialSlots::Stroke) > 0;
                bool hasFill = (((int)oldMaterialSlot) & PathMaterialSlots::Fill) > 0;
                bool needsStroke = (((int)newMaterialSlot) & PathMaterialSlots::Stroke) > 0;
                bool needsFill = (((int)newMaterialSlot) & PathMaterialSlots::Fill) > 0;
                // first, remove any materials that should not be there.
                qt3dsdm::Qt3DSDMInstanceHandle firstMaterial;
                qt3dsdm::Qt3DSDMInstanceHandle secondMaterial;
                for (int idx = 0, end = m_AssetGraph.GetChildCount(instance); idx < end; ++idx) {
                    TInstanceHandle childAsset = m_AssetGraph.GetChild(instance, idx);
                    if (m_Bridge.IsMaterialInstance(childAsset)) {
                        if (firstMaterial.Valid())
                            secondMaterial = childAsset;
                        else
                            firstMaterial = childAsset;
                    }
                }
                if (hasStroke && !needsStroke) {
                    if (firstMaterial.Valid())
                        DeleteInstance(firstMaterial);
                }
                if (hasFill && !needsFill) {
                    if (hasStroke) {
                        if (secondMaterial.Valid())
                            DeleteInstance(secondMaterial);
                    } else if (firstMaterial.Valid())
                        DeleteInstance(firstMaterial);
                }

                if (needsStroke && !hasStroke) {
                    CreatePathMaterial(instance, true, false);
                }
                if (needsFill && !hasFill) {
                    CreatePathMaterial(instance, false, needsStroke);
                }
            }
            // Now set the property for reals
            thePropertySystem.SetInstancePropertyValue(instance, propName, value);
        } else {
            if (propName != m_Bridge.GetAlias().m_ReferencedNode.m_Property) {
                thePropertySystem.SetInstancePropertyValue(instance, propName, value);
            } else {
                // Alias properties are set in the scene graph, not in the slides.
                // This makes the runtime expansion easier and stops problems such as
                // someone unlinking the alias
                // node reference and setting it to different values on different slides.
                m_DataCore.SetInstancePropertyValue(instance, propName, value);
            }
        }
    }

    TInstanceHandle CreateImageInstanceForMaterialOrLayer(TInstanceHandle instance,
                                                          TPropertyHandle propName)
    {
        // Check to make sure there isn't one already assigned here.
        {
            qt3dsdm::Qt3DSDMInstanceHandle theImageInstance =
                GetImageInstanceForProperty(instance, propName);
            if (theImageInstance.Valid())
                return theImageInstance;
        }

        Qt3DSDMSlideHandle theSlide(GetAssociatedSlide(instance));
        TInstanceHandle theImageInstance =
            CreateSceneGraphInstance(ComposerObjectTypes::Image, instance, theSlide);
        const Q3DStudio::TGUIDPacked thePackedGuid(m_Bridge.GetGUID(theImageInstance));
        qt3dsdm::SLong4 theImageGuid(thePackedGuid.Data1, thePackedGuid.Data2, thePackedGuid.Data3,
                                     thePackedGuid.Data4);
        m_SlideCore.ForceSetInstancePropertyValue(theSlide, instance, propName, theImageGuid);
        if (propName == m_Bridge.GetObjectDefinitions().m_Material.m_SpecularReflection) {
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TextureMapping,
                                     std::make_shared<CDataStr>(L"Environmental Mapping"), false);
        } else if (propName == m_Bridge.GetObjectDefinitions().m_Layer.m_LightProbe
                   || propName == m_Bridge.GetObjectDefinitions().m_Layer.m_LightProbe2) {
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TextureMapping,
                                     std::make_shared<CDataStr>(L"Light Probe"), false);
            // Preserve legacy behavior where image based lighting used always tiling for
            // horizontal direction
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TilingU,
                                     std::make_shared<CDataStr>(L"Tiled"), false);
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TilingV,
                                     std::make_shared<CDataStr>(L"No Tiling"), false);
        } else if (propName == m_Bridge.GetObjectDefinitions().m_MaterialBase.m_IblProbe) {
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TextureMapping,
                                     std::make_shared<CDataStr>(L"Light Probe"), false);
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TilingU,
                                     std::make_shared<CDataStr>(L"Tiled"), false);
            SetInstancePropertyValue(theImageInstance,
                                     m_Bridge.GetObjectDefinitions().m_Image.m_TilingV,
                                     std::make_shared<CDataStr>(L"No Tiling"), false);
        }
        return theImageInstance;
    }

    void DeleteImageInstanceFromMaterialOrLayer(TInstanceHandle instance, TPropertyHandle propName)
    {
        Qt3DSDMSlideHandle theAssociatedSlide(GetAssociatedSlide(instance));
        qt3dsdm::Qt3DSDMInstanceHandle theImageInstance =
            GetImageInstanceForProperty(instance, propName);
        if (theImageInstance.Valid()) {
            DeleteInstance(theImageInstance);
            m_SlideCore.SetInstancePropertyValue(theAssociatedSlide, instance, propName, SLong4());
        }
    }

    TInstanceHandle SetInstancePropertyValueAsImage(TInstanceHandle instance,
                                                            TPropertyHandle propName,
                                                            const Q3DStudio::CString &inSourcePath) override
    {
        CFilePath thePath = m_Doc.GetResolvedPathToDoc(inSourcePath);
        assert(thePath.IsFile());
        if (!thePath.IsFile())
            return 0;
        Qt3DSDMSlideHandle theSlide(GetAssociatedSlide(instance));

        TInstanceHandle theImageInstance =
            CreateImageInstanceForMaterialOrLayer(instance, propName);
        TDataStrPtr thePtrPath(new CDataStr(inSourcePath, inSourcePath.size()));
        SetInstancePropertyValue(instance, propName, thePtrPath);

        return theImageInstance;
    }

    virtual TInstanceHandle
    SetInstancePropertyValueAsRenderable(TInstanceHandle instance, TPropertyHandle propName,
                                         const Q3DStudio::CString &inSourcePath) override
    {
        CFilePath thePath = m_Doc.GetResolvedPathToDoc(inSourcePath);
        // Delete any existing renderable object children.
        vector<TInstanceHandle> childrenToDelete;
        for (long idx = 0, end = m_AssetGraph.GetChildCount(instance); idx < end; ++idx) {
            TInstanceHandle existingChild = m_AssetGraph.GetChild(instance, idx);
            if (m_Bridge.IsRenderPluginInstance(existingChild))
                childrenToDelete.push_back(existingChild);
        }
        for (size_t childIdx = 0, childEnd = childrenToDelete.size(); childIdx < childEnd;
             ++childIdx)
            DeleteInstance(childrenToDelete[childIdx]);

        // If this is an image instance, set the inSourcePath also as the value of corresponding
        // image property in the parent
        if (m_Bridge.IsImageInstance(instance)) {
            Qt3DSDMInstanceHandle parent;
            Qt3DSDMPropertyHandle imageProperty;
            if (!m_Bridge.GetMaterialFromImageInstance(instance, parent, imageProperty))
                m_Bridge.GetLayerFromImageProbeInstance(instance, parent, imageProperty);
            bool parentEmptied = false;
            if (parent.Valid()) {
                SetInstancePropertyValue(parent, imageProperty,
                                         std::make_shared<qt3dsdm::CDataStr>(inSourcePath.c_str()),
                                         true);
                // Setting the parent image property to empty will delete the image child,
                // so we should skip setting the property there
                if (inSourcePath.IsEmpty())
                    parentEmptied = true;
            }
            if (!parentEmptied) {
                SetInstancePropertyValue(instance, propName,
                                         std::make_shared<qt3dsdm::CDataStr>(inSourcePath.c_str()),
                                         true);
            }
        } else if (m_Bridge.IsLayerInstance(instance)
                   && m_Bridge.GetSourcePathProperty() == propName
                   && !inSourcePath.IsEmpty()) {
            // Resize the layer to be the size of the presentation
            QSize presSize(g_StudioApp.getRenderableSize(inSourcePath.toQString()));
            auto &layer = m_Bridge.GetLayer();

            // Determine if width and height properties are visible
            auto isPropertyVisible = [this, &instance](TPropertyHandle propHandle) {
                IMetaData &metaData = *m_Doc.GetStudioSystem()->GetActionMetaData();
                Qt3DSDMMetaDataPropertyHandle metaHandle
                        = metaData.GetMetaDataProperty(instance, propHandle);
                qt3ds::foundation::NVConstDataRef<SPropertyFilterInfo> filters(
                            metaData.GetMetaDataPropertyFilters(metaHandle));
                if (filters.size()) {
                    qt3dsdm::IPropertySystem &propertySystem(
                                *m_Doc.GetStudioSystem()->GetPropertySystem());
                    for (QT3DSU32 propIdx = 0, propEnd = filters.size(); propIdx < propEnd;
                         ++propIdx) {
                        const SPropertyFilterInfo &filter(filters[propIdx]);
                        SValue value;
                        propertySystem.GetInstancePropertyValue(
                                    instance, filter.m_FilterProperty, value);
                        if (value == filter.m_Value)
                            return true;
                    }
                }
                return false;
            };
            bool widthVisible = isPropertyVisible(layer.m_Width);
            bool heightVisible = isPropertyVisible(layer.m_Height);

            // If width is visible, adjust that. Otherwise adjust right in relation to left.
            SValue pixelValue = std::make_shared<CDataStr>(L"pixels");
            SValue percentValue = std::make_shared<CDataStr>(L"percent");
            if (widthVisible) {
                SetInstancePropertyValue(instance, layer.m_WidthUnits, pixelValue, true);
                SetInstancePropertyValue(instance, layer.m_Width, float(presSize.width()), true);
            } else {
                long curWidth = m_Doc.GetCore()->GetStudioProjectSettings()
                        ->getPresentationSize().width();
                Option<SValue> leftVal = GetInstancePropertyValue(instance, layer.m_Left);
                Option<SValue> leftUnitsVal = GetInstancePropertyValue(instance, layer.m_LeftUnits);
                float left = qt3dsdm::get<float>(leftVal.getValue());
                if (Equals(leftUnitsVal, percentValue))
                    left = (curWidth * left) / 100;
                float right = curWidth - (left + float(presSize.width()));
                SetInstancePropertyValue(instance, layer.m_RightUnits, pixelValue, true);
                SetInstancePropertyValue(instance, layer.m_Right, right, true);
            }
            // If height is visible, adjust that. Otherwise adjust bottom in relation to top.
            if (heightVisible) {
                SetInstancePropertyValue(instance, layer.m_HeightUnits, pixelValue, true);
                SetInstancePropertyValue(instance, layer.m_Height, float(presSize.height()), true);
            } else {
                long curHeight = m_Doc.GetCore()->GetStudioProjectSettings()
                        ->getPresentationSize().height();
                Option<SValue> topVal = GetInstancePropertyValue(instance, layer.m_Top);
                Option<SValue> topUnitsVal = GetInstancePropertyValue(instance, layer.m_TopUnits);
                float top = qt3dsdm::get<float>(topVal.getValue());
                if (Equals(topUnitsVal, percentValue))
                    top = (curHeight * top) / 100;
                float bottom = curHeight - (top + float(presSize.height()));
                SetInstancePropertyValue(instance, layer.m_BottomUnits, pixelValue, true);
                SetInstancePropertyValue(instance, layer.m_Bottom, bottom, true);
            }
            SetInstancePropertyValue(instance, propName,
                                     std::make_shared<qt3dsdm::CDataStr>(inSourcePath.c_str()),
                                     true);
        } else {
            SetInstancePropertyValue(instance, propName,
                                     std::make_shared<qt3dsdm::CDataStr>(inSourcePath.c_str()),
                                     true);
        }

        // If this is a render plugin
        if (thePath.Exists() && thePath.GetExtension().CompareNoCase("plugin")) {
            Qt3DSDMSlideHandle theSlide(GetAssociatedSlide(instance));
            return LoadRenderPlugin(thePath, instance, theSlide,
                                    DocumentEditorInsertType::LastChild, -1);
        }
        return TInstanceHandle();
    }

    /**
     * Sets an instance's image-type property from a renderable or image. If no texture exists, a
     * new one is created. Next, the texture property from 'prop' param is set to the 'src' param.
     *
     * @param instance the instance
     * @param prop the instance image property
     * @param src the presentation Id or image file name to set for the texture
     */
    void setInstanceImagePropertyValue(TInstanceHandle instance, TPropertyHandle prop,
                                       const CString &src, bool isSubp = true) override
    {
        Qt3DSDMPropertyHandle img = GetImageInstanceForProperty(instance, prop);

        if (!img)
            img = CreateImageInstanceForMaterialOrLayer(instance, prop);

        SetInstancePropertyValueAsRenderable(img, isSubp ? m_Bridge.getSubpresentationProperty()
                                                         : m_Bridge.GetSourcePathProperty(), src);
    }

    /**
     * Create a rect under the active layer and set its material's diffuse map from the provided
     * source.
     *
     * @param src The presentation Id or image file name to set for the texture
     * @param slide The slide to add to
     * @param isSubPres If true, the src parameter is a subpresentation Id
     * @param pos Add position in the scene
     * @param startTime Add at this start time
     */
    void addRectFromSource(const CString &src, TSlideHandle slide, bool isSubPres,
                           const CPt &pos = {}, long startTime = -1) override
    {
        qt3dsdm::Qt3DSDMPropertyHandle activeLayer = m_Doc.GetActiveLayer();
        const auto absSrc = QFileInfo(m_Doc.GetDocumentPath()).dir()
                .absoluteFilePath(src.toQString());
        if (isSubPres) {
            qt3dsdm::Qt3DSDMInstanceHandle rectInstance =
                CreateSceneGraphInstance(ComposerObjectTypes::Model, activeLayer, slide);
            m_PropertySystem.SetInstancePropertyValue(
                rectInstance, m_Bridge.GetSourcePathProperty(),
                std::make_shared<qt3dsdm::CDataStr>(
                    m_Doc.GetBufferCache().GetPrimitiveName(PRIMITIVETYPE_RECT)));

            createRefMaterialFromImageOrPresentation(rectInstance, slide, src, true);
            SetName(rectInstance, src, true);

            FinalizeAddOrDrop(rectInstance, activeLayer,
                              Q3DStudio::DocumentEditorInsertType::LastChild,
                              pos, startTime == -1);
        } else {
            AutomapImage(CString::fromQString(absSrc), activeLayer, slide,
                         Q3DStudio::DocumentEditorInsertType::LastChild, pos, startTime);
        }
    }

    void SetMaterialType(TInstanceHandle instance,
                         const Q3DStudio::CString &inRelativePathToMaterialFile) override
    {
        if (m_Bridge.GetSourcePath(instance) == inRelativePathToMaterialFile)
            return;

        TInstanceHandle model = m_AssetGraph.GetParent(instance);
        TInstanceHandle newMaterial;
        TSlideHandle theSlide = m_SlideSystem.GetAssociatedSlide(model);
        // Keep material names the same so that if you change the material type
        // any relative path links will still work.
        // Next bug is harder (keep id's the same).
        Q3DStudio::CString theName = GetName(instance);
        SLong4 theGuid = m_Bridge.GetInstanceGUID(instance);
        TInstanceHandle nextChild = m_AssetGraph.GetSibling(instance, true);
        // Now get all the actions on the material and re-add them.

        TActionHandleList theActions;
        m_ActionCore.GetActions(instance, theActions);
        std::vector<SActionInfo> theActionData;
        std::vector<std::vector<SHandlerArgumentInfo>> theActionDataArgs;
        for (size_t actionIdx = 0, actionEnd = theActions.size(); actionIdx < actionEnd;
             ++actionIdx) {
            theActionData.push_back(m_ActionCore.GetActionInfo(theActions[actionIdx]));
            theActionDataArgs.push_back(std::vector<SHandlerArgumentInfo>());
            std::vector<SHandlerArgumentInfo> &theInfoList(theActionDataArgs.back());
            for (size_t argIdx = 0, argEnd = theActionData.back().m_HandlerArgs.size();
                 argIdx < argEnd; ++argIdx)
                theInfoList.push_back(m_ActionCore.GetHandlerArgumentInfo(
                    theActionData.back().m_HandlerArgs[argIdx]));
        }

        // save lightmap values since we want to pass on the current lightmaps settings to the new
        // material
        Option<SValue> theLightmapIndirectValue = GetInstancePropertyValue(
            instance, m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapIndirect);
        Option<SValue> theLightmapRadiosityValue = GetInstancePropertyValue(
            instance, m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapRadiosity);
        Option<SValue> theLightmapShadowValue = GetInstancePropertyValue(
            instance, m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapShadow);

        DeleteInstance(instance);
        if (inRelativePathToMaterialFile == "Standard Material")
            newMaterial =
                CreateSceneGraphInstance(ComposerObjectTypes::Material, model, theSlide, instance);
        else if (inRelativePathToMaterialFile == "Referenced Material")
            newMaterial = CreateSceneGraphInstance(ComposerObjectTypes::ReferencedMaterial, model,
                                                   theSlide, instance);
        else {
            CFilePath thePath = m_Doc.GetResolvedPathToDoc(inRelativePathToMaterialFile);
            newMaterial = LoadCustomMaterial(thePath, model, theSlide,
                                             DocumentEditorInsertType::LastChild, 0, instance);
        }

        if (newMaterial.Valid() && nextChild.Valid())
            m_AssetGraph.MoveBefore(newMaterial, nextChild);

        // restore current lightmap settings for new material
        if (theLightmapIndirectValue.hasValue())
            SetInstancePropertyValue(newMaterial,
                                     m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapIndirect,
                                     theLightmapIndirectValue, false);
        if (theLightmapRadiosityValue.hasValue())
            SetInstancePropertyValue(
                newMaterial, m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapRadiosity,
                theLightmapRadiosityValue, false);
        if (theLightmapShadowValue.hasValue())
            SetInstancePropertyValue(newMaterial,
                                     m_Bridge.GetObjectDefinitions().m_Lightmaps.m_LightmapShadow,
                                     theLightmapShadowValue, false);

        SetName(newMaterial, theName, false);
        m_Bridge.SetInstanceGUID(newMaterial, theGuid);
        // Copy all actions from old material instance to new material instance
        for (size_t actionIdx = 0, actionEnd = theActionData.size(); actionIdx < actionEnd;
             ++actionIdx) {
            const SActionInfo &theSourceInfo(theActionData[actionIdx]);

            Qt3DSDMActionHandle theNewAction = AddAction(
                theSourceInfo.m_Slide, newMaterial, theSourceInfo.m_Event, theSourceInfo.m_Handler);
            m_ActionCore.SetTriggerObject(theNewAction, theSourceInfo.m_TriggerObject);
            m_ActionCore.SetTargetObject(theNewAction, theSourceInfo.m_TargetObject);
            std::vector<SHandlerArgumentInfo> &theInfoList(theActionDataArgs[actionIdx]);
            for (size_t argIdx = 0, argEnd = theInfoList.size(); argIdx < argEnd; ++argIdx) {
                const SHandlerArgumentInfo &theArgData(theInfoList[argIdx]);
                Qt3DSDMHandlerArgHandle theParamHandle = m_ActionCore.AddHandlerArgument(
                    theNewAction, theArgData.m_Name, theArgData.m_ArgType, theArgData.m_ValueType);
                m_ActionCore.SetHandlerArgumentValue(theParamHandle, theArgData.m_Value);
            }
        }
        m_Doc.SelectDataModelObject(newMaterial);
    }

    QString getMaterialDirectoryPath() const override
    {
        return m_Doc.GetCore()->getProjectFile().getProjectPath() + QStringLiteral("/materials/");
    }

    QString getMaterialFilePath(const QString &materialName) const override
    {
        QString actualMaterialName = materialName;
        int slashIndex = actualMaterialName.lastIndexOf(QLatin1Char('/'));
        if (slashIndex != -1)
            actualMaterialName = actualMaterialName.mid(slashIndex + 1);
        return getMaterialDirectoryPath() + actualMaterialName + QStringLiteral(".materialdef");
    }

    void writeMaterialFile(Qt3DSDMInstanceHandle instance, bool createNewFile) override
    {
        const auto materialName = CFilePath::MakeSafeFileStem(GetName(instance)).toQString();
        writeMaterialFile(instance, materialName, createNewFile,
                          getFilePathFromMaterialName(materialName));
    }

    Q3DStudio::CString writeMaterialFile(Qt3DSDMInstanceHandle instance,
                                         const QString &materialName,
                                         bool createNewFile,
                                         const QString &sourcePath = {}) override
    {
        if (materialName == getMaterialNameFromFilePath(m_Bridge.getDefaultMaterialName()))
            return "";

        EStudioObjectType type = m_Bridge.GetObjectType(instance);

        if (type == EStudioObjectType::OBJTYPE_MATERIAL
            || type == EStudioObjectType::OBJTYPE_CUSTOMMATERIAL) {
            QString actualSourcePath = sourcePath;
            if (actualSourcePath.isEmpty())
                actualSourcePath = getMaterialFilePath(materialName);

            QFileInfo fileInfo(actualSourcePath);
            if (!fileInfo.dir().exists())
                fileInfo.dir().mkpath(QStringLiteral("."));

            QFile file(actualSourcePath);
            if ((createNewFile && !file.exists()) || (!createNewFile && file.exists()))
                saveMaterial(instance, file);
            return m_Doc.GetRelativePathToDoc(actualSourcePath);
        }

        return "";
    }

    void writeProperty(QFile &file, const QString &name, const QString &value,
                       int indent = 1, bool isTexture = false, bool useCData = true)
    {
        for (int i = 0; i < indent; ++i)
            file.write("\t");
        file.write("<Property name=\"");
        file.write(name.toUtf8().constData());
        if (isTexture)
            file.write("\" type=\"Texture");
        file.write("\">");
        if (useCData) {
            QString cDataValue = QStringLiteral("<![CDATA[") + value + QStringLiteral("]]>");
            file.write(cDataValue.toUtf8().constData());
        } else {
            file.write(value.toUtf8().constData());
        }
        file.write("</Property>\n");
    }

    void writeProperty(QFile &file, const QString &name, const SValue &value, int indent = 1,
                       bool isTexture = false)
    {
        MemoryBuffer<RawAllocator> tempBuffer;
        WCharTWriter writer(tempBuffer);
        WStrOps<SValue>().ToBuf(value, writer);
        tempBuffer.write(0);

        if (tempBuffer.size()) {
            bool useCData = name == QLatin1String("name");
            writeProperty(file, name,
                          QString::fromWCharArray((const wchar_t *)tempBuffer.begin()),
                          indent, isTexture, useCData);
        }
    }

    bool isSaveableMaterialProperty(const QString& name) {
        return name != QLatin1String("starttime")
                && name != QLatin1String("endtime")
                && name != QLatin1String("controlledproperty")
                && name != QLatin1String("eyeball")
                && name != QLatin1String("shy")
                && name != QLatin1String("locked")
                && name != QLatin1String("id")
                && name != QLatin1String("fileid")
                && name != QLatin1String("timebarcolor")
                && name != QLatin1String("timebartext");
    }

    void saveIfMaterial(Qt3DSDMInstanceHandle instance)
    {
        Qt3DSDMInstanceHandle material;
        if (m_Bridge.isInsideMaterialContainer(instance)) {
            const auto type = m_Bridge.GetObjectType(instance);
            if (type == OBJTYPE_MATERIAL || type == OBJTYPE_CUSTOMMATERIAL) {
                material = instance;
            } else {
                const auto parent = m_Bridge.GetParentInstance(instance);
                const auto parentType = m_Bridge.GetObjectType(parent);
                if (parentType == OBJTYPE_MATERIAL || parentType == OBJTYPE_CUSTOMMATERIAL)
                    material = parent;
            }
        }

        if (material.Valid())
            writeMaterialFile(material, false);
    }

    void saveMaterial(Qt3DSDMInstanceHandle instance, QFile &file)
    {
        SValue value;
        file.open(QIODevice::WriteOnly);
        file.write("<MaterialData version=\"1.0\">\n");
        QMap<QString, Qt3DSDMInstanceHandle> textureHandles;
        qt3dsdm::TPropertyHandleList propList;

        const QDir docDir(m_Doc.GetDocumentDirectory().toQString());
        const QDir projDir = g_StudioApp.GetCore()->getProjectFile().getProjectPath();
        auto sourcePathProp = m_Bridge.GetSourcePathProperty();
        // Importing interprets "./" prefix to mean project dir relative
        const QString projPrefix = QStringLiteral("./");

        m_PropertySystem.GetAggregateInstanceProperties(instance, propList);
        for (auto &prop : propList) {
            const auto name = QString::fromWCharArray(m_PropertySystem.GetName(prop).wide_str());

            if (!isSaveableMaterialProperty(name))
                continue;

            if (m_AnimationSystem.IsPropertyAnimated(instance, prop))
                continue;

            m_PropertySystem.GetInstancePropertyValue(instance, prop, value);

            if (!value.empty()) {
                bool valid = true;
                bool isTexture = false;
                bool isPath = true;
                QString strValue;
                if (value.getType() == DataModelDataType::Long4) {
                    SLong4 guid = get<qt3dsdm::SLong4>(value);
                    if (guid.Valid()) {
                        auto ref = m_Bridge.GetInstanceByGUID(guid);
                        textureHandles[name] = ref;
                        strValue = m_Bridge.GetSourcePath(ref).toQString();
                        if (strValue.isEmpty()) {
                            strValue = m_Bridge.getSubpresentation(ref).toQString();
                            isPath = false;
                        }
                    } else {
                        valid = false;
                    }
                } else {
                    qt3dsdm::AdditionalMetaDataType::Value additionalMetaDataType
                        = m_PropertySystem.GetAdditionalMetaDataType(instance, prop);
                    if (additionalMetaDataType == AdditionalMetaDataType::Texture) {
                        isTexture = true;
                        TDataStrPtr strPtr = get<TDataStrPtr>(value);
                        strValue = QString::fromWCharArray(strPtr->GetData());
                    } else if (sourcePathProp == prop) {
                        TDataStrPtr strPtr = get<TDataStrPtr>(value);
                        strValue = QString::fromWCharArray(strPtr->GetData());
                    }
                }

                if (strValue.isEmpty() && valid) {
                    writeProperty(file, name, value);
                } else if (!strValue.isEmpty()) {
                    // Save paths relative to the project instead of the presentation.
                    // This makes it possible to use same material from multiple presentations
                    // that are not all in the same folder.
                    if (isPath) {
                        strValue = projPrefix
                                + projDir.relativeFilePath(docDir.absoluteFilePath(strValue));
                    }
                    writeProperty(file, name, strValue, 1, isTexture);
                }
            }
        }

        const QFileInfo fileInfo(file);
        writeProperty(file, QStringLiteral("path"), fileInfo.absoluteFilePath());

        QMapIterator<QString, Qt3DSDMInstanceHandle> i(textureHandles);
        while (i.hasNext()) {
            i.next();
            const auto &texName = i.key();
            const auto &handle = i.value();
            file.write(QByteArrayLiteral("\t<TextureData name=\"")
                       + texName.toUtf8() + QByteArrayLiteral("\">\n"));
            propList.clear();
            m_PropertySystem.GetAggregateInstanceProperties(handle, propList);
            for (auto &prop : propList) {
                const auto name = QString::fromWCharArray(
                            m_PropertySystem.GetName(prop).wide_str());

                if (!isSaveableMaterialProperty(name))
                    continue;

                if (m_AnimationSystem.IsPropertyAnimated(handle, prop))
                    continue;

                m_PropertySystem.GetInstancePropertyValue(handle, prop, value);
                if (!value.empty()) {
                    if (sourcePathProp == prop) {
                        TDataStrPtr strPtr = get<TDataStrPtr>(value);
                        QString strValue = QString::fromWCharArray(strPtr->GetData());
                        strValue = projPrefix
                                + projDir.relativeFilePath(docDir.absoluteFilePath(strValue));
                        writeProperty(file, name, strValue, 2);
                    } else {
                        writeProperty(file, name, value, 2);
                    }
                }
            }
            file.write("\t</TextureData>\n");
        }

        file.write("</MaterialData>");
    }

    Qt3DSDMInstanceHandle getOrCreateMaterialContainer()
    {
        auto instance = m_Bridge.getMaterialContainer();
        if (!instance.Valid()) {
            IObjectReferenceHelper *objRefHelper = m_Doc.GetDataModelObjectReferenceHelper();
            Qt3DSDMInstanceHandle parent;
            CRelativePathTools::EPathType type;
            objRefHelper->ResolvePath(m_Doc.GetSceneInstance(),
                                      CString::fromQString(
                                          m_Bridge.getMaterialContainerParentPath()),
                                      type, parent, true);
            if (!parent.Valid())
                parent = m_Doc.GetSceneInstance();
            Qt3DSDMSlideHandle slide = m_Bridge.GetOrCreateGraphRoot(parent);
            instance = CreateSceneGraphInstance(ComposerObjectTypes::Material, parent,
                                                slide, DocumentEditorInsertType::LastChild,
                                                CPt(), PRIMITIVETYPE_UNKNOWN, -1, true, false);
            SetName(instance, CString::fromQString(m_Bridge.getMaterialContainerName()));
            m_SlideCore.forceSetInstancePropertyValueOnAllSlides(
                        instance, m_Bridge.GetSceneAsset().m_EndTime, 0);
        }
        return instance;
    }

    QString getFilePathFromMaterialName(const QString &name) override
    {
        return QDir(m_Doc.GetCore()->getProjectFile().getProjectPath())
                .absoluteFilePath(name + QStringLiteral(".materialdef"));
    }

    QString getMaterialNameFromFilePath(const QString &path) override
    {
        QString materialName;
        QString dirPath;
        if (path.contains(QLatin1String(".materialdef"))) {
            QDir dir(path);
            if (dir.isAbsolute())
                dirPath = QDir(m_Doc.GetDocumentDirectory().toQString()).relativeFilePath(path);
            else
                dirPath = dir.path();
            QFileInfo fi = QFileInfo(dirPath);
            materialName = fi.completeBaseName();
            dirPath = fi.path();
            dirPath.remove(QLatin1String("../"));
            if (dirPath.startsWith(QLatin1String("..")))
                dirPath = dirPath.mid(2);
        } else {
            if (!materialName.startsWith(QLatin1String("materials/")))
                dirPath = QLatin1String("materials");
            materialName = path;
        }
        if (dirPath.size() == 0)
            return materialName;
        return dirPath + QLatin1Char('/') + materialName;
    }

    Qt3DSDMInstanceHandle getMaterial(const QString &path) override
    {
        IObjectReferenceHelper *objRefHelper = m_Doc.GetDataModelObjectReferenceHelper();
        QString name = m_Bridge.getMaterialContainerPath() + QStringLiteral(".")
                + getMaterialNameFromFilePath(path)
                .replace(QLatin1Char('.'), QLatin1String("\\."));
        Qt3DSDMInstanceHandle material;
        CRelativePathTools::EPathType type;
        objRefHelper->ResolvePath(m_Doc.GetSceneInstance(),
                                  Q3DStudio::CString::fromQString(name),
                                  type, material, true);
        return material;
    }

    Qt3DSDMInstanceHandle getOrCreateMaterial(const QString &path,
                                              bool selectCreatedInstance = true) override
    {
        auto material = getMaterial(path);
        if (!material.Valid()) {
            auto parent = getOrCreateMaterialContainer();
            material = CreateSceneGraphInstance(ComposerObjectTypes::Material, parent,
                                                GetAssociatedSlide(parent),
                                                DocumentEditorInsertType::LastChild,
                                                CPt(), PRIMITIVETYPE_UNKNOWN, -1, true,
                                                selectCreatedInstance);
            SetName(material, Q3DStudio::CString::fromQString(getMaterialNameFromFilePath(path)));
        }
        return material;
    }

    void setMaterialProperties(TInstanceHandle instance,
                               const Q3DStudio::CString &materialSourcePath,
                               const QMap<QString, QString> &values,
                               const QMap<QString, QMap<QString, QString>> &textureValues) override
    {
        SetMaterialType(instance, "Referenced Material");
        setMaterialSourcePath(instance, materialSourcePath);
        setMaterialValues(materialSourcePath.toQString(), values, textureValues);
        setMaterialReferenceByPath(instance, materialSourcePath.toQString());
    }

    void setMaterialReferenceByPath(TInstanceHandle instance, const QString &path) override
    {
        Qt3DSDMInstanceHandle material = getOrCreateMaterial(path);
        IObjectReferenceHelper *objRefHelper = m_Doc.GetDataModelObjectReferenceHelper();
        SObjectRefType objRef = objRefHelper->GetAssetRefValue(material, m_Doc.GetSceneInstance(),
                                                               CRelativePathTools::EPATHTYPE_GUID);
        SetInstancePropertyValue(instance,
                                 m_Bridge.GetObjectDefinitions().m_ReferencedMaterial
                                 .m_ReferencedMaterial.m_Property,
                                 objRef, false);
        setReferencedMaterialNameByPath(instance, path);
    }


    void setReferencedMaterialNameByPath(TInstanceHandle instance, const QString &path)
    {
        auto name = getMaterialNameFromFilePath(path);
        int slashIndex = name.lastIndexOf(QLatin1Char('/'));
        if (slashIndex != -1)
            name = name.mid(slashIndex + 1);
        SetName(instance, Q3DStudio::CString::fromQString(name));
    }

    void setMaterialNameByPath(TInstanceHandle instance, const QString &path) override
    {
        SetName(instance, Q3DStudio::CString::fromQString(getMaterialNameFromFilePath(path)));
    }

    void setMaterialSourcePath(TInstanceHandle instance,
                               const Q3DStudio::CString &materialSourcePath) override
    {
        SetInstancePropertyValue(instance, m_Bridge.GetSceneAsset().m_SourcePath,
                                 std::make_shared<CDataStr>(materialSourcePath));
    }

    void setMaterialValues(const QString &path,
                           const QMap<QString, QString> &values,
                           const QMap<QString, QMap<QString, QString>> &textureValues) override
    {
        auto instance = getOrCreateMaterial(path, false);
        if (instance.Valid())
            setMaterialValues(instance, values, textureValues);
    }

    struct ChildInstance
    {
        QString name;
        TInstanceHandle handle;
    };

    void setInstanceValueIfChanged(TInstanceHandle instance, TPropertyHandle prop, SValue value)
    {
        SValue oldValue;
        m_PropertySystem.GetInstancePropertyValue(instance, prop, oldValue);
        if (oldValue != value)
            SetInstancePropertyValue(instance, prop, value);
    }

    QVector<ChildInstance> setPropertyValues(TInstanceHandle instance,
                                             const QMap<QString, QString> &values)
    {
        QVector<ChildInstance> childInstances;
        QMapIterator<QString, QString> i(values);
        while (i.hasNext()) {
            i.next();

            if (!isSaveableMaterialProperty(i.key()))
                continue;

            TCharStr propName(i.key().toStdWString().c_str());
            Q3DStudio::CString propString = Q3DStudio::CString::fromQString(i.value());
            Qt3DSDMPropertyHandle prop
                    = m_PropertySystem.GetAggregateInstancePropertyByName(
                        instance, propName);

            if (m_AnimationSystem.IsPropertyAnimated(instance, prop))
                continue;

            const auto type = m_PropertySystem.GetDataType(prop);
            switch (type) {
            case DataModelDataType::Long4:
            {
                setInstanceValueIfChanged(instance, prop, std::make_shared<CDataStr>(propString));
                SValue value;
                m_PropertySystem.GetInstancePropertyValue(instance, prop, value);
                if (!value.empty()) {
                    if (value.getType() == DataModelDataType::Long4) {
                        SLong4 guid = get<qt3dsdm::SLong4>(value);
                        auto childInstance = m_Bridge.GetInstanceByGUID(guid);
                        if (childInstance.Valid())
                            childInstances.push_back({i.key(), childInstance});
                    }
                }
                break;
            }
            case DataModelDataType::Float:
            {
                setInstanceValueIfChanged(instance, prop, i.value().toFloat());
                break;
            }
            case DataModelDataType::Float2:
            {
                QStringList floats = i.value().split(QStringLiteral(" "));
                if (floats.length() == 2) {
                    SFloat2 value(floats[0].toFloat(), floats[1].toFloat());
                    setInstanceValueIfChanged(instance, prop, value);
                }
                break;
            }
            case DataModelDataType::Float3:
            {
                QStringList floats = i.value().split(QStringLiteral(" "));
                if (floats.length() == 3) {
                    SFloat3 value(floats[0].toFloat(), floats[1].toFloat(), floats[2].toFloat());
                    setInstanceValueIfChanged(instance, prop, value);
                }
                break;
            }
            case DataModelDataType::Bool:
            {
                if (propString == "True")
                    setInstanceValueIfChanged(instance, prop, true);
                else if (propString == "False")
                    setInstanceValueIfChanged(instance, prop, false);
                break;
            }
            case DataModelDataType::String:
            {
                setInstanceValueIfChanged(instance, prop, std::make_shared<CDataStr>(propString));
                break;
            }
            default:
                break;
            }
        }
        return childInstances;
    }

    void setMaterialValues(TInstanceHandle instance, const QMap<QString, QString> &values,
                           const QMap<QString, QMap<QString, QString>> &textureValues) override
    {
        if (values.contains(QStringLiteral("type"))) {
            if (values[QStringLiteral("type")] == QLatin1String("CustomMaterial")
                    && values.contains(QStringLiteral("sourcepath"))) {
                SetMaterialType(instance, Q3DStudio::CString::fromQString(
                                    values[QStringLiteral("sourcepath")]));
                if (values.contains(QStringLiteral("name"))) {
                    SetName(instance, Q3DStudio::CString::fromQString(
                                values[QStringLiteral("name")]));
                }
            }
        }

        const auto childInstances = setPropertyValues(instance, values);

        for (auto &child : childInstances) {
            if (textureValues.contains(child.name))
                setPropertyValues(child.handle, textureValues[child.name]);
        }

        m_Doc.GetCore()->GetDispatch()->FireImmediateRefreshInstance(instance);
    }

    void SetSlideName(TInstanceHandle inSlideInstance, TPropertyHandle propName,
                              const wchar_t *inOldName, const wchar_t *inNewName) override
    {
        SValue theOldValue = std::make_shared<CDataStr>(inOldName);
        SValue theNewValue = std::make_shared<CDataStr>(inNewName);

        // Update the slide name property value
        IPropertySystem &thePropertySystem(m_PropertySystem);
        thePropertySystem.SetInstancePropertyValue(inSlideInstance, propName, theNewValue);

        // Find all actions that point to the old slide name, and change it to new name
        // First, we need to get the owning component instance, for example inSlideInstance is owned
        // by Scene
        Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetSlideByInstance(inSlideInstance);
        if (theSlide.Valid() == false) {
            assert(0);
            return;
        }
        Qt3DSDMInstanceHandle theComponentInstance = m_Bridge.GetOwningComponentInstance(theSlide);
        if (theComponentInstance.Valid() == false) {
            assert(0);
            return;
        }

        // Next, get list of all actions
        TActionHandleList theActions;
        m_ActionCore.GetActions(theActions);
        for (TActionHandleList::iterator theIter = theActions.begin(); theIter != theActions.end();
             ++theIter) {
            // Check if the action target object is the owning component instance, for example if
            // the target object is the Scene
            SActionInfo theActionInfo = m_ActionCore.GetActionInfo(*theIter);
            Qt3DSDMInstanceHandle theTargetInstance =
                m_Bridge.GetInstance(theActionInfo.m_Owner, theActionInfo.m_TargetObject);
            if (theTargetInstance == theComponentInstance) {
                Qt3DSDMHandlerHandle theHandler = m_Bridge.ResolveHandler(theActionInfo);
                if (theHandler.Valid()) {
                    for (THandlerArgHandleList::const_iterator theArgHandle =
                             theActionInfo.m_HandlerArgs.begin();
                         theArgHandle != theActionInfo.m_HandlerArgs.end(); ++theArgHandle) {
                        // and check if handler is Slide type (for example "Go to Slide") that
                        // points to the old slide
                        const SHandlerArgumentInfo &theArgumentInfo =
                            m_ActionCore.GetHandlerArgumentInfo(*theArgHandle);
                        Option<SMetaDataHandlerArgumentInfo> theArgMetaData(
                            m_MetaData.FindHandlerArgumentByName(theHandler,
                                                                 theArgumentInfo.m_Name));
                        if (theArgMetaData.hasValue()
                            && theArgMetaData->m_ArgType == HandlerArgumentType::Slide) {
                            SValue theHandlerValue;
                            m_ActionCore.GetHandlerArgumentValue(*theArgHandle, theHandlerValue);
                            if (Equals(theHandlerValue, theOldValue))
                                // Update action handler argument to point to new slide name
                                m_ActionCore.SetHandlerArgumentValue(*theArgHandle, theNewValue);
                        }
                    }
                }
            }
        }
    }

    void copyMaterialProperties(Qt3DSDMInstanceHandle src, Qt3DSDMInstanceHandle dst) override
    {
        const auto srcSlide = m_SlideSystem.GetApplicableSlide(src);
        const auto dstSlide = m_SlideSystem.GetApplicableSlide(dst);
        const auto name = GetName(dst);
        SValue value;
        qt3dsdm::TPropertyHandleList propList;
        m_PropertySystem.GetAggregateInstanceProperties(src, propList);

        for (auto &prop : propList) {
            const auto name = QString::fromWCharArray(m_PropertySystem.GetName(prop).wide_str());

            if (!isSaveableMaterialProperty(name))
                continue;

            TInstanceHandle srcChild;
            m_PropertySystem.GetInstancePropertyValue(src, prop, value);
            if (!value.empty() && value.getType() == DataModelDataType::Long4) {
                SLong4 guid = get<qt3dsdm::SLong4>(value);
                if (guid.Valid()) {
                    srcChild = m_Bridge.GetInstanceByGUID(guid);
                    const auto path = std::make_shared<CDataStr>(m_Bridge.GetSourcePath(srcChild));
                    SetInstancePropertyValue(dst, prop, path);
                }
            } else {
                m_PropertySystem.SetInstancePropertyValue(dst, prop, value);
            }

            TInstanceHandle dstChild;
            m_PropertySystem.GetInstancePropertyValue(dst, prop, value);
            if (!value.empty() && value.getType() == DataModelDataType::Long4) {
                SLong4 guid = get<qt3dsdm::SLong4>(value);
                if (guid.Valid())
                    dstChild = m_Bridge.GetInstanceByGUID(guid);
            }

            if (srcChild.Valid() && dstChild.Valid())
                CopyProperties(srcSlide, srcChild, dstSlide, dstChild);
        }

        SetName(dst, name);
    }

    void CopyProperties(TSlideHandle inSourceSlide, TInstanceHandle inSourceInstance,
                        TSlideHandle inDestSlide, TInstanceHandle inDestInstance)
    {
        m_SlideCore.CopyProperties(inSourceSlide, inSourceInstance, inDestSlide, inDestInstance);
        m_AnimationCore.CopyAnimations(inSourceSlide, inSourceInstance, inDestSlide,
                                       inDestInstance);
    }

    void UnlinkProperty(TInstanceHandle instance, TPropertyHandle propName) override
    {
        IPropertySystem &thePropertySystem(m_PropertySystem);
        AdditionalMetaDataType::Value thePropertyMetaData =
            thePropertySystem.GetAdditionalMetaDataType(instance, propName);
        Qt3DSDMSlideHandle theAssociatedSlide = m_SlideSystem.GetAssociatedSlide(instance);
        SValue theValue;
        if (thePropertyMetaData == AdditionalMetaDataType::Image) {
            qt3dsdm::Qt3DSDMInstanceHandle theInstance;
            if (m_SlideCore.GetSpecificInstancePropertyValue(theAssociatedSlide, instance, propName,
                                                             theValue)) {
                SLong4 theGuid(get<SLong4>(theValue));
                theInstance = m_Bridge.GetInstanceByGUID(theGuid);
            }
            if (theInstance.Valid() == false)
                theInstance = CreateImageInstanceForMaterialOrLayer(instance, propName);

            if (theInstance)
                UnlinkProperty(theInstance, m_Bridge.GetSourcePathProperty());
        } else {
            // Note that we get the value *before* unlinking.
            m_SlideSystem.UnlinkProperty(instance, propName);
            // WE ignore mesh and import properties because for mesh properties, regardless of link
            // or unlink status, the materials need to stay in the associated slide of the model.
            // for imported hierarchies, the operation of recursively going down the tree and
            // manually
            // setting up a new import hierarchy is too tedious; the artist can just re-import
            // the data.
        }
    }
    void LinkProperty(TInstanceHandle instance, TPropertyHandle propName) override
    {
        IPropertySystem &thePropertySystem(m_PropertySystem);
        AdditionalMetaDataType::Value thePropertyMetaData =
            thePropertySystem.GetAdditionalMetaDataType(instance, propName);
        Qt3DSDMSlideHandle theAssociatedSlide = m_SlideSystem.GetAssociatedSlide(instance);
        SValue theValue;
        if (thePropertyMetaData == AdditionalMetaDataType::Image
            && m_SlideCore.GetSpecificInstancePropertyValue(theAssociatedSlide, instance, propName,
                                                            theValue)) {
            SLong4 theGuid(get<SLong4>(theValue));
            qt3dsdm::Qt3DSDMInstanceHandle theInstance = m_Bridge.GetInstanceByGUID(theGuid);
            if (theInstance) {
                LinkProperty(theInstance, m_Bridge.GetSourcePathProperty());
                // If the instance has no source path property, then we get rid of it automatically.
                m_SlideCore.GetSpecificInstancePropertyValue(
                    theAssociatedSlide, theInstance, m_Bridge.GetSourcePathProperty(), theValue);
                qt3dsdm::TDataStrPtr theSourcePath(get<TDataStrPtr>(theValue));
                if (!theSourcePath || theSourcePath->GetLength() == 0) {
                    DeleteImageInstanceFromMaterialOrLayer(instance, propName);
                }
            }
        } else {
            if (thePropertyMetaData == AdditionalMetaDataType::Import) {
                TSlideHandleList theChildren;
                m_SlideCore.GetChildSlides(theAssociatedSlide, theChildren);
                for (size_t idx = 0, end = theChildren.size(); idx < end; ++idx) {
                    Qt3DSDMSlideHandle theChildSlide(theChildren[idx]);
                    for (long childIdx = 0; childIdx < m_AssetGraph.GetChildCount(instance);
                         ++childIdx) {
                        TInstanceHandle theChild(m_AssetGraph.GetChild(instance, childIdx));
                        if (GetAssociatedSlide(theChild) == theChildSlide && IsImported(theChild)) {
                            DeleteInstance(theChild);
                            --childIdx;
                        }
                    }
                }
            }
            m_SlideSystem.LinkProperty(instance, propName);
        }
    }

    void SetTimeRange(TInstanceHandle inInstance, long inStart, long inEnd) override
    {
        SetStartTime(inInstance, inStart);
        SetEndTime(inInstance, inEnd);
    }

    void SetTimeRangeInSlide(TSlideHandle inSlide, TInstanceHandle inInstance, long inStart,
                                     long inEnd) override
    {
        m_SlideCore.ForceSetInstancePropertyValue(inSlide, inInstance,
                                                  m_Bridge.GetSceneAsset().m_StartTime,
                                                  static_cast<qt3ds::QT3DSI32>(inStart));
        m_SlideCore.ForceSetInstancePropertyValue(inSlide, inInstance,
                                                  m_Bridge.GetSceneAsset().m_EndTime,
                                                  static_cast<qt3ds::QT3DSI32>(inEnd));
    }

    void SetStartTime(TInstanceHandle inInstance, long inStart) override
    {
        m_PropertySystem.SetInstancePropertyValue(inInstance, m_Bridge.GetSceneAsset().m_StartTime,
                                                  static_cast<qt3ds::QT3DSI32>(inStart));
    }

    void SetEndTime(TInstanceHandle inInstance, long inEnd) override
    {
        m_PropertySystem.SetInstancePropertyValue(inInstance, m_Bridge.GetSceneAsset().m_EndTime,
                                                  static_cast<qt3ds::QT3DSI32>(inEnd));
    }

    bool IsAssetNotInActiveSlide(Q3DStudio::TIdentifier inIdentifier)
    {
        Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetAssociatedSlide(inIdentifier);
        Qt3DSDMSlideHandle theActiveSlide = m_Doc.GetActiveSlide();
        // return true to filter the object, apparently.
        bool isInCurrentSlide =
            theSlide == theActiveSlide || theSlide == m_SlideSystem.GetMasterSlide(theActiveSlide);
        return !isInCurrentSlide;
    }
    // The original implementation of this function is absolutely not correct
    // in all cases.
    void GetAssetChildrenInActiveSlide(Qt3DSDMInstanceHandle inInstance, CGraphIterator &outIterator)
    {
        outIterator +=
            Q3DStudio::TFilter(std::bind(&CDocEditor::IsAssetNotInActiveSlide, this,
                                         std::placeholders::_1));
        m_AssetGraph.GetChildren(outIterator, inInstance);
    }

    void ResizeTimeRange(TInstanceHandle inInstance, long inTime, bool inSetStart) override
    {
        // Get the current time range
        std::pair<long, long> theTimeRange = GetTimeRange(inInstance);

        // Change the start time or end time
        if (inSetStart) {
            // Never let the start time get less than 0
            if (inTime < 0)
                inTime = 0;
            // Never let the start time get more than the end time
            else if (inTime > theTimeRange.second)
                inTime = theTimeRange.second;
            // Set start time
            SetStartTime(inInstance, inTime);
        } else {
            // Never let the end time get less than the start time
            if (inTime < theTimeRange.first)
                inTime = theTimeRange.first;
            // Set end time
            SetEndTime(inInstance, inTime);
        }

        // Iterate children and see if we need to resize children time as well
        CGraphIterator theChildren;
        GetAssetChildrenInActiveSlide(inInstance, theChildren);
        for (; !theChildren.IsDone(); ++theChildren) {
            TInstanceHandle theChild = theChildren.GetCurrent();
            // Do not adjust locked children
            SValue locked;
            m_PropertySystem.GetInstancePropertyValue(
                        theChild, m_Bridge.GetSceneAsset().m_Locked, locked);
            if (!qt3dsdm::get<bool>(locked)) {
                std::pair<long, long> theChildTimeRange = GetTimeRange(theChild);
                if (inSetStart) {
                    // If we are resizing start time, if child's start time == parent's child time
                    // then we need to resize child as well
                    if (theChildTimeRange.first == theTimeRange.first)
                        ResizeTimeRange(theChild, inTime, inSetStart);
                } else {
                    // If we are resizing end time, if child's end time == parent's end time
                    // then we need to resize child as well
                    if (theChildTimeRange.second == theTimeRange.second)
                        ResizeTimeRange(theChild, inTime, inSetStart);
                }
            }
        }
    }

    void OffsetTimeRange(TInstanceHandle inInstance, long inOffset) override
    {
        // Get the current time range
        std::pair<long, long> theTimeRange = GetTimeRange(inInstance);

        // Do not allow the object to go into negative time
        if (inOffset < 0 && (-inOffset) > theTimeRange.first) {
            inOffset = -theTimeRange.first;
        }
        SetTimeRange(inInstance, theTimeRange.first + inOffset, theTimeRange.second + inOffset);
        // Offset all the keyframes linked to animations of this instance by this offset.
        m_AnimationCore.OffsetAnimations(m_Doc.GetActiveSlide(), inInstance, inOffset);

        // Offset children time as well
        CGraphIterator theChildren;
        GetAssetChildrenInActiveSlide(inInstance, theChildren);
        for (; !theChildren.IsDone(); ++theChildren) {
            TInstanceHandle theChild = theChildren.GetCurrent();
            // Do not adjust locked children
            SValue locked;
            m_PropertySystem.GetInstancePropertyValue(
                        theChild, m_Bridge.GetSceneAsset().m_Locked, locked);
            if (!qt3dsdm::get<bool>(locked))
                OffsetTimeRange(theChild, inOffset);
        }
    }

    void TruncateTimeRange(TInstanceHandle inInstance, bool inSetStart, long inTime) override
    {
        if (m_Bridge.IsMaterialInstance(inInstance) || m_Bridge.IsImageInstance(inInstance))
            return; // bail!

        // Set the time range if the instance is not the current Component or Scene
        if (inInstance != m_Doc.GetActiveRootInstance()) {
            std::pair<long, long> theRange(GetTimeRange(inInstance));
            if (inSetStart)
                theRange.first = inTime;
            else
                theRange.second = inTime;

            // Ensure the time range is valid before going further.
            if (theRange.first <= theRange.second)
                SetTimeRange(inInstance, theRange.first, theRange.second);
        }

        CGraphIterator theChildren;
        GetAssetChildrenInActiveSlide(inInstance, theChildren);
        for (; !theChildren.IsDone(); ++theChildren) {
            TInstanceHandle theChild = theChildren.GetCurrent();
            // Do not adjust locked children
            SValue locked;
            m_PropertySystem.GetInstancePropertyValue(
                        theChild, m_Bridge.GetSceneAsset().m_Locked, locked);
            if (!qt3dsdm::get<bool>(locked))
                TruncateTimeRange(theChild, inSetStart, inTime);
        }
    }

    void SetTimebarColor(TInstanceHandle inInstance, ::CColor inColor) override
    {
        m_PropertySystem.SetInstancePropertyValue(
            inInstance, m_Bridge.GetSceneAsset().m_TimebarColor,
            qt3dsdm::SFloat3(inColor.GetRed() / 255.0f, inColor.GetGreen() / 255.0f,
                           inColor.GetBlue() / 255.0f));
    }

    void SetTimebarText(TInstanceHandle inInstance, const Q3DStudio::CString &inComment) override
    {
        m_PropertySystem.SetInstancePropertyValue(inInstance,
                                                  m_Bridge.GetSceneAsset().m_TimebarText,
                                                  qt3dsdm::SStringRef(inComment.c_str()));
    }

    void AddChild(Qt3DSDMInstanceHandle parent, Qt3DSDMInstanceHandle child,
                          TInstanceHandle inNextSibling) override
    {
        TInstanceHandle currentParent = m_AssetGraph.GetParent(child);
        if (currentParent.Valid() == false)
            m_AssetGraph.AddChild(parent, child);
        if (inNextSibling.Valid())
            m_AssetGraph.MoveBefore(child, inNextSibling);
        else
            m_AssetGraph.MoveTo(child, parent, COpaquePosition::LAST);
    }
    void RemoveChild(Qt3DSDMInstanceHandle parent, Qt3DSDMInstanceHandle child) override
    {
        if (m_AssetGraph.GetParent(child) == parent) {
            m_AssetGraph.RemoveChild(child, false);
        } else {
            QT3DS_ASSERT(false);
        }
    }

    template <typename TKeyframeType>
    void AddKeyframes(Qt3DSDMAnimationHandle animHandle, const float *keyframeValues, long numValues,
                      long inOffsetInSeconds)
    {
        long numFloatsPerKeyframe = sizeof(TKeyframeType) / sizeof(float);
        if (numValues % numFloatsPerKeyframe) {
            QT3DS_ASSERT(false);
        }
        const TKeyframeType *keyframes = reinterpret_cast<const TKeyframeType *>(keyframeValues);
        long numKeyframes = numValues / numFloatsPerKeyframe;
        for (long idx = 0; idx < numKeyframes; ++idx) {
            TKeyframeType theData(keyframes[idx]);
            theData.m_KeyframeSeconds += inOffsetInSeconds;
            m_AnimationCore.InsertKeyframe(animHandle, theData);
        }
    }

    void SetKeyframeTime(TKeyframeHandle inKeyframe, long inTime) override
    {
        float theTimeinSecs = static_cast<float>(inTime) / 1000.f;
        // round off to 4 decimal place to workaround precision issues
        // TODO: fix this, either all talk float OR long. choose one.
        theTimeinSecs = ceilf(theTimeinSecs * 10000.0f) / 10000.0f;
        TKeyframe theData = m_AnimationCore.GetKeyframeData(inKeyframe);
        // Function programming paradigm, returns new value instead of changing
        // current value.
        theData = qt3dsdm::SetKeyframeSeconds(theData, theTimeinSecs);
        m_AnimationCore.SetKeyframeData(inKeyframe, theData);
    }

    void DeleteAllKeyframes(Qt3DSDMAnimationHandle inAnimation) override
    {
        m_AnimationCore.DeleteAllKeyframes(inAnimation);
    }

    void KeyframeProperty(Qt3DSDMInstanceHandle inInstance, Qt3DSDMPropertyHandle inProperty,
                                  bool inDoDiffValue) override
    {
        m_AnimationSystem.KeyframeProperty(inInstance, inProperty, inDoDiffValue);
    }

    virtual Qt3DSDMAnimationHandle
    CreateOrSetAnimation(Qt3DSDMSlideHandle inSlide, Qt3DSDMInstanceHandle instance,
                         const wchar_t *propName, long subIndex, EAnimationType animType,
                         const float *keyframeValues, long numValues, bool /*inUserEdited*/) override
    {
        Qt3DSDMPropertyHandle propHdl =
            m_DataCore.GetAggregateInstancePropertyByName(instance, propName);
        if (propHdl.Valid() == false) {
            QT3DS_ASSERT(false);
            return 0;
        }
        if (inSlide.Valid() == false) {
            Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetAssociatedSlide(instance);
            if (theSlide.Valid() == false) {
                assert(0);
                return 0;
            }
            if (m_SlideSystem.IsPropertyLinked(instance, propHdl))
                theSlide = m_SlideSystem.GetMasterSlide(theSlide);
            inSlide = theSlide;
        }

        Qt3DSDMAnimationHandle animHandle =
            m_AnimationCore.GetAnimation(inSlide, instance, propHdl, subIndex);

        if (animHandle.Valid() == true)
            m_AnimationCore.DeleteAnimation(animHandle);

        animHandle =
            m_AnimationCore.CreateAnimation(inSlide, instance, propHdl, subIndex, animType, false);

        long theStartTime = GetTimeRange(instance).first;
        long theTimeOffsetInSeconds = long(theStartTime / 1000.f);

        switch (animType) {
        case EAnimationTypeLinear:
            AddKeyframes<SLinearKeyframe>(animHandle, keyframeValues, numValues,
                                          theTimeOffsetInSeconds);
            break;
        case EAnimationTypeBezier:
            AddKeyframes<SBezierKeyframe>(animHandle, keyframeValues, numValues,
                                          theTimeOffsetInSeconds);
            break;
        case EAnimationTypeEaseInOut:
            AddKeyframes<SEaseInEaseOutKeyframe>(animHandle, keyframeValues, numValues,
                                                 theTimeOffsetInSeconds);
            break;
        default:
            QT3DS_ASSERT(false);
            AddKeyframes<SLinearKeyframe>(animHandle, keyframeValues, numValues,
                                          theTimeOffsetInSeconds);
            break;
        }
        return animHandle;
    }
    bool RemoveAnimation(Qt3DSDMSlideHandle inSlide, Qt3DSDMInstanceHandle instance,
                                 const wchar_t *propName, long subIndex) override
    {
        Qt3DSDMPropertyHandle propHdl =
            m_DataCore.GetAggregateInstancePropertyByName(instance, propName);
        if (propHdl.Valid() == false) {
            QT3DS_ASSERT(false);
            return false;
        }
        Qt3DSDMAnimationHandle animHandle =
            m_AnimationCore.GetAnimation(inSlide, instance, propHdl, subIndex);
        if (animHandle.Valid()) {
            m_AnimationCore.DeleteAnimation(animHandle);
            return true;
        }
        return false;
    }

    void SetIsArtistEdited(Qt3DSDMAnimationHandle inAnimation, bool inEdited = true) override
    {
        m_AnimationCore.SetIsArtistEdited(inAnimation, inEdited);
    }

    qt3dsdm::Qt3DSDMInstanceHandle
    FinalizeAddOrDrop(qt3dsdm::Qt3DSDMInstanceHandle inInstance, qt3dsdm::Qt3DSDMInstanceHandle inParent,
                      DocumentEditorInsertType::Enum inInsertType, const CPt &inPosition,
                      bool inSetTimeRangeToParent, bool inSelectInstanceWhenFinished = true,
                      bool checkUniqueName = true, bool notifyRename = true)
    {
        if (inPosition.x != 0 && inPosition.y != 0) {
            Q3DStudio::IDocSceneGraph *theGraph(m_Doc.GetSceneGraph());
            QT3DSVec3 thePos(0, 0, 0);
            if (theGraph) {
                thePos = theGraph->GetIntendedPosition(inInstance, inPosition);
                SetPosition(inInstance, SFloat3(thePos.x, thePos.y, thePos.z));
            } else {
                QT3DS_ASSERT(false);
            }
        }
        RearrangeObject(inInstance, inParent, inInsertType, checkUniqueName, notifyRename);
        if (inSetTimeRangeToParent)
            SetTimeRangeToParent(inInstance);
        if (inSelectInstanceWhenFinished)
            m_Doc.SelectDataModelObject(inInstance);
        return inInstance;
    }

    CString GetName(Qt3DSDMInstanceHandle inInstance) const override
    {
        Option<SValue> theValue = GetInstancePropertyValue(
            inInstance, m_Bridge.GetObjectDefinitions().m_Named.m_NameProp);
        if (theValue.hasValue()) {
            TDataStrPtr theNamePtr(get<TDataStrPtr>(*theValue));
            if (theNamePtr)
                return theNamePtr->GetData();
        }
        return L"";
    }

    CString GetSourcePath(Qt3DSDMInstanceHandle inInstance) const override
    {
        Option<SValue> theValue = GetInstancePropertyValue(
            inInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath);
        if (theValue.hasValue()) {
            TDataStrPtr theNamePtr(get<TDataStrPtr>(*theValue));
            if (theNamePtr)
                return theNamePtr->GetData();
        }
        return L"";
    }

    TInstanceHandle GetFirstBaseClass(Qt3DSDMInstanceHandle inInstance) const override
    {
        TInstanceHandleList theList;
        m_DataCore.GetInstanceParents(inInstance, theList);
        if (theList.size())
            return theList[0];
        return 0;
    }

    void SetName(Qt3DSDMInstanceHandle inInstance, const CString &inName,
                         bool inMakeUnique = false) override
    {
        CString theUniqueName = inName;
        if (inMakeUnique)
            theUniqueName = m_Bridge.GetUniqueChildName(GetParent(inInstance), inInstance, inName);

        SetInstancePropertyValue(inInstance, m_Bridge.GetNameProperty(),
                                 std::make_shared<CDataStr>(theUniqueName.c_str()), false);
    }

    TInstanceHandleList DoPasteSceneGraphObject(std::shared_ptr<IDOMReader> inReader,
                                                TInstanceHandle inNewRoot,
                                                bool inGenerateUniqueName,
                                                DocumentEditorInsertType::Enum inInsertType,
                                                const CPt &inPosition,
                                                bool notifyRename = true)
    {
        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();
        TInstanceHandleList retval = theSerializer->SerializeSceneGraphObject(
            *inReader, m_Doc.GetDocumentDirectory(), inNewRoot, GetActiveSlide(inNewRoot));
        for (size_t idx = 0, end = retval.size(); idx < end; ++idx) {
            qt3dsdm::Qt3DSDMInstanceHandle theInstance(retval[idx]);
            if (inInsertType == DocumentEditorInsertType::NextSibling)
                theInstance = retval[end - idx - 1];

            FinalizeAddOrDrop(theInstance, inNewRoot, inInsertType, inPosition, false, true, true,
                              notifyRename);

            SetName(theInstance, GetName(theInstance), inGenerateUniqueName);
        }

        return retval;
    }

    TInstanceHandleList PasteSceneGraphObject(const CFilePath &inFilePath,
                                                      TInstanceHandle inNewRoot,
                                                      bool inGenerateUniqueName,
                                                      DocumentEditorInsertType::Enum inInsertType,
                                                      const CPt &inPosition) override
    {
        qt3ds::QT3DSI32 theVersion = 0;
        std::shared_ptr<IDOMReader> theReader = m_Doc.CreateDOMReader(
            inFilePath.toCString(), theVersion);
        if (!theReader)
            return TInstanceHandleList();
        return DoPasteSceneGraphObject(theReader, inNewRoot, inGenerateUniqueName, inInsertType,
                                       inPosition, false);
    }

    virtual TInstanceHandleList
    PasteSceneGraphObjectMaster(const CFilePath &inFilePath, TInstanceHandle inNewRoot,
                                bool inGenerateUniqueName,
                                DocumentEditorInsertType::Enum inInsertType, const CPt &inPosition) override
    {
        qt3ds::QT3DSI32 theVersion = 0;
        std::shared_ptr<IDOMReader> theReader = m_Doc.CreateDOMReader(
            inFilePath.toCString(), theVersion);
        if (!theReader)
            return TInstanceHandleList();

        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();
        TInstanceHandleList retval = theSerializer->SerializeSceneGraphObject(
            *theReader, m_Doc.GetDocumentDirectory(), inNewRoot,
            m_Doc.GetStudioSystem()->GetSlideSystem()->GetMasterSlide(GetActiveSlide(inNewRoot)));
        for (size_t idx = 0, end = retval.size(); idx < end; ++idx) {
            qt3dsdm::Qt3DSDMInstanceHandle theInstance(retval[idx]);
            if (inInsertType == DocumentEditorInsertType::NextSibling)
                theInstance = retval[end - idx - 1];

            FinalizeAddOrDrop(theInstance, inNewRoot, inInsertType, inPosition, false, true,
                              true, false);

            SetName(theInstance, GetName(theInstance), inGenerateUniqueName);
        }

        return retval;
    }

    SFloat3 GetPosition(Qt3DSDMInstanceHandle inInstance)
    {
        Option<SValue> theValue =
            GetInstancePropertyValue(inInstance, m_Bridge.GetObjectDefinitions().m_Node.m_Position);
        if (theValue.hasValue())
            return get<SFloat3>(*theValue);
        return SFloat3();
    }

    void SetPosition(Qt3DSDMInstanceHandle inInstance, const SFloat3 &inPos)
    {
        SetInstancePropertyValue(inInstance, m_Bridge.GetObjectDefinitions().m_Node.m_Position,
                                 inPos, false);
    }

    QT3DSU32 BuildGraphOrderItem(qt3dsdm::Qt3DSDMInstanceHandle inInstance, QT3DSU32 inCurrentIndex)
    {
        m_GraphOrderMap.insert(std::make_pair(inInstance.GetHandleValue(), inCurrentIndex));
        ++inCurrentIndex;
        for (long childIdx = 0, childEnd = m_AssetGraph.GetChildCount(inInstance);
             childIdx < childEnd; ++childIdx) {
            inCurrentIndex =
                BuildGraphOrderItem(m_AssetGraph.GetChild(inInstance, childIdx), inCurrentIndex);
        }
        return inCurrentIndex;
    }

    QT3DSU32 GetInstanceGraphOrder(qt3dsdm::Qt3DSDMInstanceHandle inInstance)
    {
        if (m_GraphOrderMap.size() == 0) {
            BuildGraphOrderItem(m_AssetGraph.GetRoot(0), 0);
        }
        std::unordered_map<long, QT3DSU32>::iterator iter = m_GraphOrderMap.find(inInstance);
        if (iter != m_GraphOrderMap.end())
            return iter->second;
        return QT3DS_MAX_U32;
    }

    bool GraphOrderLessThan(qt3dsdm::Qt3DSDMInstanceHandle lhs, qt3dsdm::Qt3DSDMInstanceHandle rhs)
    {
        return GetInstanceGraphOrder(lhs) < GetInstanceGraphOrder(rhs);
    }

    qt3dsdm::TInstanceHandleList ToGraphOrdering(const qt3dsdm::TInstanceHandleList &inInstances)
    {
        qt3dsdm::TInstanceHandleList sortableList(inInstances);
        m_GraphOrderMap.clear();
        std::sort(sortableList.begin(), sortableList.end(),
                  std::bind(&CDocEditor::GraphOrderLessThan, this, std::placeholders::_1,
                            std::placeholders::_2));
        return sortableList;
    }

    void RearrangeObjects(const qt3dsdm::TInstanceHandleList &inInstances,
                                  TInstanceHandle inDest,
                                  DocumentEditorInsertType::Enum inInsertType,
                                  bool checkUniqueName, bool notifyRename = true) override
    {
        qt3dsdm::TInstanceHandleList sortableList(ToGraphOrdering(inInstances));
        TInstanceHandle theParent(inDest);
        if (inInsertType == DocumentEditorInsertType::PreviousSibling
            || inInsertType == DocumentEditorInsertType::NextSibling)
            theParent = GetParent(inDest);

        if (m_Bridge.IsComponentInstance(theParent)
                && moveIntoComponent(inInstances, theParent, checkUniqueName, notifyRename)) {
            return;
        }

        for (size_t idx = 0, end = sortableList.size(); idx < end; ++idx) {
            qt3dsdm::Qt3DSDMInstanceHandle theInstance(sortableList[idx]);
            // If the insert type is next sibling, we have to reverse the list
            // in order to respect the ordering.
            if (inInsertType == DocumentEditorInsertType::NextSibling)
                theInstance = sortableList[end - idx - 1];
            // Rename if the new parent already has object with a same name
            CString currName = m_Bridge.GetName(theInstance);
            if (checkUniqueName) {
                if (!m_Bridge.CheckNameUnique(theParent, theInstance, currName)) {
                    CString newName = m_Bridge.GetUniqueChildName(theParent, theInstance,
                                                                  currName);
                    if (notifyRename) {
                        m_Doc.getMoveRenameHandler()->displayMessageBox(currName.toQString(),
                                                                        newName.toQString());
                    }
                    SetName(theInstance, newName);
                }
            }
            if (inInsertType == DocumentEditorInsertType::PreviousSibling)
                m_AssetGraph.MoveBefore(theInstance, inDest);
            else if (inInsertType == DocumentEditorInsertType::NextSibling)
                m_AssetGraph.MoveAfter(theInstance, inDest);
            else if (inInsertType == DocumentEditorInsertType::LastChild)
                m_AssetGraph.MoveTo(theInstance, inDest, COpaquePosition::LAST);
        }
    }

    // Move all children out of a given parent instances and delete the instances.
    // Typically the parent instances are groups as the function name implies.
    void ungroupObjects(const TInstanceHandleList &inInstances) override
    {
        for (size_t idx = 0, end = inInstances.size(); idx < end; ++idx) {
            TInstanceHandle selected = inInstances[idx];
            if (selected.Valid()) {
                TInstanceHandleList childHandles;
                CGraphIterator children;
                GetAssetChildrenInActiveSlide(selected, children);
                for (; !children.IsDone(); ++children) {
                    TInstanceHandle child = children.GetCurrent();
                    childHandles.push_back(child);
                }

                // Rename the selected and to-be deleted instance so that it is less likely to cause
                // name clash when its children are moved to the same level
                CString name = GetName(selected);
                name.append("@@to_be_deleted@@");
                SetName(selected, name);

                // Move group's children directly below the group item
                RearrangeObjects(childHandles, selected, DocumentEditorInsertType::NextSibling,
                                 true);

                // Delete the group
                DeleteInstance(selected);

                // Select ungrouped instances
                for (size_t i = 0, end = childHandles.size(); i < end; ++i) {
                    if (i == 0 && idx == 0)
                        m_Doc.SelectDataModelObject(childHandles[i]);
                    else
                        m_Doc.ToggleDataModelObjectToSelection(childHandles[i]);
                }
            }
        }
    }

    // Creates a new group object and moves the specified objects as its children
    void groupObjects(const TInstanceHandleList &inInstances) override
    {
        TInstanceHandleList sortedList(ToGraphOrdering(inInstances));

        // Create a new group next to the topmost item in the graph
        TInstanceHandle sibling = sortedList.front();
        Qt3DSDMSlideHandle slide = GetActiveSlide(sibling);
        TInstanceHandle group = CreateSceneGraphInstance(ComposerObjectTypes::Group, sibling, slide,
                                                         DocumentEditorInsertType::PreviousSibling,
                                                         CPt(), PRIMITIVETYPE_UNKNOWN, -1);
        // Move items into the group
        RearrangeObjects(sortedList, group, DocumentEditorInsertType::LastChild, true);
    }

    Qt3DSDMInstanceHandle MakeComponent(const qt3dsdm::TInstanceHandleList &inInstances) override
    {
        if (inInstances.empty())
            return Qt3DSDMInstanceHandle();

        qt3dsdm::TInstanceHandleList theInstances = ToGraphOrdering(inInstances);

        // Get the original start/end times
        QList<std::pair<long, long>> theStartEndTimes;

        for (auto instance : qAsConst(theInstances))
            theStartEndTimes.append(GetTimeRange(instance));

        // Do this in reverse order.
        // first add new component.
        Qt3DSDMSlideHandle theSlide = GetAssociatedSlide(theInstances[0]);

        TInstanceHandle component = CreateSceneGraphInstance(
            ComposerObjectTypes::Component, theInstances[0], theSlide,
            DocumentEditorInsertType::NextSibling, CPt(), PRIMITIVETYPE_UNKNOWN, 0);

        CString theName = GetName(theInstances[0]);

        // now cut the group
        std::shared_ptr<IDOMReader> theReader(CopySceneGraphObjectsToMemory(theInstances));
        DeleteInstances(theInstances);

        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();
        Qt3DSDMSlideHandle theComponentSlide(m_Bridge.GetComponentActiveSlide(component));

        // Paste into the master slide of the new component
        TInstanceHandleList insertedHandles = theSerializer->SerializeSceneGraphObject(
                    *theReader,m_Doc.GetDocumentDirectory(), component,
                    m_SlideSystem.GetMasterSlide(theComponentSlide));

        // Restore the original time range for all objects.
        if (insertedHandles.size()) {
            for (int i = 0; i < theStartEndTimes.size(); i++) {
                if (theStartEndTimes.at(i) != std::make_pair(0L, 0L)) {
                    SetTimeRange(insertedHandles.at(i), theStartEndTimes.at(i).first,
                                 theStartEndTimes.at(i).second);
                }
            }
        }

        SetName(component, theName);

        m_Doc.SelectDataModelObject(component);
        return component;
    }

    void makeAnimatable(const qt3dsdm::TInstanceHandleList &instances) override
    {
        for (auto &instance : instances) {
            const Q3DStudio::CString oldType = GetObjectTypeName(instance);
            if (oldType == "ReferencedMaterial") {
                Qt3DSDMInstanceHandle refMaterial = m_Bridge.getMaterialReference(instance);

                if (refMaterial.Valid()) {
                    const Q3DStudio::CString refType = GetObjectTypeName(refMaterial);
                    Q3DStudio::CString v;
                    if (refType == "CustomMaterial")
                        v = m_Bridge.GetSourcePath(refMaterial);
                    else
                        v = "Standard Material";

                    SetMaterialType(instance, v);
                    copyMaterialProperties(refMaterial, instance);
                } else {
                    SetMaterialType(instance, "Standard Material");
                }

                const auto name = GetName(instance);
                if (!name.toQString().endsWith(QLatin1String("_animatable")))
                    SetName(instance, name + "_animatable");
            }
        }
    }

    // Moves specified instances into target component by a simulated cut and paste.
    // This is only necessary when moving objects from outside the component into the component.
    // Returns true if move was done. Returns false if instances are already in target component,
    // which means a regular rearrange can be done.
    bool moveIntoComponent(const qt3dsdm::TInstanceHandleList &inInstances,
                           const Qt3DSDMInstanceHandle targetComponent, bool checkUniqueName,
                           bool notifyRename)
    {
        if (inInstances.empty())
            return false;

        Qt3DSDMInstanceHandle rootInstance = GetParent(inInstances[0]);
        while (rootInstance.Valid() && !m_Bridge.IsComponentInstance(rootInstance))
            rootInstance = GetParent(rootInstance);

        if (rootInstance == targetComponent)
            return false;

        const qt3dsdm::TInstanceHandleList theInstances = ToGraphOrdering(inInstances);
        QList<std::pair<long, long>> theStartEndTimes;

        for (auto instance : theInstances)
            theStartEndTimes.append(GetTimeRange(instance));

        // Now cut the group from the scene.
        std::shared_ptr<IDOMReader> theReader(CopySceneGraphObjectsToMemory(theInstances));

        DeleteInstances(theInstances);

        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();
        Qt3DSDMSlideHandle theComponentSlide(m_Bridge.GetComponentActiveSlide(targetComponent));

        // Paste into the master slide of the new component.
        TInstanceHandleList insertedHandles =
                theSerializer->SerializeSceneGraphObject(
                    *theReader, m_Doc.GetDocumentDirectory(),
                    targetComponent,
                    m_SlideSystem.GetMasterSlide(theComponentSlide));

        if (insertedHandles.size()) {
            // Restore the original time range for all objects.
            for (int i = 0; i < theStartEndTimes.size(); i++) {
                if (theStartEndTimes.at(i) != std::make_pair(0L, 0L))
                    SetTimeRange(insertedHandles.at(i), theStartEndTimes.at(i).first,
                                 theStartEndTimes.at(i).second);
            }

            // Check for name uniqueness
            if (checkUniqueName) {
                for (auto instance : insertedHandles) {
                    CString currName = m_Bridge.GetName(instance);
                    if (!m_Bridge.CheckNameUnique(targetComponent, instance, currName)) {
                        CString newName = m_Bridge.GetUniqueChildName(
                                    targetComponent, instance, currName);
                        if (notifyRename) {
                            m_Doc.getMoveRenameHandler()->displayMessageBox(currName.toQString(),
                                                                            newName.toQString());
                        }
                        SetName(instance, newName);
                    }
                }
            }
        }
        return true;
    }

    void DuplicateInstances(const qt3dsdm::TInstanceHandleList &inInstances) override
    {

        TInstanceHandleList theInstances = ToGraphOrdering(inInstances);
        if (theInstances.empty())
            return;
        DuplicateInstances(theInstances, theInstances.back(),
                           DocumentEditorInsertType::NextSibling);
    }

    TInstanceHandleList DuplicateInstances(const qt3dsdm::TInstanceHandleList &inInstances,
                                                   TInstanceHandle inDest,
                                                   DocumentEditorInsertType::Enum inInsertType) override
    {
        qt3dsdm::TInstanceHandleList theInstances(ToGraphOrdering(inInstances));
        std::shared_ptr<IDOMReader> theReader(CopySceneGraphObjectsToMemory(theInstances));
        return DoPasteSceneGraphObject(theReader, inDest, true, inInsertType, CPt(), false);
    }

    Qt3DSDMActionHandle AddAction(Qt3DSDMSlideHandle inSlide, Qt3DSDMInstanceHandle inOwner,
                                         const wstring &inEvent, const wstring &inHandler) override
    {
        Q3DStudio::CId theGuid = m_Bridge.GetGUID(inOwner);
        Q3DStudio::TGUIDPacked thePacked(theGuid);
        SLong4 theInitialTriggerTarget(thePacked.Data1, thePacked.Data2, thePacked.Data3,
                                       thePacked.Data4);
        Qt3DSDMActionHandle theAction =
            m_ActionSystem.CreateAction(inSlide, inOwner, theInitialTriggerTarget);
        m_ActionCore.SetEvent(theAction, inEvent);
        m_ActionCore.SetHandler(theAction, inHandler);
        m_Bridge.ResetHandlerArguments(theAction, inHandler);
        return theAction;
    }

    void DeleteAction(Qt3DSDMActionHandle inAction) override
    {
        m_ActionSystem.DeleteAction(inAction);
    }

    Qt3DSDMActionHandle PasteAction(const CFilePath &inFilePath,
                                           Qt3DSDMInstanceHandle inNewRoot) override
    {
        CFileSeekableIOStream theStream(inFilePath.toCString(), FileReadFlags());
        if (theStream.IsOpen() == false) {
            QT3DS_ASSERT(false);
            return 0;
        }
        std::shared_ptr<IDOMFactory> theFactory(
            IDOMFactory::CreateDOMFactory(m_DataCore.GetStringTablePtr()));
        SDOMElement *theElem = CDOMSerializer::Read(*theFactory, theStream);
        if (theElem == NULL) {
            QT3DS_ASSERT(false);
            return 0;
        }
        std::shared_ptr<IDOMReader> theReader(
            IDOMReader::CreateDOMReader(*theElem, m_DataCore.GetStringTablePtr(), theFactory));
        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();
        return theSerializer->SerializeAction(*theReader, inNewRoot, GetActiveSlide(inNewRoot));
    }

    bool ContainsSlideByName(const CString &inName, Qt3DSDMSlideHandle inMasterSlide)
    {
        size_t existingCount = m_SlideSystem.GetSlideCount(inMasterSlide);
        for (size_t idx = 0; idx < existingCount; ++idx) {
            Qt3DSDMSlideHandle theSlide = m_SlideSystem.GetSlideByIndex(inMasterSlide, idx);
            Qt3DSDMInstanceHandle theInstance(m_SlideSystem.GetSlideInstance(theSlide));
            if (GetName(theInstance) == inName)
                return true;
        }
        return false;
    }

    CString GenerateUniqueSlideName(const CString &inStem, Qt3DSDMSlideHandle inMasterSlide,
                                    int inStartIndex)
    {
        size_t theStartIndex = inStartIndex;
        if (theStartIndex < 0)
            theStartIndex = m_SlideSystem.GetSlideCount(inMasterSlide);

        CString baseName = inStem;
        int nameIdx = (int)theStartIndex;
        wchar_t nameBuf[16];
        WStrOps<int>().ToStr(nameIdx, toDataRef(nameBuf, 16));
        CString theNameStr = baseName;
        theNameStr.append(nameBuf);
        while (ContainsSlideByName(theNameStr, inMasterSlide)) {
            ++nameIdx;
            WStrOps<int>().ToStr(nameIdx, toDataRef(nameBuf, 16));
            theNameStr = baseName;
            theNameStr.append(nameBuf);
        }
        return theNameStr;
    }

    void CheckSlideGroupPlayThroughTo(Qt3DSDMSlideHandle inSlide)
    {
        Qt3DSDMSlideHandle theMaster(m_SlideSystem.GetMasterSlide(inSlide));
        size_t slideCount(m_SlideSystem.GetSlideCount(theMaster));
        for (size_t idx = 1; idx < slideCount; ++idx) {
            bool hasPrevious = idx > 1;
            bool hasNext = idx < slideCount - 1;
            Qt3DSDMSlideHandle theCurrentSlide = m_SlideSystem.GetSlideByIndex(theMaster, idx);
            Qt3DSDMInstanceHandle theSlideInstance = m_SlideCore.GetSlideInstance(theCurrentSlide);
            SValue theValue;
            Qt3DSDMPropertyHandle theProp = m_Bridge.GetObjectDefinitions().m_Slide.m_PlaythroughTo;
            m_DataCore.GetInstancePropertyValue(theSlideInstance, theProp, theValue);
            SStringOrInt theData(get<SStringOrInt>(theValue));
            if (theData.GetType() == SStringOrIntTypes::Int) {
                Qt3DSDMSlideHandle theSlide((int)get<long>(theData.m_Value));
                if (m_SlideCore.IsSlide(theSlide) == false) {
                    theData = SStringOrInt(std::make_shared<CDataStr>(L"Next"));
                    m_DataCore.SetInstancePropertyValue(theSlideInstance, theProp, theData);
                }
            }
            // Note that we explicitly run this next section to take care of the situation
            // where the target playthroughto slide was deleted and now we have to deal with it.
            if ((hasNext || hasPrevious) && theData.GetType() == SStringOrIntTypes::String) {
                TDataStrPtr theStrPtr = get<TDataStrPtr>(theData.m_Value);
                if (hasNext == false && AreEqual(L"Next", theStrPtr->GetData()))
                    m_DataCore.SetInstancePropertyValue(
                        theSlideInstance, theProp,
                        SStringOrInt(std::make_shared<CDataStr>(L"Previous")));
                else if (hasPrevious == false && AreEqual(L"Previous", theStrPtr->GetData()))
                    m_DataCore.SetInstancePropertyValue(
                        theSlideInstance, theProp,
                        SStringOrInt(std::make_shared<CDataStr>(L"Next")));
            }
            if (slideCount == 2) {
                theProp = m_Bridge.GetObjectDefinitions().m_Slide.m_PlayMode;
                m_DataCore.GetInstancePropertyValue(theSlideInstance, theProp, theValue);
                TDataStrPtr theStrPtr = get<TDataStrPtr>(theValue);
                if (AreEqual(theStrPtr->GetData(), L"Play Through To..."))
                    m_DataCore.SetInstancePropertyValue(theSlideInstance, theProp,
                                                        std::make_shared<CDataStr>(L"Looping"));
            }
        }
    }

    Qt3DSDMSlideHandle AddSlide(Qt3DSDMSlideHandle inMasterSlide, int inIndex = -1) override
    {
        CString theNewName = GenerateUniqueSlideName(L"Slide", inMasterSlide, inIndex);
        Qt3DSDMSlideHandle theNewSlide = m_SlideSystem.DuplicateSlide(inMasterSlide, inIndex);
        Qt3DSDMInstanceHandle newInstance(m_SlideSystem.GetSlideInstance(theNewSlide));
        m_DataCore.SetInstancePropertyValue(newInstance,
                                            m_Bridge.GetObjectDefinitions().m_Named.m_NameProp,
                                            std::make_shared<CDataStr>(theNewName.c_str()));
        m_Doc.SetActiveSlideWithTransaction(theNewSlide);
        int newSlideIndex = m_SlideSystem.GetSlideIndex(theNewSlide);
        m_SlideSystem.SetActiveSlide(inMasterSlide, newSlideIndex);
        m_Doc.NotifyActiveSlideChanged(theNewSlide, true);
        CheckSlideGroupPlayThroughTo(theNewSlide);
        Qt3DSDMInstanceHandle theInstance = m_Doc.GetSelectedInstance();
        if (theInstance.Valid() && GetAssociatedSlide(theInstance) != inMasterSlide)
            m_Doc.SelectDataModelObject(0);
        return theNewSlide;
    }

    // Only valid if the master slide has more than one slide.
    void DeleteSlide(Qt3DSDMSlideHandle inSlide) override
    {
        TInstanceHandleList theInstances;
        m_SlideSystem.GetAssociatedInstances(inSlide, theInstances);
        for (size_t idx = 0, end = theInstances.size(); idx < end; ++idx) {
            // Action instances are also associated with slides but they need to be deleted
            // by DataModel when the action itself is deleted rather than by us right here.
            TInstanceHandle theInstance(theInstances[idx]);
            if (m_SlideSystem.GetAssociatedSlide(theInstance) == inSlide && IsInstance(theInstance)
                && m_DataCore.IsInstanceOrDerivedFrom(
                       theInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_Instance)) {
                DeleteInstance(theInstance);
            }
        }

        Qt3DSDMSlideHandle theMaster = m_SlideCore.GetParentSlide(inSlide);
        size_t theCount = m_SlideSystem.GetSlideCount(theMaster);
        if (theCount < 2) {
            QT3DS_ASSERT(false);
            return;
        }
        TInstanceHandleList theSlideInstances;
        m_SlideCore.DeleteSlide(inSlide, theSlideInstances);
        m_DataCore.DeleteInstance(theSlideInstances[0]);
        CheckSlideGroupPlayThroughTo(theMaster);
    }

    void RearrangeSlide(Qt3DSDMSlideHandle inSlide, int inNewIndex) override
    {
        Qt3DSDMSlideHandle theMaster = m_SlideSystem.GetMasterSlide(inSlide);
        int theOldIndex = m_SlideSystem.GetSlideIndex(inSlide);
        m_SlideSystem.RearrangeSlide(theMaster, theOldIndex, inNewIndex);
        CheckSlideGroupPlayThroughTo(theMaster);
    }

    Qt3DSDMSlideHandle DuplicateSlide(Qt3DSDMSlideHandle inSlide) override
    {
        std::shared_ptr<IDOMReader> theReader(CopySlide(inSlide));
        if (!theReader)
            return 0;

        Qt3DSDMSlideHandle theMaster = m_SlideSystem.GetMasterSlide(inSlide);
        int theIndex = m_SlideSystem.GetSlideIndex(inSlide);
        std::shared_ptr<IComposerSerializer> theSerializer = m_Doc.CreateSerializer();

        CString theNewName = GenerateUniqueSlideName(L"Slide", theMaster, theIndex + 1);

        Qt3DSDMSlideHandle theNewSlide = theSerializer->SerializeSlide(
            *theReader, m_Doc.GetDocumentDirectory(), theMaster, theIndex);

        Qt3DSDMInstanceHandle newInstance(m_SlideSystem.GetSlideInstance(theNewSlide));
        m_DataCore.SetInstancePropertyValue(newInstance,
                                            m_Bridge.GetObjectDefinitions().m_Named.m_NameProp,
                                            std::make_shared<CDataStr>(theNewName.c_str()));

        // Ensure the active slide change gets recorded in the transaction system so that
        // undo will place us back at the old slide before things start reading from the object
        // model.
        int newSlideIndex = m_SlideSystem.GetSlideIndex(theNewSlide);
        m_SlideSystem.SetActiveSlide(theMaster, newSlideIndex);
        m_Doc.SetActiveSlideWithTransaction(theNewSlide);

        m_Doc.NotifyActiveSlideChanged(theNewSlide, true);
        CheckSlideGroupPlayThroughTo(theNewSlide);
        return theNewSlide;
    }

    Qt3DSDMGuideHandle CreateGuide(const qt3dsdm::SGuideInfo &inInfo) override
    {
        Qt3DSDMGuideHandle retval = m_GuideSystem.CreateGuide();
        m_GuideSystem.SetGuideInfo(retval, inInfo);
        return retval;
    }

    void UpdateGuide(Qt3DSDMGuideHandle hdl, const qt3dsdm::SGuideInfo &inInfo) override
    {
        m_GuideSystem.SetGuideInfo(hdl, inInfo);
    }

    void DeleteGuide(Qt3DSDMGuideHandle hdl) override { m_GuideSystem.DeleteGuide(hdl); }

    void ClearGuides() override
    {
        qt3dsdm::TGuideHandleList theGuides(GetGuides());
        for (size_t idx = 0, end = theGuides.size(); idx < end; ++idx)
            DeleteGuide(theGuides[idx]);
        m_Doc.GetSceneGraph()->RequestRender();
    }

    qt3dsdm::TGuideHandleList GetGuides() const override { return m_GuideSystem.GetAllGuides(); }

    qt3dsdm::SGuideInfo GetGuideInfo(qt3dsdm::Qt3DSDMGuideHandle inGuide) const override
    {
        return m_GuideSystem.GetGuideInfo(inGuide);
    }

    bool IsGuideValid(qt3dsdm::Qt3DSDMGuideHandle inGuide) const override
    {
        return m_GuideSystem.IsGuideValid(inGuide);
    }

    bool AreGuidesEditable() const override { return m_GuideSystem.AreGuidesEditable(); }

    void SetGuidesEditable(bool val) override
    {
        m_GuideSystem.SetGuidesEditable(val);
        if (m_Doc.GetSelectedValue().getType() == Q3DStudio::SelectedValueTypes::Guide
            && val == false)
            m_Doc.NotifySelectionChanged();
    }

    void updateMaterialFiles()
    {
        auto parent = getOrCreateMaterialContainer();
        TInstanceList children;
        GetChildren(GetAssociatedSlide(parent), parent, children);

        for (auto &instance : children) {
            const auto name = GetName(instance).toQString();
            const QString path = getFilePathFromMaterialName(name);
            writeMaterialFile(getOrCreateMaterial(path), name, false, path);
        }
    }

    void updateMaterialInstances(const QStringList &filenames) override
    {
        const auto parent = m_Bridge.getMaterialContainer();
        if (parent.Valid()) {
            TInstanceList children;
            GetChildren(GetAssociatedSlide(parent), parent, children);

            for (auto &instance : children) {
                auto name = GetName(instance).toQString();
                if (name != getMaterialNameFromFilePath(m_Bridge.getDefaultMaterialName())
                        && !filenames.contains(name)) {
                    DeleteInstance(instance);
                }
            }
        }
    }

    void removeUnusedFromMaterialContainer() override
    {
        QVector<Qt3DSDMInstanceHandle> usedMats;
        m_Doc.getUsedSharedMaterials(usedMats);

        const auto parent = m_Bridge.getMaterialContainer();
        if (parent.Valid()) {
            TInstanceList children;
            GetChildren(GetAssociatedSlide(parent), parent, children);

            unsigned int removedChildrenCount = 0;
            for (auto &instance : children) {
                if (!usedMats.contains(instance)) {
                    DeleteInstance(instance);
                    removedChildrenCount++;
                }
            }

            if (removedChildrenCount == children.size())
                DeleteInstance(parent);
        }
    }

    void removeDeletedFromMaterialContainer() override
    {
        const auto parent = m_Bridge.getMaterialContainer();
        if (parent.Valid()) {
            TInstanceList children;
            GetChildren(GetAssociatedSlide(parent), parent, children);

            unsigned int removedChildrenCount = 0;
            for (auto &instance : children) {
                const auto name = GetName(instance).toQString();
                if (name != getMaterialNameFromFilePath(m_Bridge.getDefaultMaterialName())
                        && !QFileInfo(getFilePathFromMaterialName(name)).exists()) {
                    DeleteInstance(instance);
                    removedChildrenCount++;
                }
            }

            if (removedChildrenCount == children.size())
                DeleteInstance(parent);
        }
    }

    TInstanceHandle DoImport(
        CFilePath inImportFilePath, Q3DStudio::CString importSrc, Qt3DSDMInstanceHandle inParent,
        Qt3DSDMInstanceHandle inRoot, Qt3DSDMSlideHandle inSlide, Q3DStudio::CString inDocDir,
        STranslationLog &inTranslationLog,
        function<SImportResult(IComposerEditorInterface &, Q3DStudio::CString)> inImportFunction,
        DocumentEditorInsertType::Enum inInsertType, const CPt &inPosition, long inStartTime)
    {
        CFilePath outputDir(inImportFilePath.GetDirectory());
        bool alwaysKeepDirectory = outputDir.Exists();
        bool keepDirectory = false;
        Qt3DSDMInstanceHandle theRealParent = inInsertType == DocumentEditorInsertType::LastChild
            ? inParent
            : Qt3DSDMInstanceHandle(m_AssetGraph.GetParent(inParent));
        // We have to pass in the real parent to the editor interface so that object lifetimes can
        // be setup correctly as the import tree is being built.
        std::shared_ptr<IComposerEditorInterface> importToComposer =
            IComposerEditorInterface::CreateEditorInterface(*this, theRealParent, inRoot, inSlide,
                                                            inDocDir, inImportFilePath, inStartTime,
                                                            m_StringTable);

        CDispatch &theDispatch(*m_Doc.GetCore()->GetDispatch());
        CFilePath theDestFile(importToComposer->GetDestImportFile());
        try {
            theDispatch.FireOnProgressBegin(QObject::tr("Importing "),
                                            QFileInfo(importSrc.toQString()).fileName());
            SImportResult result = inImportFunction(*importToComposer, theDestFile);
            bool forceError = importToComposer->HasError();
            if (!forceError)
                importToComposer->Finalize(result.m_FilePath);
            keepDirectory = alwaysKeepDirectory || forceError == false;
            theDispatch.FireOnProgressEnd();
            IDocumentEditor::DisplayImportErrors(importSrc.toQString(), result.m_Error,
                                                 m_Doc.GetImportFailedHandler(), inTranslationLog,
                                                 forceError);
            if (!forceError) {
                Qt3DSDMInstanceHandle theImportRoot = importToComposer->GetRoot();
                CFilePath theRelPath(m_Doc.GetRelativePathToDoc(theDestFile));
                SValue theSourcePathValue(std::make_shared<CDataStr>(theRelPath.toCString()));
                Qt3DSDMPropertyHandle theProp(m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath);
                if (inSlide.Valid())
                    m_SlideCore.ForceSetInstancePropertyValue(inSlide, theImportRoot, theProp,
                                                              theSourcePathValue);
                else
                    m_DataCore.SetInstancePropertyValue(theImportRoot, theProp, theSourcePathValue);

                // Do not check for unique name as we set it anyway after getting new handle
                Qt3DSDMInstanceHandle retval =
                    FinalizeAddOrDrop(importToComposer->GetRoot(), inParent, inInsertType,
                                      inPosition, inStartTime == -1, true, false);
                SetName(retval, theRelPath.GetFileStem(), true);

                updateMaterialFiles();

                return retval;
            }
        } catch (...) {
            theDispatch.FireOnProgressEnd();
            m_Doc.RollbackTransaction(); // Run away!!!
        }
        return 0;
    }

    TInstanceHandle ImportDAE(const Q3DStudio::CString &inFullPathToDocument,
                                      TInstanceHandle inParent, TSlideHandle inSlide,
                                      const Q3DStudio::CString &inImportFileExtension,
                                      DocumentEditorInsertType::Enum inDropType,
                                      const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        // If we already have an import file that points back to this DAE then we need to
        // not import the DAE but import the import file again.

        CFilePath importSrc = CFilePath(inFullPathToDocument);
        if (importSrc.Exists() == false)
            return 0;
        CFilePath theRelativeDAE = m_Doc.GetRelativePathToDoc(importSrc);

        CFilePath docPath(m_Doc.GetDocumentPath());
        CFilePath docDir(docPath.GetDirectory());
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());
        if (docPath.size() == 0) {
            if (theHandler)
                theHandler->DisplayImportFailed(importSrc.toQString(),
                                                QObject::tr("Qt3DStudio document has no path"),
                                                false);
            return 0;
        }
        if (!importSrc.IsFile()) {
            if (theHandler)
                theHandler->DisplayImportFailed(importSrc.toQString(),
                                                QObject::tr("Source File Doesn't Exist"), false);
            return 0;
        }

        Q3DStudio::CString fname = importSrc.GetFileStem();

        CFilePath importsDir = CFilePath::CombineBaseAndRelative(docDir, CFilePath(L"Imports"));
        if (importsDir.Exists() == false)
            importsDir.CreateDir(true);

        CFilePath outputDir = Q3DStudio::SFileTools::FindUniqueDestDirectory(importsDir, fname);
        Q3DStudio::CString outputFileName(fname + L"." + inImportFileExtension);
        SColladaTranslator translator(importSrc.toQString());
        TInstanceHandle retval =
            DoImport(CFilePath::CombineBaseAndRelative(outputDir, outputFileName), importSrc,
                     inParent, 0, inSlide, docDir, translator.m_TranslationLog,
                     std::bind(CPerformImport::ImportToComposer, translator,
                               std::placeholders::_1, std::placeholders::_2), inDropType,
                               inPosition, inStartTime);
        if (retval.Valid()) {
            CFilePath theRelativeImport = m_Doc.GetRelativePathToDoc(outputFileName);
            m_ImportFileToDAEMap.insert(
                make_pair(m_StringTable.RegisterStr(theRelativeImport.toCString()),
                          m_StringTable.RegisterStr(theRelativeDAE.toCString())));
        }

        return retval;
    }

    TInstanceHandle LoadImportFile(const Q3DStudio::CString &inFullPathToDocument,
                                           TInstanceHandle inParent, TSlideHandle inSlide,
                                           DocumentEditorInsertType::Enum inDropType,
                                           const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        CFilePath docPath(m_Doc.GetDocumentPath());
        CFilePath docDir(docPath.GetDirectory());
        STranslationLog log;
        return DoImport(inFullPathToDocument, inFullPathToDocument, inParent, 0, inSlide, docDir,
                        log, std::bind(CPerformImport::ImportToComposerFromImportFile,
                                       std::placeholders::_1, std::placeholders::_2),
                                       inDropType, inPosition, inStartTime);
    }

    QString findUniqueMaterialName(const QString &name, const QString &importPath)
    {
        auto materialName = name;
        QString potentialPath = getFilePathFromMaterialName(
                    getMaterialNameFromFilePath(materialName));
        int i = 1;
        const auto originalMaterialName = materialName;
        const QString importFile = QStringLiteral("importfile");
        while (QFileInfo(potentialPath).exists()) {
            i++;
            QString name;
            QMap<QString, QString> values;
            QMap<QString, QMap<QString, QString>> textureValues;
            getMaterialInfo(potentialPath, name, values, textureValues);
            if (values.contains(importFile) && values[importFile] == importPath) {
                const auto material = getOrCreateMaterial(materialName);
                setMaterialValues(material, values, textureValues);
                break;
            }
            materialName = originalMaterialName + QString::number(i);
            potentialPath = getFilePathFromMaterialName(
                        getMaterialNameFromFilePath(materialName));
        }
        return materialName;
    }

    TInstanceHandle createRefMaterialFromImageOrPresentation(
            TInstanceHandle parent, TSlideHandle slide, const CString &absSrc, bool isSubp)
    {
        qt3dsdm::Qt3DSDMInstanceHandle refInstance
                = CreateSceneGraphInstance(ComposerObjectTypes::ReferencedMaterial, parent, slide);
        TInstanceHandle imageMaterial;
        CString relPath;
        QString materialName;
        if (isSubp) {
            relPath = absSrc;
            materialName = findUniqueMaterialName(absSrc.toQString(), relPath.toQString());
            imageMaterial = getOrCreateMaterial(materialName);
            const auto prop = m_Bridge.GetObjectDefinitions().m_Material.m_DiffuseMap1.m_Property;
            setInstanceImagePropertyValue(imageMaterial, prop, absSrc, true);
        } else {
            CFilePath absPath(absSrc);
            relPath = m_Doc.GetRelativePathToDoc(absPath);
            materialName = findUniqueMaterialName(absPath.GetFileStem().toQString(),
                                                  relPath.toQString());
            imageMaterial = getOrCreateMaterial(materialName);
            SetInstancePropertyValueAsImage(
                imageMaterial, m_Bridge.GetDefaultMaterial().m_DiffuseMap1, relPath);
        }
        IDocumentEditor::SetSpecificInstancePropertyValue(0, imageMaterial, L"importfile",
                                                          std::make_shared<CDataStr>(relPath));
        auto sourcePath = writeMaterialFile(imageMaterial, materialName, true);

        setMaterialReferenceByPath(refInstance, materialName);
        setMaterialSourcePath(refInstance, sourcePath);
        SetName(refInstance, CString::fromQString(materialName));
        return refInstance;
    }

    TInstanceHandle AutomapImage(const Q3DStudio::CString &inFullPathToDocument,
                                         TInstanceHandle inParent, TSlideHandle inSlide,
                                         DocumentEditorInsertType::Enum inDropType,
                                         const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        (void)inStartTime;

        CFilePath imageSrc(inFullPathToDocument);
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());

        if (!imageSrc.IsFile()) {
            if (theHandler)
                theHandler->DisplayImportFailed(imageSrc.toQString(),
                                                QObject::tr("Image File Doesn't Exist"), false);
            return 0;
        }
        CFilePath relativePath = m_Doc.GetRelativePathToDoc(imageSrc);
        SImageTextureData theImageBuffer =
            m_Doc.GetBufferCache().GetOrCreateImageBuffer(relativePath);
        if (theImageBuffer.m_Texture == NULL) {
            if (theHandler)
                theHandler->DisplayImportFailed(imageSrc.toQString(),
                                                QObject::tr("Can't Load Image File"), false);
            return 0;
        }

        // Automap the image to a rectangle

        qt3dsdm::Qt3DSDMInstanceHandle theModelInstance =
            CreateSceneGraphInstance(ComposerObjectTypes::Model, inParent, inSlide);
        m_PropertySystem.SetInstancePropertyValue(
            theModelInstance, m_Bridge.GetSourcePathProperty(),
            std::make_shared<qt3dsdm::CDataStr>(
                m_Doc.GetBufferCache().GetPrimitiveName(PRIMITIVETYPE_RECT)));
        // Create the object material
        createRefMaterialFromImageOrPresentation(theModelInstance, inSlide,
                                                 inFullPathToDocument, false);

        if (inStartTime != -1)
            SetStartTime(theModelInstance, inStartTime);

        STextureDetails theDetails = theImageBuffer.m_Texture->GetTextureDetails();
        float theHeight = theDetails.m_Height / 100.0f;
        float theWidth = theDetails.m_Width / 100.0f;
        qt3dsdm::SFloat3 theScale = qt3dsdm::SFloat3(2, 2, 1); // Default, per Danc.
        if (theHeight != 0 && theWidth != 0)
            theScale = qt3dsdm::SFloat3(theWidth, theHeight, 1);
        m_PropertySystem.SetInstancePropertyValue(theModelInstance, m_Bridge.GetNode().m_Scale,
                                                  theScale);

        CFilePath theFilePath(inFullPathToDocument);
        SetName(theModelInstance, theFilePath.GetFileStem(), true);

        // Set the image as the property of the first diffuse map.
        return FinalizeAddOrDrop(theModelInstance, inParent, inDropType, inPosition,
                                 inStartTime == -1);
    }

    TInstanceHandle LoadMesh(const Q3DStudio::CString &inFullPathToDocument,
                                     TInstanceHandle inParent, TSlideHandle inSlide,
                                     DocumentEditorInsertType::Enum inDropType,
                                     const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        CFilePath imageSrc(inFullPathToDocument);
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());
        if (!imageSrc.IsFile()) {
            if (theHandler)
                theHandler->DisplayImportFailed(imageSrc.toQString(),
                                                QObject::tr("Source File Doesn't Exist"), false);
            return 0;
        }
        Q3DStudio::CString theRelativePath(m_Doc.GetRelativePathToDoc(inFullPathToDocument));
        SModelBufferAndPath theModelBuffer =
            m_Doc.GetBufferCache().GetOrCreateModelBuffer(theRelativePath);
        if (theModelBuffer.m_ModelBuffer == NULL) {
            if (theHandler)
                theHandler->DisplayImportFailed(imageSrc.toQString(),
                                                QObject::tr("Could Not Load Model Buffer"), false);
            return 0;
        }
        // Ensure we include the model buffer version in the relative path
        theRelativePath = m_Doc.GetRelativePathToDoc(theModelBuffer.m_FilePath);

        qt3dsdm::Qt3DSDMInstanceHandle theModelInstance =
            CreateSceneGraphInstance(ComposerObjectTypes::Model, inParent, inSlide);

        SValue theValue(std::make_shared<qt3dsdm::CDataStr>(theRelativePath));
        m_PropertySystem.SetInstancePropertyValue(theModelInstance,
                                                  m_Bridge.GetSourcePathProperty(), theValue);

        if (inStartTime != -1)
            SetStartTime(theModelInstance, inStartTime);

        CheckMeshSubsets(theModelInstance, m_Bridge.GetSourcePathProperty());

        SetName(theModelInstance, imageSrc.GetFileStem(), true);

        return FinalizeAddOrDrop(theModelInstance, inParent, inDropType, inPosition,
                                 inStartTime == -1);
    }

    static void *l_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
    {
        (void)ud;
        (void)osize; /* not used */
        if (nsize == 0) {
            free(ptr);
            return NULL;
        } else
            return realloc(ptr, nsize);
    }

    QString LoadScriptFile(const CFilePath &inFile)
    {
        QString retval;

        QQmlEngine engine;
        QString path = inFile.filePath();
        path.replace('\\', '/');
        QQmlComponent component(&engine, QUrl::fromLocalFile(path),
                                QQmlComponent::CompilationMode::PreferSynchronous);
        if (component.status() == QQmlComponent::Error)
            retval = component.errorString().toUtf8().data();

        return retval;
    }

    void DisplayLoadWarnings(const QString &inSrcPath,
                             std::vector<SMetaDataLoadWarning> &inWarnings,
                             const QString &inLoadError)
    {
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());
        if ((inWarnings.empty() && inLoadError.size() == 0) || !theHandler)
            return;

        QString resultDialogStr;

        for (size_t idx = 0, end = inWarnings.size(); idx < end; ++idx) {
            QString theTypeStr;
            QString theMessageStr;

            switch (inWarnings[idx].m_Type) {
            case MetaDataLoadWarningType::InvalidProperty:
                theTypeStr = QObject::tr("Invalid Property");
                break;
            case MetaDataLoadWarningType::InvalidEvent:
                theTypeStr = QObject::tr("Invalid Event");
                break;
            case MetaDataLoadWarningType::InvalidHandler:
                theTypeStr = QObject::tr("Invalid Handler");
                break;
            default:
                QT3DS_ALWAYS_ASSERT_MESSAGE("Unknown load warning type")
                break;
            }

            switch (inWarnings[idx].m_Message) {
            case MetaDataLoadWarningMessage::GeneralError:
                theMessageStr = QObject::tr("General Error");
                break;
            case MetaDataLoadWarningMessage::MissingName:
                theMessageStr = QObject::tr("Missing Name");
                break;
            case MetaDataLoadWarningMessage::InvalidDefault:
                theMessageStr = QObject::tr("Invalid Default");
                break;
            default:
                QT3DS_ALWAYS_ASSERT_MESSAGE("Unknown load warning message")
                break;
            }

            if (inWarnings[idx].m_ExtraInfo.size()) {
                theMessageStr.append(" ");
                theMessageStr.append(QString::fromStdWString(inWarnings[idx].m_ExtraInfo.wide_str()));
            }

            const QString theBuffer = QStringLiteral("%1: %2\n").arg(theTypeStr).arg(theMessageStr);

            resultDialogStr.append(theBuffer);
        }
        if (inLoadError.size()) {
            resultDialogStr.append(QObject::tr("\nError parsing script file: "));
            resultDialogStr.append(inLoadError);
        }
        if (resultDialogStr.size())
            theHandler->DisplayImportFailed(inSrcPath, resultDialogStr, true);
    }

    // Apply meta data to a new dynamic instance.  This sets up the default properties to
    // be what the meta data specifies.
    void ApplyDynamicMetaData(Qt3DSDMInstanceHandle inDynamicInstance,
                              Qt3DSDMInstanceHandle inDynamic)
    {
        std::vector<SMetaDataLoadWarning> theWarnings;
        // For all of the object std::ref properties, check if they have an absolute path
        // reference (path starts with "Scene".  If they do, then attempt to resolve the reference.
        vector<Qt3DSDMMetaDataPropertyHandle> theProperties;
        m_MetaData.GetSpecificMetaDataProperties(inDynamic, theProperties);
        for (size_t propIdx = 0, propEnd = theProperties.size(); propIdx < propEnd; ++propIdx) {
            SMetaDataPropertyInfo theInfo(
                m_MetaData.GetMetaDataPropertyInfo(theProperties[propIdx]));
            if (theInfo.m_CompleteType == CompleteMetaDataType::ObjectRef
                && GetValueType(theInfo.m_DefaultValue) == DataModelDataType::ObjectRef) {
                SObjectRefType theRef(get<SObjectRefType>(theInfo.m_DefaultValue));
                wstring theData;
                wstring theOriginalData;
                if (theRef.GetReferenceType() == ObjectReferenceType::Relative) {
                    TDataStrPtr theRefValue = get<TDataStrPtr>(theRef.m_Value);
                    if (theRefValue) {
                        theData.assign(theRefValue->GetData());
                    }
                }
                theOriginalData = theData;

                if (theData.find(L"Scene") == 0 || theData.size() == 0) {
                    Qt3DSDMInstanceHandle currentInstance = inDynamicInstance;
                    // Resolve this absolute reference string and override the default values
                    // in the datacore to be this exact datatype
                    if (theData.find(L"Scene") == 0) {
                        wstring theItemName;
                        // Walk through the data and attempt to find each object in the asset graph
                        // ignoring slides or anything else.
                        if (theData.size() > 6)
                            theData = theData.substr(6);
                        else
                            theData = L"";
                        currentInstance = m_Doc.GetSceneInstance();
                        while (theData.size() && currentInstance.Valid()) {
                            wstring::size_type thePos = theData.find(L".");
                            if (thePos != wstring::npos) {
                                theItemName = theData.substr(0, thePos);
                                theData = theData.substr(thePos + 1);
                            } else {
                                theItemName = theData;
                                theData = L"";
                            }
                            // Attempt to find the item in the asset graph.
                            long theChildCount = m_AssetGraph.GetChildCount(currentInstance);
                            Qt3DSDMInstanceHandle lastInstance = currentInstance;
                            currentInstance = 0;
                            for (long childIdx = 0;
                                 childIdx < theChildCount && currentInstance.Valid() == false;
                                 ++childIdx) {
                                Qt3DSDMInstanceHandle theChild =
                                    m_AssetGraph.GetChild(lastInstance, childIdx);
                                CString theName(GetName(theChild));
                                if (theName.Compare(theItemName.c_str()))
                                    currentInstance = theChild;
                            }
                        }
                    }

                    if (currentInstance.Valid()) {
                        CId theId(m_Bridge.GetGUID(currentInstance));

                        TGUIDPacked thePackedGuid(theId);
                        qt3dsdm::SLong4 theGuid(thePackedGuid.Data1, thePackedGuid.Data2,
                                              thePackedGuid.Data3, thePackedGuid.Data4);
                        theRef.m_Value = theGuid;
                        // Override the default value with a valid instance.
                        m_DataCore.SetInstancePropertyValue(inDynamic, theInfo.m_Property, theRef);
                    }
                }
            }
        }
    }

    class ISpecificDynamicInstance
    {
    public:
        virtual ~ISpecificDynamicInstance() {}

        virtual Qt3DSDMInstanceHandle GetRootInstance() = 0;
        // returns an error if there was one.  Empty string means no error.
        virtual QString LoadInstanceData(const CFilePath &inAbsPath) = 0;

        virtual std::shared_ptr<IDOMReader>
        ParseInstanceDefinition(const CFilePath &inFullPathToDocument,
                                std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                std::shared_ptr<IImportFailedHandler> inHandler,
                                qt3ds::render::IInputStreamFactory &inInputStreamFactory) = 0;
    };

    virtual TInstanceHandle LoadDynamicInstance(const Q3DStudio::CString &inFullPathToDocument,
                                                TInstanceHandle inParent, TSlideHandle inSlide,
                                                DocumentEditorInsertType::Enum inDropType,
                                                long inStartTime,
                                                ISpecificDynamicInstance &inSpecificInstance,
                                                bool inFinalize)
    {
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        TInstanceHandleList existing;
        m_DataCore.GetInstancesDerivedFrom(existing, inSpecificInstance.GetRootInstance());
        CFilePath theRelativePath(m_Doc.GetRelativePathToDoc(inFullPathToDocument));
        TInstanceHandleList theParents;
        Qt3DSDMInstanceHandle theParentInstance;
        for (size_t idx = 0, end = existing.size(); idx < end && theParentInstance.Valid() == false;
             ++idx) {
            Qt3DSDMInstanceHandle theBehavior(existing[idx]);
            theParents.clear();
            m_DataCore.GetInstanceParents(theBehavior, theParents);
            if (theParents.empty() || theParents[0] != inSpecificInstance.GetRootInstance())
                continue;
            // Ensure this object is *directly* derived from behavior, not indirectly.
            if (theRelativePath.toCString() == GetSourcePath(existing[idx]))
                theParentInstance = existing[idx];
        }

        if (theParentInstance.Valid() == false) {
            std::shared_ptr<IDOMReader> theReaderPtr(inSpecificInstance.ParseInstanceDefinition(
                inFullPathToDocument, m_DataCore.GetStringTablePtr(),
                m_Doc.GetImportFailedHandler(), *m_InputStreamFactory));
            if (theReaderPtr) {
                theParentInstance = m_DataCore.CreateInstance();
                m_DataCore.DeriveInstance(theParentInstance, inSpecificInstance.GetRootInstance());
                m_DataCore.SetInstancePropertyValue(
                    theParentInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath,
                    std::make_shared<CDataStr>(theRelativePath.toCString()));

                m_DataCore.SetInstancePropertyValue(
                    theParentInstance, m_Bridge.GetObjectDefinitions().m_Named.m_NameProp,
                    std::make_shared<CDataStr>(theRelativePath.GetFileStem().c_str()));
                std::vector<SMetaDataLoadWarning> theWarnings;
                m_MetaData.LoadInstance(*theReaderPtr, theParentInstance,
                                        theRelativePath.GetFileStem().c_str(), theWarnings);
                QString theLoadError = inSpecificInstance.LoadInstanceData(inFullPathToDocument);
                DisplayLoadWarnings(inFullPathToDocument.toQString(), theWarnings, theLoadError);
            }
        }
        if (theParentInstance.Valid()) {
            TInstanceHandle retval(IDocumentEditor::CreateSceneGraphInstance(
                theParentInstance, inParent, inSlide, m_DataCore, m_SlideSystem,
                m_Bridge.GetObjectDefinitions(), m_AssetGraph, m_MetaData));

            ApplyDynamicMetaData(retval, theParentInstance);
            if (inStartTime != -1)
                SetStartTime(retval, inStartTime);

            // Set unique name
            SetName(retval, GetName(retval), true);

            if (inFinalize)
                return FinalizeAddOrDrop(retval, inParent, inDropType, CPt(), inStartTime == -1);
            return retval;
        }
        return 0;
    }

    struct CScriptDynamicInstanceLoader : public ISpecificDynamicInstance
    {
        CDocEditor &m_Editor;
        CScriptDynamicInstanceLoader(CDocEditor &ed)
            : m_Editor(ed)
        {
        }

        Qt3DSDMInstanceHandle GetRootInstance() override
        {
            return m_Editor.m_Bridge.GetObjectDefinitions().m_Behavior.m_Instance;
        }
        // returns an error if there was one.  Empty string means no error.
        QString LoadInstanceData(const CFilePath &inAbsPath) override
        {
            return m_Editor.LoadScriptFile(inAbsPath);
        }

        virtual std::shared_ptr<IDOMReader>
        ParseInstanceDefinition(const CFilePath &inFullPathToDocument,
                                std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                std::shared_ptr<IImportFailedHandler> inHandler,
                                qt3ds::render::IInputStreamFactory &inInputStreamFactory) override
        {
            return IDocumentEditor::ParseScriptFile(inFullPathToDocument, inStringTable, inHandler,
                                                    inInputStreamFactory);
        }
    };

    TInstanceHandle LoadBehavior(const Q3DStudio::CString &inFullPathToDocument,
                                         TInstanceHandle inParent, TSlideHandle inSlide,
                                         DocumentEditorInsertType::Enum inDropType,
                                         long inStartTime) override
    {
        TInstanceHandle ret;
        if (inFullPathToDocument.Find(".qml") != Q3DStudio::CString::ENDOFSTRING) {
            CScriptDynamicInstanceLoader loader(*this);
            ret = LoadDynamicInstance(inFullPathToDocument, inParent, inSlide,
                                       inDropType, inStartTime, loader, true);
        }
        return ret;
    }

    struct CRenderPluginDynamicInstanceLoader : public ISpecificDynamicInstance
    {
        CDocEditor &m_Editor;
        CRenderPluginDynamicInstanceLoader(CDocEditor &ed)
            : m_Editor(ed)
        {
        }

        Qt3DSDMInstanceHandle GetRootInstance() override
        {
            return m_Editor.m_Bridge.GetObjectDefinitions().m_RenderPlugin.m_Instance;
        }
        // returns an error if there was one.  Empty string means no error.
        QString LoadInstanceData(const CFilePath &) override
        {
            // We would want to ask the render system to possibly load the dll at this point.
            return QString();
        }

        virtual std::shared_ptr<IDOMReader>
        ParseInstanceDefinition(const CFilePath &inFullPathToDocument,
                                std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                std::shared_ptr<IImportFailedHandler> inHandler,
                                qt3ds::render::IInputStreamFactory &inInputStreamFactory) override
        {
            return IDocumentEditor::ParsePluginFile(inFullPathToDocument, inStringTable, inHandler,
                                                    inInputStreamFactory);
        }
    };

    TInstanceHandle LoadRenderPlugin(const Q3DStudio::CString &inFullPathToDocument,
                                             TInstanceHandle inParent, TSlideHandle inSlide,
                                             DocumentEditorInsertType::Enum inDropType,
                                             long inStartTime) override
    {
        CRenderPluginDynamicInstanceLoader loader(*this);
        TInstanceHandle retval = LoadDynamicInstance(inFullPathToDocument, inParent, inSlide,
                                                     inDropType, inStartTime, loader, false);
        // Insert at the beginning.
        if (m_AssetGraph.GetChildCount(inParent) > 1)
            RearrangeObject(retval, m_AssetGraph.GetChild(inParent, 0),
                            DocumentEditorInsertType::PreviousSibling);
        return retval;
    };

    TInstanceHandle CreateText(const Q3DStudio::CString &inFullPathToDocument,
                               TInstanceHandle inParent, TSlideHandle inSlide,
                               DocumentEditorInsertType::Enum inDropType,
                               const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        (void)inStartTime;

        CFilePath theFontFile(inFullPathToDocument);
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());

        if (!theFontFile.IsFile()) {
            if (theHandler)
                theHandler->DisplayImportFailed(theFontFile.toQString(),
                                                QObject::tr("Font File Doesn't Exist"), false);
            return 0;
        }

        // Get the font name of the font file
        CString theFontName = m_Doc.GetProjectFontName(theFontFile);
        if (theFontName.size() == 0) {
            if (theHandler)
                theHandler->DisplayImportFailed(theFontFile.toQString(),
                                                QObject::tr("Unable to load Font File"), false);
            return 0;
        }

        // Create text instance
        qt3dsdm::Qt3DSDMInstanceHandle theTextInstance =
            CreateSceneGraphInstance(ComposerObjectTypes::Text, inParent, inSlide);

        // Set the Font property to the font file
        m_PropertySystem.SetInstancePropertyValue(theTextInstance, m_Bridge.GetText().m_Font,
                                                  std::make_shared<qt3dsdm::CDataStr>(theFontName));

        if (inStartTime != -1)
            SetStartTime(theTextInstance, inStartTime);

        // Set the name afterwards, do not do uniqueness check here
        auto handle = FinalizeAddOrDrop(theTextInstance, inParent, inDropType, inPosition,
                                        inStartTime == -1, true, false);
        SetName(handle, ComposerObjectTypes::Convert(ComposerObjectTypes::Text), true);
        // TODO: This should work (QT3DS-2278). The line above is a quick fix in case the actual
        // reason for this to have stopped working is not found in time for 2.1 release.
        //SetName(handle, GetName(handle), true);

        return handle;
    }

    typedef void (IMetaData::*TDynamicObjectLoader)(const char *inShaderFile,
                                                    Qt3DSDMInstanceHandle inInstance,
                                                    const TCharStr &inName,
                                                    std::vector<SMetaDataLoadWarning> &outWarnings,
                                                    qt3ds::foundation::IInStream &stream);

    TInstanceHandle LoadDynamicObject(const Q3DStudio::CString &inFullPathToDocument,
                                      TInstanceHandle inParent, TSlideHandle inSlide,
                                      DocumentEditorInsertType::Enum inDropType, long inStartTime,
                                      TDynamicObjectLoader inLoader,
                                      TInstanceHandle inDerivationParent,
                                      TInstanceHandle inTargetId = TInstanceHandle())
    {
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());

        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        CFilePath theShaderFile(inFullPathToDocument);
        if (theShaderFile.GetExtension() == "nvmpe") {
            // If user drag-drop nvmpe file, we find the corresponding glsl file and use it to load
            // the effect.
            CString shaderFile = theShaderFile.toCString();
            CString newShaderFile = shaderFile.substr(0, shaderFile.Length() - 5);
            newShaderFile.append("glsl");
            theShaderFile = CFilePath(newShaderFile);
        }

        TInstanceHandleList existing;
        m_DataCore.GetInstancesDerivedFrom(existing, inDerivationParent);
        CFilePath theRelativePath(m_Doc.GetRelativePathToDoc(theShaderFile));
        TInstanceHandleList theParents;
        Qt3DSDMInstanceHandle theParentInstance;
        for (size_t idx = 0, end = existing.size(); idx < end && theParentInstance.Valid() == false;
             ++idx) {
            Qt3DSDMInstanceHandle theEffect(existing[idx]);
            theParents.clear();
            m_DataCore.GetInstanceParents(theEffect, theParents);
            if (theParents.empty() || theParents[0] != inDerivationParent)
                continue;
            // Ensure this object is *directly* derived from Effect, not indirectly.
            if (theRelativePath.toCString() == GetSourcePath(existing[idx]))
                theParentInstance = existing[idx];
        }

        if (theParentInstance.Valid() == false) {
            if (theShaderFile.Exists()) {
                theParentInstance = m_DataCore.CreateInstance();
                m_DataCore.DeriveInstance(theParentInstance, inDerivationParent);
                m_DataCore.SetInstancePropertyValue(
                    theParentInstance, m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath,
                    std::make_shared<CDataStr>(theRelativePath.toCString()));

                m_DataCore.SetInstancePropertyValue(
                    theParentInstance, m_Bridge.GetObjectDefinitions().m_Named.m_NameProp,
                    std::make_shared<CDataStr>(theRelativePath.GetFileStem().c_str()));

                std::vector<SMetaDataLoadWarning> theWarnings;
                QString shaderFile = theShaderFile.toQString();
                NVScopedRefCounted<qt3ds::render::IRefCountedInputStream> theStream(
                    m_InputStreamFactory->GetStreamForFile(shaderFile));
                (m_MetaData.*inLoader)(m_StringTable.GetNarrowStr(theRelativePath.toCString()),
                                       theParentInstance,
                                       theRelativePath.GetFileStem().c_str(),
                                       theWarnings,
                                       *theStream);
                IDocumentEditor::fixDefaultTexturePaths(theParentInstance);
                DisplayLoadWarnings(shaderFile, theWarnings, QString());
            } else {
                if (theHandler)
                    theHandler->DisplayImportFailed(theShaderFile.toQString(),
                                                    QObject::tr("Unable to load Shader File"),
                                                    false);
                return 0;
            }
        }

        TInstanceHandle retval(IDocumentEditor::CreateSceneGraphInstance(
            theParentInstance, inParent, inSlide, m_DataCore, m_SlideSystem,
            m_Bridge.GetObjectDefinitions(), m_AssetGraph, m_MetaData, inTargetId));

        if (inStartTime != -1)
            SetStartTime(retval, inStartTime);

        // Set unique name
        SetName(retval, GetName(retval), true);

        return FinalizeAddOrDrop(retval, inParent, inDropType, CPt(), inStartTime == -1);
    }

    TInstanceHandle LoadEffect(const Q3DStudio::CString &inFullPathToDocument,
                                       TInstanceHandle inParent, TSlideHandle inSlide,
                                       DocumentEditorInsertType::Enum inDropType, long inStartTime) override
    {
        return LoadDynamicObject(inFullPathToDocument, inParent, inSlide, inDropType, inStartTime,
                                 &IMetaData::LoadEffectInstance,
                                 m_Bridge.GetObjectDefinitions().m_Effect.m_Instance);
    }

    TInstanceHandle LoadCustomMaterial(const Q3DStudio::CString &inFullPathToDocument,
                                               TInstanceHandle inParent, TSlideHandle inSlide,
                                               DocumentEditorInsertType::Enum inDropType,
                                               long inStartTime,
                                               TInstanceHandle inTargetId = TInstanceHandle()) override
    {
        return LoadDynamicObject(inFullPathToDocument, inParent, inSlide, inDropType, inStartTime,
                                 &IMetaData::LoadMaterialInstance,
                                 m_Bridge.GetObjectDefinitions().m_CustomMaterial.m_Instance,
                                 inTargetId);
    }

    static void eatspace(const char8_t *str)
    {
        while (!isTrivial(str) && *str == ' ') {
            ++str;
        }
    }

    void SetUniqueName(TInstanceHandle inItem, const char8_t *inNameBase,
                       eastl::vector<Q3DStudio::CString> &inExistingNames)
    {
        Q3DStudio::CString theName(inNameBase);
        QT3DSU32 idx = 1;
        while (eastl::find(inExistingNames.begin(), inExistingNames.end(), theName)
               != inExistingNames.end()) {
            char8_t nameBuffer[64];
            sprintf(nameBuffer, "%d", idx);
            ++idx;
            theName.assign(inNameBase);
            theName.append("_");
            theName.append(nameBuffer);
        }
        SetName(inItem, theName, false);
        inExistingNames.push_back(theName);
    }

    virtual TInstanceHandle LoadPathBuffer(const Q3DStudio::CString &inFullPathToDocument,
                                           TInstanceHandle inParent, TSlideHandle inSlide,
                                           DocumentEditorInsertType::Enum inDropType,
                                           long inStartTime)
    {
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());
        Q3DStudio::CString relPath = m_Doc.GetRelativePathToDoc(inFullPathToDocument);
        TInstanceHandle retval =
            CreateSceneGraphInstance(ComposerObjectTypes::Path, inParent, inSlide);
        Q3DStudio::CFilePath theFilePath(relPath);

        SetName(retval, theFilePath.GetFileStem().GetCharStar(), true);
        CreateSceneGraphInstance(ComposerObjectTypes::Material, retval, inSlide);
        {
            TInstanceHandle strokeMaterial = m_AssetGraph.GetChild(retval, 0);
            SetName(strokeMaterial, L"Stroke");
        }

        qt3dsdm::ISlideCore &theSlideCore(
            *m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetTransactionlessSlideCore());
        theSlideCore.ForceSetInstancePropertyValue(
            inSlide, retval, m_Bridge.GetObjectDefinitions().m_Path.m_PathType,
            TDataStrPtr(new CDataStr(L"Painted")));
        SetInstancePropertyValue(retval, m_Bridge.GetObjectDefinitions().m_Asset.m_SourcePath,
                                 TDataStrPtr(new CDataStr(relPath.c_str())));
        FinalizeAddOrDrop(retval, inParent, inDropType, CPt(), inStartTime == -1, false);
        return retval;
    }

    TInstanceHandle ImportFile(DocumentEditorFileType::Enum inFileType,
                                       const Q3DStudio::CString &inFullPathToDocument,
                                       TInstanceHandle inParent, TSlideHandle inSlide,
                                       const Q3DStudio::CString &inImportFileExtension,
                                       DocumentEditorInsertType::Enum inDropType,
                                       const CPt &inPosition = CPt(), long inStartTime = -1) override
    {
        std::shared_ptr<IImportFailedHandler> theHandler(m_Doc.GetImportFailedHandler());
        switch (inFileType) {
        case DocumentEditorFileType::DAE:
            return ImportDAE(inFullPathToDocument, inParent, inSlide, inImportFileExtension,
                             inDropType, inPosition, inStartTime);
        case DocumentEditorFileType::Image:
            return AutomapImage(inFullPathToDocument, inParent, inSlide, inDropType, inPosition,
                                inStartTime);
        case DocumentEditorFileType::Mesh:
            return LoadMesh(inFullPathToDocument, inParent, inSlide, inDropType, inPosition,
                            inStartTime);
        case DocumentEditorFileType::Import:
            return LoadImportFile(inFullPathToDocument, inParent, inSlide, inDropType, inPosition,
                                  inStartTime);
        case DocumentEditorFileType::Behavior:
            return LoadBehavior(inFullPathToDocument, inParent, inSlide, inDropType, inStartTime);
        case DocumentEditorFileType::Font:
            return CreateText(inFullPathToDocument, inParent, inSlide, inDropType, inPosition,
                              inStartTime);
        case DocumentEditorFileType::Effect:
            return LoadEffect(inFullPathToDocument, inParent, inSlide, inDropType, inStartTime);
        case DocumentEditorFileType::Material:
            return LoadCustomMaterial(inFullPathToDocument, inParent, inSlide, inDropType,
                                      inStartTime);
        default: {
            if (theHandler)
                theHandler->DisplayImportFailed(inFullPathToDocument.toQString(),
                                                QObject::tr("Unsupported Document Editor Type (at this time!)"),
                                                false);
            break;
        }
        }
        return 0;
    }

    void DepthFirstAddImportChildren(TSlideHandle inSlide, TInstanceHandle inInstance,
                                     TIdMultiMap &inMap, std::unordered_set<int> &ioAddedChildren)
    {
        TCharPtr theId = m_StringTable.RegisterStr(GetImportId(inInstance).c_str());
        if (!IsTrivial(theId) && m_SlideSystem.GetAssociatedSlide(inInstance) == inSlide) {
            pair<TIdMultiMap::iterator, bool> theResult =
                inMap.insert(make_pair(theId, vector<pair<TSlideHandle, TInstanceHandle>>()));
            insert_unique(theResult.first->second, make_pair(inSlide, inInstance));
            ioAddedChildren.insert(inInstance);
        }

        for (long idx = 0, end = m_AssetGraph.GetChildCount(inInstance); idx < end; ++idx) {
            TInstanceHandle theInstance = m_AssetGraph.GetChild(inInstance, idx);
            DepthFirstAddImportChildren(inSlide, theInstance, inMap, ioAddedChildren);
        }
    }

    // Precondition is that our source path to instance map
    // has all of the source-path-to-instance hooks already looked up.
    void DoRefreshImport(const CFilePath &inOldFile, const CFilePath &inNewFile)
    {
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        vector<CFilePath> importFileList;

        // Find which import files use this dae file.
        for (TCharPtrToSlideInstanceMap::iterator theIter = m_SourcePathInstanceMap.begin(),
                                                  end = m_SourcePathInstanceMap.end();
             theIter != end; ++theIter) {
            CFilePath theSource(theIter->first);
            if (theSource.GetExtension().Compare(L"import", CString::ENDOFSTRING, false)) {
                CFilePath theFullPath = m_Doc.GetResolvedPathToDoc(theSource);
                if (theFullPath.Exists() && theFullPath.IsFile()) {
                    if (std::find(importFileList.begin(), importFileList.end(),
                                  theFullPath.filePath())
                        == importFileList.end()) {
                        ImportPtrOrError theImport = Import::Load(theFullPath.toCString());
                        if (theImport.m_Value) {
                            CFilePath theSrcFile = CFilePath::CombineBaseAndRelative(
                                CFilePath(theImport.m_Value->GetDestDir()),
                                CFilePath(theImport.m_Value->GetSrcFile()));
                            if (theSrcFile.toCString().Compare(
                                inOldFile.toCString(), false))
                                importFileList.push_back(theFullPath.filePath());
                            theImport.m_Value->Release();
                        }
                    }
                }
            }
        }
        TCharPtrToSlideInstanceMap theImportPaths;
        GetImportPathToInstanceMap(theImportPaths);
        std::unordered_set<int> theAddedInstances;

        // OK, for each import file
        // 1.  Find each group in the system using that import file as its source path.
        // 2.  for each group we find, build a map of import id->item that we will use to
        //		 communicate the import changes to the item.
        // 4.  Run the refresh process using a composer editor that runs off of our
        //		mappings
        TIdMultiMap theGroupIdMap;
        for (size_t importIdx = 0, end = importFileList.size(); importIdx < end; ++importIdx) {
            theGroupIdMap.clear();
            CFilePath theImportFilePath = importFileList[importIdx];
            CFilePath theImportRelativePath = m_Doc.GetRelativePathToDoc(theImportFilePath);
            TCharPtrToSlideInstanceMap::iterator theIter =
                m_SourcePathInstanceMap.find(m_StringTable.RegisterStr(theImportRelativePath.toCString()));
            if (theIter == m_SourcePathInstanceMap.end())
                continue;
            // First pass just build the group id entries.  This avoids us copying hashtables which
            // may
            // be quite expensive
            for (TSlideInstanceList::iterator theSlideInst = theIter->second.begin(),
                                              theSlideInstEnd = theIter->second.end();
                 theSlideInst != theSlideInstEnd; ++theSlideInst) {
                TInstanceHandle theRoot = theSlideInst->second;
                TSlideHandle theSlide = theSlideInst->first;

                // For a depth first search of all children of this object *in this slide*,
                // if they have an import id then add them to the map.
                DepthFirstAddImportChildren(theSlide, theRoot, theGroupIdMap, theAddedInstances);
                TIdMultiMap::iterator theGroupId =
                    theGroupIdMap
                        .insert(make_pair(m_StringTable.GetWideStr(GetImportId(theRoot)),
                                          vector<pair<Qt3DSDMSlideHandle, Qt3DSDMInstanceHandle>>()))
                        .first;
                insert_unique(theGroupId->second, make_pair(theSlide, theRoot));
                theAddedInstances.insert(theRoot);
            }
            // Since some objects may be completely free standing, we need to go through *all*
            // objects.
            // Unfortunately the first revision of the system didn't put import paths on objects so
            // we need both the above loop *and* to consider every object who's import path matches
            // out import document's relative path.
            theIter = theImportPaths.find(m_StringTable.RegisterStr(theImportRelativePath.toCString()));
            TSlideHandleList theAssociatedSlides;
            if (theIter != theImportPaths.end()) {
                vector<pair<Qt3DSDMSlideHandle, Qt3DSDMInstanceHandle>> &theInstances =
                    theIter->second;
                for (size_t freeInstanceIdx = 0, end = theInstances.size(); freeInstanceIdx < end;
                     ++freeInstanceIdx) {
                    if (theAddedInstances.find(theInstances[freeInstanceIdx].second)
                        != theAddedInstances.end())
                        continue;
                    theAssociatedSlides.clear();
                    Qt3DSDMInstanceHandle theInstance(theInstances[freeInstanceIdx].second);
                    GetAllAssociatedSlides(theInstance, theAssociatedSlides);
                    TIdMultiMap::iterator theInstanceId =
                        theGroupIdMap
                            .insert(
                                make_pair(m_StringTable.GetWideStr(GetImportId(theInstance)),
                                          vector<pair<Qt3DSDMSlideHandle, Qt3DSDMInstanceHandle>>()))
                            .first;
                    for (size_t slideIdx = 0, slideEnd = theAssociatedSlides.size();
                         slideIdx < slideEnd; ++slideIdx)
                        insert_unique(theInstanceId->second,
                                      make_pair(theAssociatedSlides[slideIdx], theInstance));
                    theAddedInstances.insert(theInstance);
                }
            }

            //
            // OK, we have distinct maps sorted on a per-slide basis for all trees of children
            // of this asset.  We now need to attempt to run the refresh algorithm.

            qt3dsimp::ImportPtrOrError theImportPtr = qt3dsimp::Import::Load(theImportFilePath.toCString());
            if (theImportPtr.m_Value == NULL) {
                QT3DS_ASSERT(false);
                continue;
            }

            if (inNewFile.Exists() == false) {
                QT3DS_ASSERT(false);
                continue;
            }

            // Select correct translator according to file type
            ITranslator *translator = nullptr;
            STranslationLog *translationLog = nullptr;
            Q3DStudio::CString newExtension(inNewFile.GetExtension());
            Q3DStudio::CString oldExtension(inOldFile.GetExtension());
            if (newExtension.Compare(CDialogs::GetWideDAEFileExtension(),
                Q3DStudio::CString::ENDOFSTRING, false)
                && oldExtension.Compare(CDialogs::GetWideDAEFileExtension(),
                    Q3DStudio::CString::ENDOFSTRING, false)) {
                SColladaTranslator *colladaTranslator = new SColladaTranslator(inNewFile.toQString());
                translationLog = &(colladaTranslator->m_TranslationLog);
                translator = colladaTranslator;
#ifdef QT_3DSTUDIO_FBX
            } else if (newExtension.Compare(CDialogs::GetWideFbxFileExtension(),
                Q3DStudio::CString::ENDOFSTRING, false)
                && oldExtension.Compare(CDialogs::GetWideFbxFileExtension(),
                    Q3DStudio::CString::ENDOFSTRING, false)) {
                SFbxTranslator *fbxTranslator = new SFbxTranslator(inNewFile.toQString());
                translationLog = &(fbxTranslator->m_TranslationLog);
                translator = fbxTranslator;
#endif
            } else {
                STranslationLog emptyLog;
                IDocumentEditor::DisplayImportErrors(inNewFile.toQString(),
                    ImportErrorCodes::TranslationToImportFailed,
                    m_Doc.GetImportFailedHandler(), emptyLog, true);
                continue;
            }

            std::shared_ptr<IComposerEditor> theComposer(
                IComposerEditorInterface::CreateEditorInterface(
                    *this, theGroupIdMap, m_Doc.GetDocumentDirectory(), theImportFilePath, 0,
                    m_StringTable, m_AssetGraph));

            SImportResult theImportResult = CPerformImport::RefreshToComposer(
                *translator, *theComposer, *theImportPtr.m_Value, theImportFilePath);

            IDocumentEditor::DisplayImportErrors(inNewFile.toQString(), theImportResult.m_Error,
                m_Doc.GetImportFailedHandler(),
                *translationLog, false);
        }

        updateMaterialFiles();
    }

    void RefreshImport(const CFilePath &inOldFile, const CFilePath &inNewFile) override
    {
        CDispatch &theDispatch(*m_Doc.GetCore()->GetDispatch());
        theDispatch.FireOnProgressBegin(
            QObject::tr("Refreshing Import "), QFileInfo(inNewFile.toQString()).fileName());
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        try {
            m_SourcePathInstanceMap.clear();
            GetSourcePathToInstanceMap(m_SourcePathInstanceMap, false);
            DoRefreshImport(inOldFile, inNewFile);
        } catch (...) {
        }
        theDispatch.FireOnProgressEnd();
    }

    bool CleanUpMeshes() override
    {
        CDispatch &theDispatch(*m_Doc.GetCore()->GetDispatch());
        theDispatch.FireOnProgressBegin(
                    QObject::tr("Old UIP version"), QObject::tr("Cleaning up meshes"));
        ScopedBoolean __ignoredDirs(m_IgnoreDirChange);
        bool cleanedSome = false;
        try {
            vector<CFilePath> importFileList;
            m_SourcePathInstanceMap.clear();
            GetSourcePathToInstanceMap(m_SourcePathInstanceMap, false);
            for (TCharPtrToSlideInstanceMap::iterator theIter = m_SourcePathInstanceMap.begin(),
                                                      end = m_SourcePathInstanceMap.end();
                 theIter != end; ++theIter) {
                CFilePath theSource(theIter->first);
                if (theSource.GetExtension().Compare(L"mesh", CString::ENDOFSTRING, false)) {
                    CFilePath theFullPath = m_Doc.GetResolvedPathToDoc(theSource);

                    if (!theFullPath.Exists() || !theFullPath.isFile()
                            || Mesh::GetHighestMultiVersion(theFullPath.toCString().GetCharStar())
                            == 1) {
                        continue;
                    }

                    Mesh *theMesh = Mesh::LoadMulti(
                                theFullPath.toCString().GetCharStar(),
                                Mesh::GetHighestMultiVersion(
                                    theFullPath.toCString().GetCharStar()));

                    if (!theMesh)
                        continue;

                    // Import file still has revisions, so we need to use SaveMulti for saving
                    // the mesh file with correct revision number.
                    // Once import file revisioning has been removed (QT3DS-1815), this can be
                    // replaced with theMesh->Save(theFullPath.toCString().GetCharStar());
                    // It also requires ripping the revisions out from the *.import files
                    Qt3DSFileToolsSeekableMeshBufIOStream output(
                                SFile::Wrap(SFile::OpenForWrite(theFullPath, FileWriteFlags()),
                                            theFullPath));
                    if (!output.IsOpen())
                        QT3DS_ALWAYS_ASSERT_MESSAGE(theFullPath.toCString().GetCharStar());
                    MallocAllocator allocator;
                    theMesh->SaveMulti(allocator, output);

                    delete theMesh;

                    cleanedSome = true;
                }
            }
        } catch (...) {
        }
        theDispatch.FireOnProgressEnd();

        return cleanedSome;
    }

    void ExternalizePath(TInstanceHandle path) override
    {
        CFilePath thePathsDirectory(
            CFilePath::CombineBaseAndRelative(m_Doc.GetDocumentDirectory(), L"paths"));
        thePathsDirectory.CreateDir(true);
        Q3DStudio::CString theName = GetName(path);
        CFilePath theTargetFileName(CFilePath::CombineBaseAndRelative(thePathsDirectory, theName));
        theTargetFileName.setFile(theTargetFileName.filePath() + ".path");
        if (theTargetFileName.Exists()) {
            CString targetFile = theTargetFileName.toCString();
            CFilePath tempPath(targetFile.substr(0, targetFile.size() - 5));
            QT3DSU32 index = 1;
            do {
                wchar_t buffer[64];
                swprintf(buffer, 64, L"%d", index);
                tempPath.setFile(
                    tempPath.filePath() + "_" + QString::fromWCharArray(buffer));
                ++index;
            } while (tempPath.Exists());
            theTargetFileName = tempPath;
            theTargetFileName.setFile(theTargetFileName.filePath() + ".path");
        }
        NVScopedRefCounted<IPathBufferBuilder> theBuilder(
            IPathBufferBuilder::CreateBuilder(*this->m_Foundation.m_Foundation));

        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        TPropertyHandle positionProp(theDefinitions.m_PathAnchorPoint.m_Position.m_Property);
        TPropertyHandle angleProp(theDefinitions.m_PathAnchorPoint.m_IncomingAngle.m_Property);
        TPropertyHandle incomingdistanceProp(
            theDefinitions.m_PathAnchorPoint.m_IncomingDistance.m_Property);
        TPropertyHandle outgoingdistanceProp(
            theDefinitions.m_PathAnchorPoint.m_OutgoingDistance.m_Property);
        TPropertyHandle closedProp(theDefinitions.m_SubPath.m_Closed.m_Property);

        eastl::vector<TInstanceHandle> theSubPathChildren;

        for (QT3DSI32 pathChildIdx = 0, pathChildEnd = m_AssetGraph.GetChildCount(path);
             pathChildIdx < pathChildEnd; ++pathChildIdx) {
            TInstanceHandle pathChild(m_AssetGraph.GetChild(path, pathChildIdx));
            if (GetObjectTypeName(pathChild) == L"SubPath") {
                theSubPathChildren.push_back(pathChild);
                bool isClosed = GetTypedInstancePropertyValue<bool>(pathChild, closedProp);
                TInstanceHandle theLastAnchor;
                for (QT3DSI32 subPathChildIdx = 0,
                           subPathChildEnd = m_AssetGraph.GetChildCount(pathChild);
                     subPathChildIdx < subPathChildEnd; ++subPathChildIdx) {
                    TInstanceHandle theAnchor(m_AssetGraph.GetChild(pathChild, subPathChildIdx));
                    QT3DSVec2 position =
                        ToFnd(GetTypedInstancePropertyValue<SFloat2>(theAnchor, positionProp));
                    if (subPathChildIdx == 0)
                        theBuilder->MoveTo(position);
                    else {
                        QT3DSVec2 prevPos = ToFnd(
                            GetTypedInstancePropertyValue<SFloat2>(theLastAnchor, positionProp));
                        QT3DSF32 prevAngle =
                            GetTypedInstancePropertyValue<float>(theLastAnchor, angleProp) + 180.0f;
                        QT3DSF32 prevDistance = GetTypedInstancePropertyValue<float>(
                            theLastAnchor, outgoingdistanceProp);
                        QT3DSVec2 c1 = IPathManager::GetControlPointFromAngleDistance(
                            prevPos, prevAngle, prevDistance);

                        QT3DSF32 angle = GetTypedInstancePropertyValue<float>(theAnchor, angleProp);
                        QT3DSF32 distance =
                            GetTypedInstancePropertyValue<float>(theAnchor, incomingdistanceProp);
                        QT3DSVec2 c2 = IPathManager::GetControlPointFromAngleDistance(position, angle,
                                                                                   distance);
                        theBuilder->CubicCurveTo(c1, c2, position);
                    }
                    theLastAnchor = theAnchor;
                }
                if (isClosed)
                    theBuilder->Close();
            }
        }
        SPathBuffer theBuffer = theBuilder->GetPathBuffer();
        CFileSeekableIOStream theWriter(theTargetFileName.toCString(), FileWriteFlags());
        theBuffer.Save(theWriter);

        for (QT3DSU32 idx = 0, end = theSubPathChildren.size(); idx < end; ++idx)
            DeleteInstance(theSubPathChildren[idx]);

        CFilePath relativeFileName(
            CFilePath::GetRelativePathFromBase(m_Doc.GetDocumentDirectory(), theTargetFileName));
        SetInstancePropertyValue(path, theDefinitions.m_Asset.m_SourcePath,
                                 TDataStrPtr(new CDataStr(relativeFileName.toCString())));
    }
    static SFloat2 NextDataItem(NVConstDataRef<QT3DSF32> inData, QT3DSU32 &inDataIdx)
    {
        SFloat2 retval(inData[inDataIdx], inData[inDataIdx + 1]);
        inDataIdx += 2;
        return retval;
    }

    static QT3DSF32 ToMinimalAngle(QT3DSF32 inAngle)
    {
        while (inAngle > 360.0f)
            inAngle -= 360.0f;
        while (inAngle < 0.0f)
            inAngle += 360.0f;
        return inAngle;
    }

    void InternalizePath(TInstanceHandle path) override
    {
        Option<TDataStrPtr> thePathOpt =
            GetTypedInstancePropertyValue<TDataStrPtr>(path, m_Bridge.GetSourcePathProperty());
        if (thePathOpt.hasValue() == false || !(*thePathOpt))
            return;
        CFilePath thePathToPathFile = CFilePath::CombineBaseAndRelative(
            m_Doc.GetDocumentDirectory(), (*thePathOpt)->GetData());
        CFileSeekableIOStream theReader(thePathToPathFile.toCString(), FileReadFlags());
        if (theReader.IsOpen() == false)
            return;
        qt3dsimp::SPathBuffer *theLoadedBuffer =
            qt3dsimp::SPathBuffer::Load(theReader, *m_Foundation.m_Foundation);
        if (theLoadedBuffer == NULL)
            return;

        SetInstancePropertyValue(path, m_Bridge.GetSourcePathProperty(),
                                 TDataStrPtr(new CDataStr()), false);

        // Get rid of any existing sub path children.  There shouldn't be any but who knows.
        eastl::vector<TInstanceHandle> theSubPathChildren;

        for (QT3DSI32 pathChildIdx = 0, pathChildEnd = m_AssetGraph.GetChildCount(path);
             pathChildIdx < pathChildEnd; ++pathChildIdx) {
            TInstanceHandle pathChild(m_AssetGraph.GetChild(path, pathChildIdx));
            if (GetObjectTypeName(pathChild) == L"SubPath")
                theSubPathChildren.push_back(pathChild);
        }

        for (QT3DSU32 idx = 0, end = theSubPathChildren.size(); idx < end; ++idx)
            DeleteInstance(theSubPathChildren[idx]);

        QT3DSU32 dataIdx = 0;

        TInstanceHandle theCurrentSubPath;
        TInstanceHandle theCurrentAnchorPoint;
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());
        TPropertyHandle positionProp(theDefinitions.m_PathAnchorPoint.m_Position.m_Property);
        TPropertyHandle angleProp(theDefinitions.m_PathAnchorPoint.m_IncomingAngle.m_Property);
        TPropertyHandle incomingdistanceProp(
            theDefinitions.m_PathAnchorPoint.m_IncomingDistance.m_Property);
        TPropertyHandle outgoingdistanceProp(
            theDefinitions.m_PathAnchorPoint.m_OutgoingDistance.m_Property);
        TPropertyHandle closedProp(theDefinitions.m_SubPath.m_Closed.m_Property);
        qt3dsdm::ISlideCore &theSlideCore(
            *m_StudioSystem.GetFullSystem()->GetCoreSystem()->GetTransactionlessSlideCore());
        TSlideHandle theCurrentSlide = GetAssociatedSlide(path);
        QT3DSU32 subPathIndex = 0;
        wchar_t theNameBuffer[256];
        QT3DSVec2 theCurrentPosition;

        for (QT3DSU32 idx = 0, end = theLoadedBuffer->m_Commands.size(); idx < end; ++idx) {
            switch (theLoadedBuffer->m_Commands[idx]) {
            case qt3dsimp::PathCommand::MoveTo:
                theCurrentSubPath = CreateSceneGraphInstance(qt3dsdm::ComposerObjectTypes::SubPath,
                                                             path, theCurrentSlide);
                if (subPathIndex)
                    swprintf(theNameBuffer, 256, L"SubPath_%d", subPathIndex);
                else
                    swprintf(theNameBuffer, 256, L"SubPath");
                SetName(theCurrentSubPath, theNameBuffer);
                theCurrentAnchorPoint =
                    CreateSceneGraphInstance(qt3dsdm::ComposerObjectTypes::PathAnchorPoint,
                                             theCurrentSubPath, theCurrentSlide);
                SetName(theCurrentAnchorPoint, L"PathAnchorPoint");
                theCurrentPosition = ToFnd(NextDataItem(theLoadedBuffer->m_Data, dataIdx));
                theSlideCore.ForceSetInstancePropertyValue(theCurrentSlide, theCurrentAnchorPoint,
                                                           positionProp,
                                                           ToDataModel(theCurrentPosition));
                ++subPathIndex;
                break;
            case qt3dsimp::PathCommand::CubicCurveTo: {
                QT3DSVec2 c1 = ToFnd(NextDataItem(theLoadedBuffer->m_Data, dataIdx));
                QT3DSVec2 c2 = ToFnd(NextDataItem(theLoadedBuffer->m_Data, dataIdx));
                QT3DSVec2 p2 = ToFnd(NextDataItem(theLoadedBuffer->m_Data, dataIdx));
                QT3DSVec2 outgoing =
                    IPathManager::GetAngleDistanceFromControlPoint(theCurrentPosition, c1);
                outgoing.x += 180.0f;
                outgoing.x = ToMinimalAngle(outgoing.x);
                QT3DSVec2 incoming = IPathManager::GetAngleDistanceFromControlPoint(p2, c2);
                incoming.x = ToMinimalAngle(incoming.x);
                theSlideCore.ForceSetInstancePropertyValue(theCurrentSlide, theCurrentAnchorPoint,
                                                           outgoingdistanceProp, outgoing.y);
                if (fabs(outgoing.y) > .01f) // if the control point is not on the anchor point.
                    theSlideCore.ForceSetInstancePropertyValue(
                        theCurrentSlide, theCurrentAnchorPoint, angleProp, outgoing.x);
                theCurrentPosition = p2;
                theCurrentAnchorPoint =
                    CreateSceneGraphInstance(qt3dsdm::ComposerObjectTypes::PathAnchorPoint,
                                             theCurrentSubPath, theCurrentSlide);
                SetName(theCurrentAnchorPoint, L"PathAnchorPoint");
                theSlideCore.ForceSetInstancePropertyValue(theCurrentSlide, theCurrentAnchorPoint,
                                                           positionProp,
                                                           ToDataModel(theCurrentPosition));
                theSlideCore.ForceSetInstancePropertyValue(theCurrentSlide, theCurrentAnchorPoint,
                                                           incomingdistanceProp, incoming.y);
                if (fabs(incoming.y) > .01f)
                    theSlideCore.ForceSetInstancePropertyValue(
                        theCurrentSlide, theCurrentAnchorPoint, angleProp, incoming.x);
            } break;
            case qt3dsimp::PathCommand::Close:
                theSlideCore.ForceSetInstancePropertyValue(theCurrentSlide, theCurrentSubPath,
                                                           closedProp, true);
                break;
            default:
                QT3DS_ASSERT(false);
                break;
            }
        }
        theLoadedBuffer->Free(m_Foundation.m_Foundation->getAllocator());
    }

    void ReplaceTextFontNameWithTextFileStem(qt3ds::render::ITextRenderer &inRenderer) override
    {
        TInstanceHandleList theTextInstances;
        m_DataCore.GetInstancesDerivedFrom(theTextInstances, m_Bridge.GetText().m_Instance);
        TSlideHandleList theChildSlides;
        for (size_t idx = 0, end = theTextInstances.size(); idx < end; ++idx) {
            SValue theValue;
            qt3dsdm::Qt3DSDMInstanceHandle theTextHandle(theTextInstances[idx]);
            if (m_DataCore.GetInstancePropertyValue(theTextHandle, m_Bridge.GetText().m_Font,
                                                    theValue)) {
                qt3dsdm::TDataStrPtr theDataStr(qt3dsdm::get<qt3dsdm::TDataStrPtr>(theValue));
                if (theDataStr && theDataStr->GetLength()) {

                    Option<CRegisteredString> theNewValueOpt = inRenderer.GetFontNameForFont(
                        m_StringTable.GetNarrowStr(theDataStr->GetData()));
                    if (theNewValueOpt.hasValue()) {
                        CRegisteredString theNewValue(*theNewValueOpt);
                        const wchar_t *theWideValue = m_StringTable.GetWideStr(theNewValue);
                        if (wcscmp(theWideValue, theDataStr->GetData()) != 0)
                            m_DataCore.SetInstancePropertyValue(
                                theTextHandle, m_Bridge.GetText().m_Font,
                                std::make_shared<CDataStr>(theWideValue));
                    }
                }
            }
            qt3dsdm::Qt3DSDMSlideHandle theAssociatedSlide = GetAssociatedSlide(theTextHandle);
            if (theAssociatedSlide.Valid()) {
                theChildSlides.clear();
                m_SlideCore.GetChildSlides(theAssociatedSlide, theChildSlides);
                theChildSlides.insert(theChildSlides.begin(), theAssociatedSlide);
                for (size_t theSlideIdx = 0, theSlideEnd = theChildSlides.size();
                     theSlideIdx < theSlideEnd; ++theSlideIdx) {
                    SValue theSlideValue;
                    if (m_SlideCore.GetSpecificInstancePropertyValue(
                            theChildSlides[theSlideIdx], theTextHandle, m_Bridge.GetText().m_Font,
                            theSlideValue)) {
                        qt3dsdm::TDataStrPtr theDataStr(
                            qt3dsdm::get<qt3dsdm::TDataStrPtr>(theSlideValue));
                        if (theDataStr && theDataStr->GetLength()) {
                            Option<CRegisteredString> theNewValueOpt =
                                inRenderer.GetFontNameForFont(
                                    m_StringTable.GetNarrowStr(theDataStr->GetData()));
                            if (theNewValueOpt.hasValue()) {
                                CRegisteredString theNewValue(*theNewValueOpt);
                                const wchar_t *theWideValue = m_StringTable.GetWideStr(theNewValue);
                                m_SlideCore.ForceSetInstancePropertyValue(
                                    theChildSlides[theSlideIdx], theTextHandle,
                                    m_Bridge.GetText().m_Font,
                                    std::make_shared<CDataStr>(theWideValue));
                            }
                        }
                    }
                }
            }
        }
    }

    void toggleBoolPropertyOnSelected(TPropertyHandle property) override
    {
        qt3dsdm::IPropertySystem *propertySystem = m_Doc.GetStudioSystem()->GetPropertySystem();
        qt3dsdm::TInstanceHandleList selectedInstances
                = m_Doc.GetSelectedValue().GetSelectedInstances();

        if (selectedInstances.size() > 0) {
            bool boolValue = false;
            SValue value;
            for (size_t idx = 0, end = selectedInstances.size(); idx < end; ++idx) {
                qt3dsdm::Qt3DSDMInstanceHandle handle(selectedInstances[idx]);
                if (handle.Valid()) {
                    if (value.empty()) {
                        // First valid handle selects if all are hidden/unhidden
                        propertySystem->GetInstancePropertyValue(handle, property, value);
                        boolValue = !qt3dsdm::get<bool>(value);
                    }
                    propertySystem->SetInstancePropertyValue(handle, property, boolValue);
                }
            }
        }
    }

    void BuildDAEMap(const TFileModificationList &inList)
    {
        for (size_t fileIdx = 0, fileEnd = inList.size(); fileIdx < fileEnd; ++fileIdx) {
            const SFileModificationRecord &theRecord(inList[fileIdx]);
            CString theExtension = theRecord.m_File.GetExtension();
            bool isImport = theExtension.Compare(L"import", CString::ENDOFSTRING, false);
            CFilePath theRelativePath(m_Doc.GetRelativePathToDoc(theRecord.m_File));

            if (theRecord.m_ModificationType == FileModificationType::InfoChanged
                || theRecord.m_ModificationType == FileModificationType::Destroyed) {
                if (isImport)
                    m_ImportFileToDAEMap.erase(theRelativePath.toCString());
                continue;
            }
            if (isImport) {
                qt3dsimp::ImportPtrOrError theImportPtr = qt3dsimp::Import::Load(theRecord.m_File.toCString());
                if (theImportPtr.m_Value) {
                    CFilePath theDestDir = theImportPtr.m_Value->GetDestDir();
                    CFilePath theSrcFile = theImportPtr.m_Value->GetSrcFile();
                    CFilePath theFullSrcPath =
                        CFilePath::CombineBaseAndRelative(theDestDir, theSrcFile);
                    TCharPtr theDAERelativePath =
                        m_StringTable.RegisterStr(m_Doc.GetRelativePathToDoc(theFullSrcPath));
                    pair<unordered_map<TCharPtr, TCharPtr>::iterator, bool> theInsertResult =
                        m_ImportFileToDAEMap.insert(
                            make_pair(m_StringTable.RegisterStr(theRelativePath.toCString()),
                                      theDAERelativePath));
                    theImportPtr.m_Value->Release();
                    if (theInsertResult.second == false)
                        theInsertResult.first->second = theDAERelativePath;
                }
            }
        }
    }

    static const char *ModificationTypeToString(FileModificationType::Enum inType)
    {
        switch (inType) {
        case FileModificationType::Created:
            return "Created";
        case FileModificationType::Destroyed:
            return "Destroyed";
        case FileModificationType::InfoChanged:
            return "InfoChanged";
        case FileModificationType::Modified:
            return "Modified";
        case FileModificationType::NoChange:
            return "NoChange";
        default:
            return "Unknown";
        }
    }

    void OnProjectDirChanged(const TFileModificationList &inList)
    {
        if (m_IgnoreDirChange == true) {
            BuildDAEMap(inList);
            return;
        }
        CDispatch &theDispatch(*m_Doc.GetCore()->GetDispatch());
        bool hasProgressFired = false;
        bool hasDispatchNotificationScope = false;
        bool requestRender = false;

        if (inList.size() == 1
            && m_Doc.GetDocumentPath().endsWith(inList[0].m_File.GetFileName().toQString())
            && inList[0].m_ModificationType == FileModificationType::Modified) {
            if (!m_Doc.GetCore()->HasJustSaved()) {
                CDispatch &theDispatch(*m_Doc.GetCore()->GetDispatch());
                theDispatch.FireOnPresentationModifiedExternally();
                return;
            }
            m_Doc.GetCore()->SetJustSaved(false);
        }

#define ENSURE_PROGRESS                                                                            \
    if (!hasProgressFired) {                                                                       \
        theDispatch.FireOnProgressBegin(QObject::tr("Updating project"), {});                      \
        hasProgressFired = true;                                                                   \
    }

        m_SourcePathInstanceMap.clear();
        GetSourcePathToInstanceMap(m_SourcePathInstanceMap);
        TInstanceHandleList theParents;
        SComposerObjectDefinitions &theDefinitions(m_Bridge.GetObjectDefinitions());

        for (size_t fileIdx = 0, fileEnd = inList.size(); fileIdx < fileEnd; ++fileIdx) {
            const SFileModificationRecord &theRecord(inList[fileIdx]);

            CString theExtension = theRecord.m_File.GetExtension();
            bool isImport = theExtension.Compare(L"import", CString::ENDOFSTRING, false);
            CFilePath theRelativePath(m_Doc.GetRelativePathToDoc(theRecord.m_File));
            const wchar_t *theString(
                m_DataCore.GetStringTable().RegisterStr(theRelativePath.toCString()));

            if ((theExtension.CompareNoCase(L"ttf")
                 || theExtension.CompareNoCase(L"otf")) // should use CDialogs::IsFontFileExtension
                && m_Doc.GetSceneGraph() && m_Doc.GetSceneGraph()->GetTextRenderer()) {
                m_Doc.GetSceneGraph()->GetTextRenderer()->ReloadFonts();
                CFilePath thePath = m_Doc.GetDocumentDirectory();
                CFilePath theFontCache = CFilePath::CombineBaseAndRelative(thePath, L"fontcache");
                theFontCache.DeleteThisDirectory(true);
            }

            if (theRecord.m_ModificationType == FileModificationType::InfoChanged
                || theRecord.m_ModificationType == FileModificationType::Destroyed) {
                if (isImport)
                    m_ImportFileToDAEMap.erase(theRelativePath.toCString());
                continue;
            }

            QDir modifiedPath = QDir::cleanPath(QString::fromWCharArray(theString));
            TCharPtrToSlideInstanceMap::iterator theFind = m_SourcePathInstanceMap.end();
            for (TCharPtrToSlideInstanceMap::iterator it = m_SourcePathInstanceMap.begin();
                 it != m_SourcePathInstanceMap.end(); ++it) {
                QDir sourcePath = QDir::cleanPath(QString::fromWCharArray(it->first));
                if (sourcePath == modifiedPath) {
                    theFind = it;
                    break;
                }
            }

            if (theFind == m_SourcePathInstanceMap.end())
                continue;

            const TSlideInstanceList theInstances(theFind->second);
            if (theRecord.m_ModificationType != FileModificationType::Created) {
                requestRender = true;
                m_Doc.GetBufferCache().InvalidateBuffer(theRelativePath);
            }

            qCInfo(qt3ds::TRACE_INFO) << "Change detected: " << theRelativePath.toQString() << " "
                      << ModificationTypeToString(theRecord.m_ModificationType);

            if (isImport) {
                qt3dsimp::ImportPtrOrError theImportPtr = qt3dsimp::Import::Load(theRecord.m_File.toCString());
                if (theImportPtr.m_Value) {
                    ENSURE_PROGRESS;
                    CFilePath theDestDir = theImportPtr.m_Value->GetDestDir();
                    CFilePath theSrcFile = theImportPtr.m_Value->GetSrcFile();
                    CFilePath theFullSrcPath =
                        CFilePath::CombineBaseAndRelative(theDestDir, theSrcFile);
                    TCharPtr theDAERelativePath =
                        m_StringTable.RegisterStr(m_Doc.GetRelativePathToDoc(theFullSrcPath));
                    pair<unordered_map<TCharPtr, TCharPtr>::iterator, bool> theInsertResult =
                        m_ImportFileToDAEMap.insert(
                            make_pair(m_StringTable.RegisterStr(theRelativePath.toCString()),
                                      theDAERelativePath));
                    theImportPtr.m_Value->Release();
                    if (theInsertResult.second == false)
                        theInsertResult.first->second = theDAERelativePath;
                }
            } else if (theExtension.Compare(L"qml", CString::ENDOFSTRING, false)
                       && theRecord.m_ModificationType != FileModificationType::Created
                       && theInstances.empty() == false) {
                // First, refresh the parent behavior.
                if (!hasDispatchNotificationScope) {
                    theDispatch.FireBeginDataModelNotifications();
                    hasDispatchNotificationScope = true;
                }

                for (size_t instIdx = 0, instEnd = theInstances.size(); instIdx < instEnd;
                     ++instIdx) {
                    ENSURE_PROGRESS;
                    Qt3DSDMInstanceHandle theBehavior = theInstances[instIdx].second;
                    theParents.clear();
                    m_DataCore.GetInstanceParents(theBehavior, theParents);

                    if (theParents.empty()
                        || theParents[0] != theDefinitions.m_Behavior.m_Instance) {
                        // This indicates we are dealing with a scene instance.
                        // In this case we want to clear any intermediate cached
                        // values from the instance itself so that new defaults
                        // in the file will show through to the UI.
                        m_DataCore.RemoveCachedValues(theBehavior);
                    } else {
                        std::shared_ptr<IDOMReader> theReaderPtr;
                        theReaderPtr = ParseScriptFile(theRecord.m_File,
                                                       m_DataCore.GetStringTablePtr(),
                                                       m_Doc.GetImportFailedHandler(),
                                                       *m_InputStreamFactory);
                        if (!theReaderPtr) {
                            // then effectively no change...
                            QT3DS_ASSERT(false);
                        } else {
                            std::vector<SMetaDataLoadWarning> theWarnings;
                            m_MetaData.LoadInstance(*theReaderPtr, theBehavior,
                                                    theRelativePath.GetFileStem().c_str(),
                                                    theWarnings);
                            CScriptDynamicInstanceLoader inSpecificInstance(*this);
                            QString theLoadError =
                                inSpecificInstance.LoadInstanceData(theRecord.m_File);
                            DisplayLoadWarnings(theRecord.m_File.toQString(),
                                                theWarnings, theLoadError);
                        }
                    }
                }
            } else if (theExtension.Compare(L"effect", CString::ENDOFSTRING, false)
                       && theRecord.m_ModificationType != FileModificationType::Created
                       && theInstances.empty() == false) {
                CString theNameStr = GetName(theInstances[0].second);
                std::vector<SMetaDataLoadWarning> theWarnings;
                NVScopedRefCounted<qt3ds::render::IRefCountedInputStream> theStream(
                    m_InputStreamFactory->GetStreamForFile(theRecord.m_File.toQString()));
                if (theStream) {
                    m_MetaData.LoadEffectInstance(m_StringTable.GetNarrowStr(theRelativePath.toCString()),
                                                  theInstances[0].second,
                                                  TCharStr(theNameStr),
                                                  theWarnings, *theStream);
                    IDocumentEditor::fixDefaultTexturePaths(theInstances[0].second);
                }

                for (size_t i = 0; i < theInstances.size(); ++i) {
                    theDispatch.FireReloadEffectInstance(theInstances[i].second);
                    theDispatch.FireImmediateRefreshInstance(theInstances[i].second);
                }
            }
            // There used to be an extension here for meshes
            // but that causes the product to delete materials in some cases which loses work.
            // so that experiment failed and we will just have to let the users manually updated
            // their
            // meshes through the dropdown if they need them updated.
        }
        if (hasProgressFired)
            theDispatch.FireOnProgressEnd();
        if (requestRender && m_Doc.GetSceneGraph())
            m_Doc.GetSceneGraph()->RequestRender();
        if (hasDispatchNotificationScope)
            theDispatch.FireEndDataModelNotifications();
    }
};
}

void IDocumentEditor::DisplayImportErrors(const QString &inImportSource,
                                          ImportErrorCodes::Enum inImportError,
                                          std::shared_ptr<IImportFailedHandler> inHandler,
                                          STranslationLog &inTranslationLog, bool inForceError)
{
    bool isError = false;
    Q3DStudio::CString resultDialogStr;
    std::shared_ptr<IImportFailedHandler> theHandler(inHandler);
    if (inImportError == ImportErrorCodes::TranslationToImportFailed || inForceError) {
        isError = true;
        resultDialogStr = "Failed to import file";
    }

    for (size_t idx = 0; idx < inTranslationLog.m_Warnings.size(); ++idx) {
        const std::pair<ESceneGraphWarningCode, Q3DStudio::CString> &warning(
            inTranslationLog.m_Warnings[idx]);
        const wchar_t *formatStr = L"Unrecognized warning";
        switch (warning.first) {
        case ESceneGraphWarningCode_OnlySupportTriangles:
            formatStr = L"Model %ls contains geometric elements other than triangles";
            break;
        case ESceneGraphWarningCode_TrianglesDuplicateSemantic:
            formatStr = L"Triangle contains duplicate semantics, ex: 1 triangle has multiple "
                        L"TEXCOORD (multiple UV maps)";
            break;
        case ESceneGraphWarningCode_MissingSourceFile:
            formatStr = L"Couldn't find a source image file %ls";
            break;
        case ESceneGraphWarningCode_LockedDestFile:
            formatStr = L"An image or mesh file %ls is not writeable";
            break;
        case ESceneGraphWarningCode_VertexBufferTooLarge:
            formatStr = L"A single mesh exceeds the maximum vertex count of 65535";
            break;
        default:
            break;
        }

        wchar_t buf[1024] = { 0 };
        swprintf(buf, 1024, formatStr, warning.second.c_str());
        if (resultDialogStr.size())
            resultDialogStr.append('\n');
        resultDialogStr.append(buf);
    }
    if (resultDialogStr.size()) {
        if (theHandler)
            theHandler->DisplayImportFailed(inImportSource, resultDialogStr.toQString(), !isError);
    }
}

Qt3DSDMPropertyHandle *
IDocumentEditor::GetAlwaysUnlinkedProperties(qt3dsdm::SComposerObjectDefinitions &inDefs)
{
    SComposerObjectDefinitions &theDefs(inDefs);
    static Qt3DSDMPropertyHandle theProperties[5];
    theProperties[0] = theDefs.m_Asset.m_StartTime;
    theProperties[1] = theDefs.m_Asset.m_EndTime;
    theProperties[2] = theDefs.m_Asset.m_Eyeball;
    theProperties[3] = theDefs.m_Asset.m_Shy;
    theProperties[4] = Qt3DSDMPropertyHandle();
    return theProperties;
}

// Fixes the default texture paths loaded from material and effect to be presentation relative
void IDocumentEditor::fixDefaultTexturePaths(Qt3DSDMInstanceHandle instance)
{
    const auto core = g_StudioApp.GetCore();
    const QDir docDir(core->GetDoc()->GetDocumentDirectory().toQString());
    const QDir projDir = core->getProjectFile().getProjectPath();
    const auto propertySystem = core->GetDoc()->GetStudioSystem()->GetPropertySystem();
    qt3dsdm::TPropertyHandleList propList;
    SValue value;

    propertySystem->GetAggregateInstanceProperties(instance, propList);
    for (auto &prop : propList) {
        qt3dsdm::AdditionalMetaDataType::Value additionalMetaDataType
                = propertySystem->GetAdditionalMetaDataType(instance, prop);
        if (additionalMetaDataType == AdditionalMetaDataType::Texture) {
            propertySystem->GetInstancePropertyValue(instance, prop, value);
            TDataStrPtr strPtr = get<TDataStrPtr>(value);
            const QString strValue = QString::fromWCharArray(strPtr->GetData());
            const QString docRelative = docDir.relativeFilePath(strValue);
            const QString projRelative = projDir.relativeFilePath(strValue);
            if (!QFileInfo(docRelative).exists() && !QFileInfo(projRelative).exists()) {
                // Convert path to presentation relative
                const QVariant newVarValue = QVariant::fromValue(
                            docDir.relativeFilePath(projDir.absoluteFilePath(strValue)));
                const SValue newValue = newVarValue;
                propertySystem->SetInstancePropertyValue(instance, prop, newValue);
            }
        }
    }
}

void IDocumentEditor::UnlinkAlwaysUnlinkedProperties(Qt3DSDMInstanceHandle inInstance,
                                                     SComposerObjectDefinitions &inDefs,
                                                     ISlideSystem &inSlideSystem)
{
    Qt3DSDMPropertyHandle *theUnlinked(GetAlwaysUnlinkedProperties(inDefs));
    for (Qt3DSDMPropertyHandle *theHandle = theUnlinked; theHandle->Valid(); ++theHandle)
        inSlideSystem.UnlinkProperty(inInstance, *theHandle);
}

// static
Qt3DSDMInstanceHandle IDocumentEditor::CreateSceneGraphInstance(
    const wchar_t *inType, TInstanceHandle inParent, TSlideHandle inSlide,
    qt3dsdm::IDataCore &inDataCore, qt3dsdm::ISlideSystem &inSlideSystem,
    qt3dsdm::SComposerObjectDefinitions &inObjectDefs, Q3DStudio::CGraph &inAssetGraph,
    qt3dsdm::IMetaData &inMetaData, TInstanceHandle inTargetId, bool setTimeRange,
    bool selectCreatedInstance)
{
    return CreateSceneGraphInstance(inMetaData.GetCanonicalInstanceForType(inType), inParent,
                                    inSlide, inDataCore, inSlideSystem, inObjectDefs, inAssetGraph,
                                    inMetaData, inTargetId, selectCreatedInstance);
}

// static
Qt3DSDMInstanceHandle IDocumentEditor::CreateSceneGraphInstance(
    Qt3DSDMInstanceHandle inMaster, TInstanceHandle inParent, TSlideHandle inSlide,
    qt3dsdm::IDataCore &inDataCore, qt3dsdm::ISlideSystem &inSlideSystem,
    qt3dsdm::SComposerObjectDefinitions &inObjectDefs, Q3DStudio::CGraph &inAssetGraph,
    qt3dsdm::IMetaData &inMetaData, TInstanceHandle inTargetId, bool selectCreatedInstance)
{
    Option<TCharStr> theTypeOpt = inMetaData.GetTypeForInstance(inMaster);
    if (theTypeOpt.hasValue() == false)
        return 0;

    SComposerObjectDefinitions &theDefs(inObjectDefs);
    TInstanceHandle retval = inDataCore.CreateInstance(inTargetId);
    TInstanceHandle theDerivationParent(inMaster);
    inDataCore.DeriveInstance(retval, theDerivationParent);

    if (inParent.Valid())
        inAssetGraph.AddChild(inParent, retval);
    else
        inAssetGraph.AddRoot(retval);

    if (inSlide.Valid()) {
        inSlideSystem.AssociateInstanceWithSlide(inSlide, retval);
        UnlinkAlwaysUnlinkedProperties(retval, inObjectDefs, inSlideSystem);
    }

    Q3DStudio::CId theId;
    if (ComposerObjectTypes::Convert(theTypeOpt->wide_str()) == qt3dsdm::ComposerObjectTypes::Scene)
        theId = SCENE_GUID;
    else
        theId.Generate();

    TGUIDPacked thePackedGuid(theId);
    SLong4 theLong4Id(thePackedGuid.Data1, thePackedGuid.Data2, thePackedGuid.Data3,
                      thePackedGuid.Data4);
    inDataCore.SetInstancePropertyValue(retval, theDefs.m_Guided.m_GuidProp, theLong4Id);
    return retval;
}

std::shared_ptr<IDOMReader>
IDocumentEditor::ParseScriptFile(const CFilePath &inFullPathToDocument,
                                 std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                 std::shared_ptr<IImportFailedHandler> inHandler,
                                 qt3ds::render::IInputStreamFactory &inInputStreamFactory)
{
    using namespace ScriptParser;
    std::shared_ptr<qt3dsdm::IStringTable> theStringTable(inStringTable);
    std::shared_ptr<IDOMFactory> theFactory(IDOMFactory::CreateDOMFactory(theStringTable));
    SImportXmlErrorHandler theXmlErrorHandler(inHandler,
        inFullPathToDocument.toCString());
    std::shared_ptr<IDOMReader> theReaderPtr(
        SScriptParser::ParseScriptFile(theFactory, inStringTable,
                                       inFullPathToDocument.toQString(),
                                       theXmlErrorHandler, inInputStreamFactory));

    if (!theReaderPtr) {
        QT3DS_ASSERT(false);
        if (inHandler) {
            inHandler->DisplayImportFailed(inFullPathToDocument.toQString(),
                                           QObject::tr("Failed to parse script data"),
                                           false);
        }
    }
    return theReaderPtr;
}

std::shared_ptr<IDOMReader>
IDocumentEditor::ParsePluginFile(const Q3DStudio::CFilePath &inFullPathToDocument,
                                 std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                 std::shared_ptr<IImportFailedHandler> inHandler,
                                 qt3ds::render::IInputStreamFactory &inInputStreamFactory)
{
    std::shared_ptr<qt3dsdm::IStringTable> theStringTable(inStringTable);
    std::shared_ptr<IDOMFactory> theFactory(IDOMFactory::CreateDOMFactory(theStringTable));
    SImportXmlErrorHandler theXmlErrorHandler(inHandler,
        inFullPathToDocument.toCString());

    std::shared_ptr<IDOMReader> theReaderPtr = CRenderPluginParser::ParseFile(
        theFactory, theStringTable, theStringTable->GetNarrowStr(inFullPathToDocument.toCString()),
        theXmlErrorHandler, inInputStreamFactory);
    if (!theReaderPtr) {
        QT3DS_ASSERT(false);
        if (inHandler)
            inHandler->DisplayImportFailed(inFullPathToDocument.toQString(),
                                           QObject::tr("Failed to parse plugin file"),
                                           false);
    }
    CRenderPluginParser::NavigateToMetadata(theReaderPtr);
    return theReaderPtr;
}

std::shared_ptr<IDOMReader>
IDocumentEditor::ParseCustomMaterialFile(const Q3DStudio::CFilePath &inFullPathToDocument,
                                         std::shared_ptr<qt3dsdm::IStringTable> inStringTable,
                                         std::shared_ptr<IImportFailedHandler> inHandler,
                                         qt3ds::render::IInputStreamFactory &inInputStreamFactory)
{
    std::shared_ptr<qt3dsdm::IStringTable> theStringTable(inStringTable);
    std::shared_ptr<IDOMFactory> theFactory(IDOMFactory::CreateDOMFactory(theStringTable));
    SImportXmlErrorHandler theXmlErrorHandler(inHandler,
        inFullPathToDocument.toCString());

    std::shared_ptr<IDOMReader> theReaderPtr = CRenderPluginParser::ParseFile(
        theFactory, theStringTable, theStringTable->GetNarrowStr(inFullPathToDocument.toCString()),
        theXmlErrorHandler, inInputStreamFactory);
    if (!theReaderPtr) {
        QT3DS_ASSERT(false);
        if (inHandler)
            inHandler->DisplayImportFailed(inFullPathToDocument.toQString(),
                                           QObject::tr("Failed to parse material file"),
                                           false);
    }
    CCustomMaterialParser::NavigateToMetadata(theReaderPtr);
    return theReaderPtr;
}

ScopedDocumentEditor::ScopedDocumentEditor(IDoc &inDoc, const QString &inCommandName,
                                           const char *inFile, int inLine)
    : m_Editor(inDoc.OpenTransaction(inCommandName, inFile, inLine))
{
}

CUpdateableDocumentEditor::~CUpdateableDocumentEditor()
{
    if (HasEditor()) {
        qCWarning(qt3ds::WARNING) << m_File << "(" << m_Line
                                  << "): Document editor committed upon destruction";
        CommitEditor();
    }
}

IDocumentEditor &CUpdateableDocumentEditor::EnsureEditor(const QString &inCommandName,
                                                         const char *inFile, int inLine)
{
    if (!HasEditor()) {
        m_File = inFile;
        m_Line = inLine;
    }
    return m_EditorIDocDoc.MaybeOpenTransaction(inCommandName, inFile, inLine);
}

bool CUpdateableDocumentEditor::HasEditor() const
{
    return m_EditorIDocDoc.IsTransactionOpened() && m_File != NULL;
}

void CUpdateableDocumentEditor::FireImmediateRefresh(qt3dsdm::Qt3DSDMInstanceHandle *inInstances,
                                                     long inInstanceCount)
{
    m_EditorIDocDoc.GetCore()->GetDispatch()->FireImmediateRefreshInstance(inInstances,
                                                                           inInstanceCount);
}

void CUpdateableDocumentEditor::CommitEditor()
{
    if (HasEditor()) {
        m_EditorIDocDoc.CloseTransaction();
        m_File = NULL;
    }
}

void CUpdateableDocumentEditor::RollbackEditor()
{
    if (HasEditor()) {
        m_EditorIDocDoc.RollbackTransaction();
        m_EditorIDocDoc.CloseTransaction();
        m_File = NULL;
    }
}

std::shared_ptr<IInternalDocumentEditor> IInternalDocumentEditor::CreateEditor(CDoc &doc)
{
    return std::make_shared<CDocEditor>(doc);
}