summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/MainFrm.cpp
blob: d056bff777aa68c175691f30cc7b2c3ec598d9d0 (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
/****************************************************************************
**
** Copyright (C) 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$
**
****************************************************************************/

//==============================================================================
//	Prefix
//==============================================================================
#include "MainFrm.h"
#include "ui_MainFrm.h"

#include "StudioConst.h"

//==============================================================================
//	Includes
//==============================================================================
#include "Bindings/TimelineTranslationManager.h"
#include "Bindings/Qt3DSDMTimelineItemBinding.h"
#include "SceneView.h"
#include "StudioApp.h"
#include "IKeyframesManager.h"
#include "Dialogs.h"
#include "StudioPreferencesPropSheet.h"
#include "StudioPreferences.h"
#include "HotKeys.h"
#include "RecentItems.h"
#include "PaletteManager.h"
#include "Core.h"
#include "ITickTock.h"
#include "IStudioRenderer.h"
#include "SubPresentationListDlg.h"
#include "DataInputListDlg.h"
#include "StudioTutorialWidget.h"
#include "remotedeploymentsender.h"
#include "InspectorControlView.h"
#include "TimelineWidget.h"
#include "ProjectView.h"
#include "RowTree.h"
#include "WidgetControl.h"

#include <QtGui/qevent.h>
#include <QtGui/qdesktopservices.h>
#include <QtWidgets/qdockwidget.h>
#include <QtCore/qsettings.h>
#include <QtCore/qtimer.h>
#include <QtCore/qurl.h>
#include <QtCore/qdir.h>
#include <QtCore/qprocess.h>

// Constants
const long PLAYBACK_TIMER_TIMEOUT = 10; // 10 milliseconds

//==============================================================================
/**
 * Constructor
 */
CMainFrame::CMainFrame()
    : m_ui(new Ui::MainFrame)
    , m_remoteDeploymentSender(new RemoteDeploymentSender(this))
    , m_sceneView(nullptr)
    , m_recentItems(nullptr)
    , m_paletteManager(nullptr)
    , m_updateUITimer(new QTimer)
    , m_playbackTimer(new QTimer)
    , m_propSheet(nullptr)
{
    m_ui->setupUi(this);

    OnCreate();

    g_StudioApp.GetCore()->GetDispatch()->AddPresentationChangeListener(this);
    g_StudioApp.GetCore()->GetDispatch()->AddFileOpenListener(this);
    g_StudioApp.GetCore()->GetDispatch()->AddClientPlayChangeListener(this);
    g_StudioApp.setupTimer(WM_STUDIO_TIMER, this);

    // File Menu
    connect(m_ui->action_New, &QAction::triggered, this, &CMainFrame::OnFileNew);
    connect(m_ui->action_Open, &QAction::triggered, this, &CMainFrame::OnFileOpen);
    connect(m_ui->action_Save, &QAction::triggered, this, &CMainFrame::OnFileSave);
    connect(m_ui->actionSave_As, &QAction::triggered, this, &CMainFrame::OnFileSaveAs);
    connect(m_ui->actionSave_a_Copy, &QAction::triggered, this, &CMainFrame::OnFileSaveCopy);
    connect(m_ui->action_Revert, &QAction::triggered, this, &CMainFrame::OnFileRevert);
    connect(m_ui->actionImportAssets, &QAction::triggered, this, &CMainFrame::OnFileImportAssets);
    connect(m_ui->actionSubpresentations, &QAction::triggered, this,
            &CMainFrame::OnFileSubPresentations);
    connect(m_ui->actionData_Inputs, &QAction::triggered, this, &CMainFrame::OnFileDataInputs);
    connect(m_ui->action_Connect_to_Device, &QAction::triggered, this,
            &CMainFrame::OnFileConnectToDevice);
    m_recentItems.reset(new CRecentItems(m_ui->menuRecent_Projects, 0));
    connect(m_recentItems.data(), &CRecentItems::openRecent, this, &CMainFrame::OnFileOpenRecent);
    connect(m_ui->action_Exit, &QAction::triggered, this, &CMainFrame::close);

    // Edit Menu
    connect(m_ui->action_Undo, &QAction::triggered, this, &CMainFrame::OnEditUndo);
    connect(m_ui->action_Redo, &QAction::triggered, this, &CMainFrame::OnEditRedo);
//    connect(m_ui->actionRepeat, &QAction::triggered, this, &CMainFrame::onEditRepeat); // TODO: Implement
    connect(m_ui->action_Cut, &QAction::triggered, this, &CMainFrame::OnEditCut);
    connect(m_ui->action_Copy, &QAction::triggered, this, &CMainFrame::OnEditCopy);
    connect(m_ui->action_Paste, &QAction::triggered, this, &CMainFrame::OnEditPaste);
    connect(m_ui->actionPaste_to_Master_Slide, &QAction::triggered,
            this, &CMainFrame::onEditPasteToMaster);
    connect(m_ui->action_Duplicate_Object, &QAction::triggered, this, &CMainFrame::OnEditDuplicate);
    connect(m_ui->actionDelete, &QAction::triggered, this, &CMainFrame::onEditDelete);
//    connect(m_ui->actionGroup, &QAction::triggered, this, &CMainFrame::onEditGroup); // TODO: Implement
//    connect(m_ui->actionParent, &QAction::triggered, this, &CMainFrame::onEditParent); // TODO: Implement
//    connect(m_ui->actionUnparent, &QAction::triggered, this, &CMainFrame::onEditUnparent); // TODO: Implement
    connect(m_ui->actionStudio_Preferences, &QAction::triggered,
            this, &CMainFrame::OnEditApplicationPreferences);
    connect(m_ui->actionPresentation_Settings, &QAction::triggered,
            this, &CMainFrame::OnEditPresentationPreferences);

    // View Menu
    connect(m_ui->actionReset_layout, &QAction::triggered, this, &CMainFrame::onViewResetLayout);
    connect(m_ui->actionFit_Selected, &QAction::triggered,
            this, &CMainFrame::OnEditCameraZoomExtent);
//    connect(m_ui->actionFit_all, &QAction::triggered, this, &CMainFrame::onViewFitAll); // TODO: Implement
    connect(m_ui->actionToggle_hide_unhide_selected, &QAction::triggered,
            []() { g_StudioApp.toggleEyeball(); });
//    connect(m_ui->actionToggle_hide_unhide_unselected, &QAction::triggered,
//            []() {  }); // TODO: Implement?
    connect(m_ui->actionAction, &QAction::triggered, this, &CMainFrame::OnViewAction);
    connect(m_ui->actionBasic_Objects, &QAction::triggered, this, &CMainFrame::OnViewBasicObjects);
    connect(m_ui->actionInspector, &QAction::triggered, this, &CMainFrame::OnViewInspector);
    connect(m_ui->actionProject, &QAction::triggered, this, &CMainFrame::OnViewProject);
    connect(m_ui->actionSlide, &QAction::triggered, this, &CMainFrame::OnViewSlide);
    connect(m_ui->actionTimeline, &QAction::triggered, this, &CMainFrame::OnViewTimeline);
    connect(m_ui->actionBounding_Boxes, &QAction::triggered,
            this, &CMainFrame::OnViewBoundingBoxes);
    connect(m_ui->actionPivot_Point, &QAction::triggered, this, &CMainFrame::OnViewPivotPoint);
    connect(m_ui->actionWireframe, &QAction::triggered, this, &CMainFrame::OnViewWireframe);
    connect(m_ui->actionTooltips, &QAction::triggered, this, &CMainFrame::OnViewTooltips);
//    connect(m_ui->actionFind, &QAction::triggered, this, &CMainFrame::onViewFind); // TODO: Implement

    // Timeline Menu
    connect(m_ui->actionSet_Changed_Keyframes, &QAction::triggered,
            this, &CMainFrame::OnTimelineSetChangedKeyframe);
    connect(m_ui->actionDelete_Selected_Keyframe_s, &QAction::triggered,
            [](){ g_StudioApp.DeleteSelectedKeys(); });
    connect(m_ui->actionSet_Interpolation, &QAction::triggered,
            this, &CMainFrame::OnTimelineSetInterpolation);
    connect(m_ui->actionChange_Time_Bar_Color, &QAction::triggered,
            this, &CMainFrame::OnTimelineSetTimeBarColor);
    connect(m_ui->actionAutoset_Keyframes, &QAction::triggered,
            this, &CMainFrame::OnToolAutosetkeys);

    // Help Menu
    connect(m_ui->action_Reference_Manual, &QAction::triggered, this, &CMainFrame::OnHelpIndex);
    connect(m_ui->action_Visit_Qt_Web_Site, &QAction::triggered, this, &CMainFrame::OnHelpVisitQt);
    connect(m_ui->action_About_Qt_3D_Studio, &QAction::triggered,
            []() { g_StudioApp.onAppAbout(); });
    connect(m_ui->action_Open_Tutorial, &QAction::triggered, this, &CMainFrame::OnHelpOpenTutorial);

    // Selection toolbar
    connect(m_ui->actionItem_Select_Tool, &QAction::triggered,
            m_sceneView.data(), &CSceneView::onToolItemSelection);
    connect(m_ui->actionGroup_Select_Tool, &QAction::triggered,
            m_sceneView.data(), &CSceneView::onToolGroupSelection);

    // Playback toolbar
    connect(m_ui->actionPreview, &QAction::triggered,
            this, &CMainFrame::OnPlaybackPreviewRuntime2);

    connect(m_ui->actionRemote_Preview, &QAction::triggered,
            this, &CMainFrame::OnPlaybackPreviewRemote);

    // Only show runtime1 preview if we have appropriate viewer and it's enabled
    if (CStudioPreferences::IsLegacyViewerActive()
            && CPreviewHelper::viewerExists(QStringLiteral("Qt3DViewer"))) {
        connect(m_ui->actionPreviewRuntime1, &QAction::triggered,
                this, &CMainFrame::OnPlaybackPreviewRuntime1);
    } else {
        m_ui->actionPreviewRuntime1->setVisible(false);
    }

    // Tool mode toolbar
    connect(m_ui->actionPosition_Tool, &QAction::triggered, this, &CMainFrame::OnToolMove);
    connect(m_ui->actionRotation_Tool, &QAction::triggered, this, &CMainFrame::OnToolRotate);
    connect(m_ui->actionScale_Tool, &QAction::triggered, this, &CMainFrame::OnToolScale);
    connect(m_ui->actionLocal_Global_Manipulators, &QAction::triggered,
            this, &CMainFrame::OnToolGlobalManipulators);

    // Edit Camera toolbar
#if 0 // TODO: Disabled until UX decision is made if these buttons are needed at all or not
    connect(m_ui->actionPan_Tool, &QAction::triggered, this, &CMainFrame::OnEditCameraPan);
    connect(m_ui->actionOrbit_Tool, &QAction::triggered, this, &CMainFrame::OnEditCameraRotate);
    connect(m_ui->actionZoom_Tool, &QAction::triggered, this, &CMainFrame::OnEditCameraZoom);
#endif
    connect(m_ui->actionShading_Mode, &QAction::triggered, this, &CMainFrame::OnEditViewFillMode);
    connect(m_ui->actionRulers_Guides, &QAction::triggered, this, &CMainFrame::OnViewGuidesRulers);
    connect(m_ui->actionClear_Guides, &QAction::triggered, this, &CMainFrame::OnClearGuides);
    connect(m_ui->actionLock_Guides, &QAction::triggered, this, &CMainFrame::OnLockGuides);

    // Others
    connect(m_remoteDeploymentSender.data(), &RemoteDeploymentSender::connectionChanged,
            this, &CMainFrame::OnConnectionChanged);

    // Hide unimplemented menu items
    m_ui->actionRepeat->setVisible(false);
    m_ui->actionGroup->setVisible(false);
    m_ui->actionParent->setVisible(false);
    m_ui->actionUnparent->setVisible(false);
    m_ui->actionFit_all->setVisible(false);
    m_ui->actionToggle_hide_unhide_unselected->setVisible(false);
    m_ui->actionFind->setVisible(false);

    // TODO: better solution?
    m_updateUITimer->start(500);
    connect(m_updateUITimer.data(), &QTimer::timeout, [&]() {
        if (QApplication::activeWindow() != this)
            return;

        OnUpdateFileSave();
        OnUpdateEditUndo();
        OnUpdateEditRedo();
        OnUpdateEditCopy();
        OnUpdateEditCut();
        OnUpdateToolAutosetkeys();
        OnUpdateEditPaste();
        OnUpdateEditDuplicate();
        OnUpdateTimelineDeleteSelectedKeyframes();
        OnUpdateTimelineSetInterpolation();
        OnUpdateTimelineSetTimeBarColor();
        OnUpdateViewBoundingBoxes();
        OnUpdateViewPivotPoint();
        OnUpdateViewWireframe();
        OnUpdateViewTooltips();
        OnUpdateViewTimeline();
        OnUpdateViewInspector();
        OnUpdateViewAction();
        OnUpdateViewBasicObjects();
        OnUpdateViewProject();
        OnUpdateViewSlide();
        OnUpdateHelpIndex();
        OnUpdatePlaybackPlay();
        OnUpdatePlaybackRewind();
        OnUpdatePlaybackStop();
        OnUpdatePlaybackPreview();
        OnUpdateToolMove();
        OnUpdateToolRotate();
        OnUpdateToolScale();
        OnUpdateToolGlobalManipulators();
        OnUpdateToolGroupSelection();
        OnUpdateToolItemSelection();
        OnUpdateCameraZoomExtentAndAuthorZoom();
        OnUpdateEditCameraPan();
        OnUpdateEditCameraRotate();
        OnUpdateEditCameraZoom();
        OnUpdateEditViewFillMode();
        OnUpdateViewGuidesRulers();
        OnUpdateClearGuides();
        OnUpdateLockGuides();
    });

    m_playbackTimer->setInterval(PLAYBACK_TIMER_TIMEOUT);
    connect(m_playbackTimer.data(), &QTimer::timeout, this, &CMainFrame::onPlaybackTimeout);
    qApp->installEventFilter(this);
}

//==============================================================================
/**
 * Destructor
 */
CMainFrame::~CMainFrame()
{
    qApp->removeEventFilter(this);
    m_playbackTimer->stop();
    m_updateUITimer->stop();
}

//==============================================================================
/**
 *	Timer callback
 */
void CMainFrame::onPlaybackTimeout()
{
    // Timer callback that drives playback
    Q_ASSERT(&g_StudioApp);
    g_StudioApp.GetCore()->GetDoc()->ClientStep();
}

//==============================================================================

void CMainFrame::showEvent(QShowEvent *event)
{
    QMainWindow::showEvent(event);
    handleGeometryAndState(false);
}

void CMainFrame::hideEvent(QHideEvent *event)
{
    QMainWindow::hideEvent(event);
    handleGeometryAndState(true);
}

/**
 * Called when the main frame is actually created.  Sets up tool bars and default
 * views.
 */
void CMainFrame::OnCreate()
{
    m_sceneView.reset(new CSceneView(this));
    connect(m_sceneView.data(), &CSceneView::toolChanged, this, &CMainFrame::OnUpdateToolChange);

    m_sceneView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // tell the edit camera bar about this scene view
    m_ui->m_EditCamerasBar->SetSceneView(m_sceneView.data());

    // Newly launched, the file dialog for open and import should default to more recent
    // opened/imported
    CDialogs *theDialogs = g_StudioApp.GetDialogs();
    // this must NOT be in 'command line' mode
    if (theDialogs) {
        Q3DStudio::CString theMostRecentOpen;
        if (m_recentItems && m_recentItems->GetItemCount() > 0)
            theMostRecentOpen = m_recentItems->GetItem(0).GetPath();
        if (theMostRecentOpen.IsEmpty()) // default to exe
            theMostRecentOpen = Qt3DSFile::GetApplicationDirectory().GetPath();

        theDialogs->ResetSettings(theMostRecentOpen);
    }

    // Create the view manager
    m_paletteManager.reset(new CPaletteManager(this));

    // Remove basic toolbar (open, save, undo/redo, etc.)
    // Kept in ui form in case it is going to be added back later on.
    delete m_ui->toolBar;

    // Disable toolbars and menus until we have a presentation
    m_ui->m_ClientToolsBar->setEnabled(false);
    m_ui->m_EditCamerasBar->setEnabled(false);
    m_ui->m_PlaybackToolbar->setEnabled(false);
    m_ui->menu_Edit->setEnabled(false);
    m_ui->menu_Timeline->setEnabled(false);
    m_ui->menu_View->setEnabled(false);
    m_ui->actionSave_As->setEnabled(false);
    m_ui->actionSave_a_Copy->setEnabled(false);
    m_ui->action_Connect_to_Device->setEnabled(false);
    m_ui->action_Revert->setEnabled(false);
    m_ui->actionImportAssets->setEnabled(false);
    m_ui->actionRemote_Preview->setEnabled(false);

#if 1 // TODO: Hidden until UX decision is made if these buttons are needed at all or not
    m_ui->actionPan_Tool->setVisible(false);
    m_ui->actionOrbit_Tool->setVisible(false);
    m_ui->actionZoom_Tool->setVisible(false);
#endif

    // Show a message about opening or creating a presentation
    m_sceneView.data()->setVisible(false);
    setCentralWidget(m_ui->infoText);
}

//==============================================================================
/**
 * Called when a new presenation is created.  We have to wait to associate the
 * scene object with the scene view until this point, because the scene object
 * does not exist until this function gets called.
 */
void CMainFrame::OnNewPresentation()
{
    // Make sure scene is visible
    showScene();

    // Associate the scene object with the scene view
    m_ui->m_EditCamerasBar->SetupCameras();
    // Enable dockables, toolbars, and menus
    m_paletteManager->EnablePalettes();
    m_ui->m_ClientToolsBar->setEnabled(true);
    m_ui->m_EditCamerasBar->setEnabled(true);
    m_ui->m_PlaybackToolbar->setEnabled(true);
    m_ui->menu_Edit->setEnabled(true);
    m_ui->menu_Timeline->setEnabled(true);
    m_ui->menu_View->setEnabled(true);
    m_ui->actionSave_As->setEnabled(true);
    m_ui->actionSave_a_Copy->setEnabled(true);
    m_ui->action_Connect_to_Device->setEnabled(true);
    m_ui->action_Revert->setEnabled(true);
    m_ui->actionImportAssets->setEnabled(true);

    // Clear data input list and sub-presentation list
    g_StudioApp.m_subpresentations.clear();
    g_StudioApp.m_dataInputDialogItems.clear();
}

//==============================================================================
/**
 * Called when the current presentation is being closed.
 * This will close all the editor windows that are open.
 */
void CMainFrame::OnClosingPresentation()
{
}

//==============================================================================
/**
 * Handles the Timeline | Set Interpolation menu item
 *	This is a temporary method that will display the Set Interpolation dialog.
 */
void CMainFrame::OnTimelineSetInterpolation()
{
    g_StudioApp.GetCore()->GetDoc()->SetKeyframeInterpolation();
}

//==============================================================================
/**
 *	OnEditRedo: calls handleRedoOperation
 */
//==============================================================================
void CMainFrame::OnEditRedo()
{
    g_StudioApp.GetCore()->GetCmdStack()->Redo();
}

//==============================================================================
/**
 *	OnEditUndo: calls HandleUndoOperation
 */
//==============================================================================
void CMainFrame::OnEditUndo()
{
    g_StudioApp.GetCore()->GetCmdStack()->Undo();
}

//==============================================================================
/**
 *	OnUpdateEditUndo: Handler for ID_EDIT_UNDO message
 *
 *	@param	pCmndUI	The UI element that generated the message
 */
void CMainFrame::OnUpdateEditUndo()
{
    const QString undoDescription = QObject::tr("Undo %1\tCtrl+Z").arg(
                g_StudioApp.GetCore()->GetCmdStack()->GetUndoDescription());
    m_ui->action_Undo->setEnabled(g_StudioApp.CanUndo());
    m_ui->action_Undo->setText(undoDescription);
}

//==============================================================================
/**
 *	OnUpdateEditRedo: handles the message ID_EDIT_REDO
 *
 *	@param	pCmndUI	The UI element that generated the message
 */
void CMainFrame::OnUpdateEditRedo()
{
    const QString redoDescription = QObject::tr("Redo %1\tCtrl+Y").arg(
                g_StudioApp.GetCore()->GetCmdStack()->GetRedoDescription());
    m_ui->action_Redo->setEnabled(g_StudioApp.CanRedo());
    m_ui->action_Redo->setText(redoDescription);
}

//==============================================================================
/**
 *	OnEditCopy: Handles the Copy message
 *
 *	Tells the doc to copy the selected keyframes.
 */
void CMainFrame::OnEditCopy()
{
    g_StudioApp.OnCopy();
}

//==============================================================================
/**
 *	OnUpdateEditCopy: Handle the update UI command for the copy button and menu item
 *
 *	If there are keyframes selected, the button is enabled, otherwise, it is
 *	disabled.
 *
 *	@param	pCmndUI	The UI element that generated the message
 */
void CMainFrame::OnUpdateEditCopy()
{
    if (g_StudioApp.CanCopy() && !m_actionActive) {
        QString theDescription = tr("Copy %1\tCtrl+C").arg(g_StudioApp.GetCopyType());

        m_ui->action_Copy->setText(theDescription);
        m_ui->action_Copy->setEnabled(true);
    } else {
        m_ui->action_Copy->setEnabled(false);
    }
}

//==============================================================================
/**
 *	OnEditCut: Handles the Cut message
 *
 *	Tells the doc to cut the selected keyframes.
 */
void CMainFrame::OnEditCut()
{
    g_StudioApp.OnCut();
}

//==============================================================================
/**
 *	OnUpdateEditCut: Handle the update UI command for the cut button and menu item
 *
 *	If there are keyframes selected, the button is enabled, otherwise, it is
 *	disabled.
 *
 *	@param	pCmndUI	The UI element that generated the message
 */
void CMainFrame::OnUpdateEditCut()
{
    if (g_StudioApp.CanCut() && !m_actionActive) {
        QString theDescription = tr("Cut %1\tCtrl+X").arg(g_StudioApp.GetCopyType());

        m_ui->action_Cut->setText(theDescription);
        m_ui->action_Cut->setEnabled(true);
    } else {
        m_ui->action_Cut->setEnabled(false);
    }
}

//==============================================================================
/**
 *	OnEditPaste: Handles the Paste command
 *
 *	Tells the doc to paste the copied keyframes at the current playhead time, on
 *	the currently selected object.
 */
void CMainFrame::OnEditPaste()
{
    g_StudioApp.OnPaste();
}

void CMainFrame::onEditPasteToMaster()
{
    g_StudioApp.GetCore()->GetDoc()->HandleMasterPaste();
}

//==============================================================================
/**
 *	OnUpdateEditPaste: Handle the update UI command for the paste button and menu item
 *
 *	If there we can perform a keyframe paste, the button is enabled, otherwise, it is
 *	disabled.
 *
 *	@param	pCmndUI	The UI element that generated the message
 */
void CMainFrame::OnUpdateEditPaste()
{
    if (g_StudioApp.CanPaste() && !m_actionActive) {
        QString theUndoDescription = tr("Paste %1\tCtrl+V").arg(g_StudioApp.GetPasteType());

        m_ui->action_Paste->setText(theUndoDescription);

        m_ui->action_Paste->setEnabled(true);
        m_ui->actionPaste_to_Master_Slide->setEnabled(true);
    } else {
        m_ui->action_Paste->setEnabled(false);
        m_ui->actionPaste_to_Master_Slide->setEnabled(false);
    }
}

//=============================================================================
/**
 * Called when a tool mode changes from a modifier key
 */
void CMainFrame::OnUpdateToolChange()
{
    long theSelectMode = g_StudioApp.GetSelectMode();
    m_ui->actionGroup_Select_Tool->setChecked(theSelectMode == STUDIO_SELECTMODE_GROUP);
    m_ui->actionItem_Select_Tool->setChecked(theSelectMode == STUDIO_SELECTMODE_ENTITY);

    // See what tool mode we are in and change checks accordingly
    long theToolMode = g_StudioApp.GetToolMode();
    m_ui->actionPosition_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_MOVE);
    m_ui->actionRotation_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_ROTATE);
    m_ui->actionScale_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_SCALE);
    m_ui->actionLocal_Global_Manipulators->setChecked(g_StudioApp.GetManipulationMode()
                                                      == StudioManipulationModes::Global);

#if 0 // TODO: Disabled until UX decision is made if these buttons are needed at all or not
    m_ui->actionPan_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_CAMERA_PAN);
    m_ui->actionOrbit_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_CAMERA_ROTATE);
    m_ui->actionZoom_Tool->setChecked(theToolMode == STUDIO_TOOLMODE_CAMERA_ZOOM);
#endif
}

//==============================================================================
/**
 *	OnTimelineSettimebarcolor: Handles the ID_TIMELINE_SETTIMEBARCOLOR message.
 *
 *	Called when the user clicks on Timeline->Change Time Bar Color.  Changes
 *	the currently selected timebar's color.
 */
void CMainFrame::OnTimelineSetTimeBarColor()
{
    getTimelineWidget()->openBarColorDialog();
}

//==============================================================================
/**
 *	OnUpdateTimelineSetTimeBarColor: Handles the update UI message for the
 *	"Change Time Bar Color" menu item.
 *
 *	If the currently selected object is an item in the timeline and it has a
 *	time bar, this menu item is enabled.  Otherwise, the menu item is disabled.
 *
 *	@param pCmndUI	Pointer to the ui object that generated this update message.
 */
void CMainFrame::OnUpdateTimelineSetTimeBarColor()
{
    m_ui->actionChange_Time_Bar_Color->setEnabled(g_StudioApp.CanChangeTimebarColor());
}

//==============================================================================
/**
 *	OnTimelineSetChangedKeyframe: Handles the ID_TIMELINE_SETCHANGEDKEYFRAME message.
 *
 *	Calls the StudioDoc handler to insert keyframes for animatable properties that
 *	have changed.
 */
void CMainFrame::OnTimelineSetChangedKeyframe()
{
    g_StudioApp.HandleSetChangedKeys();
}

//==============================================================================
/**
 *	OnUpdateTimelineDeleteSelectedKeyframes: Handles the update UI message for
 *	the "Delete Selected Keyframe(s)" message.
 *
 *	If there are currently keyframes selected, the menu item is enabled.  Otherwise,
 *	the menu item is disabled.
 *
 *	@param pCmdUI	The UI element that generated this message
 */
void CMainFrame::OnUpdateTimelineDeleteSelectedKeyframes()
{
    m_ui->actionDelete_Selected_Keyframe_s->setEnabled(getTimelineWidget()->hasSelectedKeyframes());
}

//==============================================================================
/**
 *	OnUpdateTimelineSetInterpolation: Handles the update UI message for
 *	the "Set Interpolation" message.
 *
 *	If there are currently keyframes selected, this menu item is enabled, otherwise
 *	it is disabled.
 *
 *	@param pCmdUI	The UI element that generated this message
 */
void CMainFrame::OnUpdateTimelineSetInterpolation()
{
    m_ui->actionSet_Interpolation->setEnabled(
                g_StudioApp.GetCore()->GetDoc()->GetKeyframesManager()->HasSelectedKeyframes());
}

//==============================================================================
/**
 *	OnEditDuplicate: Handles the ID_EDIT_DUPLICATE message.
 *
 *	Pass through to the doc.
 */
void CMainFrame::OnEditDuplicate()
{
    g_StudioApp.HandleDuplicateCommand(m_slideActive);
}

void CMainFrame::onEditDelete()
{
    g_StudioApp.DeleteSelectedObject(m_slideActive);
}

//==============================================================================
/**
 *	OnUpdateEditDuplicate: Handles the UPDATE COMMAND UI message for this menu item.
 *
 *	If the currently selected object is not null, and it is not in the library,
 *	then the user can duplicate the object and the menu item is enabled.  Otherwise,
 *	it is disabled.
 */
void CMainFrame::OnUpdateEditDuplicate()
{
    m_ui->action_Duplicate_Object->setEnabled(m_slideActive || g_StudioApp.CanDuplicateObject());
}

//=============================================================================
/**
 * Command handler for the File Open menu and toolbar options.
 * This will save the file, if the file has not been saved before this will
 * do a save as operation.
 */
void CMainFrame::OnFileOpen()
{
    g_StudioApp.OnFileOpen();
}

//=============================================================================
/**
 * Command handler for the File Save menu and toolbar options.
 * This will save the file, if the file has not been saved before this will
 * do a save as operation.
 */
void CMainFrame::OnFileSave()
{
    g_StudioApp.OnSave();
}

void CMainFrame::OnUpdateFileSave()
{
    m_ui->action_Save->setEnabled(g_StudioApp.GetCore()->GetDoc()->IsModified());
}
//=============================================================================
/**
 * Command handler for the File Save As menu option.
 * This will prompt the user for a location to save the file out to then
 * will perform the save.
 */
void CMainFrame::OnFileSaveAs()
{
    g_StudioApp.OnSaveAs();
}

//=============================================================================
/**
 * Command handler for the File Save a Copy menu option.
 * This will prompt the user for a location to save the file out to then
 * save a copy, leaving the original file open in the editor.
 */
void CMainFrame::OnFileSaveCopy()
{
    g_StudioApp.OnSaveCopy();
}

//=============================================================================
/**
 * Command handler for the New Document menu option.
 * This will create a new default document.
 */
void CMainFrame::OnFileNew()
{
    g_StudioApp.OnFileNew();
}

void CMainFrame::onCtrlNPressed()
{
    static QMap<int, int> key2index {
        {1, 9},         // Scene Camera View
        {2, 0}, {3, 1}, // Perspective & Orthographic
        {4, 2}, {5, 3}, // Top & Bottom
        {6, 4}, {7, 5}, // Left & Right
        {8, 6}, {9, 7}, // Front & Back
    };

    QAction *action = qobject_cast<QAction *>(sender());
    Q_ASSERT(action);
    QKeySequence shortcut = action->shortcut();
    QMapIterator<int, int> i(key2index);
    while (i.hasNext()) {
        i.next();
        QKeySequence keySequence(Qt::CTRL | static_cast<Qt::Key>(Qt::Key_0 + i.key()));
        if (shortcut.matches(keySequence) == QKeySequence::ExactMatch) {
            m_ui->m_EditCamerasBar->setCameraIndex(i.value());
            break;
        }
    }
}

//==============================================================================
/**
 * Overrides the close method to prompt if the document is modified.
 */
void CMainFrame::closeEvent(QCloseEvent *event)
{
    handleGeometryAndState(true);
    QMainWindow::closeEvent(event);

    if (g_StudioApp.GetCore()->GetDoc()->IsModified()) {
        CDialogs::ESavePromptResult theResult = g_StudioApp.GetDialogs()->PromptForSave();
        if (theResult == CDialogs::SAVE_FIRST) {
            // If the save was canceled or failed then do not exit.
            if (!g_StudioApp.OnSave())
                return;
        } else if (theResult == CDialogs::CANCEL_OPERATION) {
            // On cancel ditch out of here and abort exit. Abort! Abort!
            event->ignore();
            return;
        }
    }

    // Tell the app to shutdown, do it here so it does not rely on static destructor.
    g_StudioApp.performShutdown();
}

//==============================================================================
/**
 *	Displays the preferences dialog and can change program settings.
 */
void CMainFrame::OnEditApplicationPreferences()
{
    EditPreferences(PAGE_STUDIOAPPPREFERENCES);
}

//==============================================================================
/**
 *	Displays the preferences dialog and can change program settings.
 */
void CMainFrame::OnEditPresentationPreferences()
{
    EditPreferences(PAGE_STUDIOPROJECTSETTINGS);
}

//==============================================================================
/**
 *  Displays the sub-presentation dialog.
 */
void CMainFrame::OnFileSubPresentations()
{
    QString dir = g_StudioApp.GetCore()->GetDoc()->GetDocumentDirectory().toQString();

    CSubPresentationListDlg dlg(QDir::toNativeSeparators(dir), g_StudioApp.m_subpresentations);
    dlg.exec();
    if (dlg.result() == QDialog::Accepted) {
        g_StudioApp.m_subpresentations = dlg.subpresentations();
        g_StudioApp.SaveUIAFile();
    }
}

//==============================================================================
/**
 *  Displays the data input dialog.
 */
void CMainFrame::OnFileDataInputs()
{
    CDataInputListDlg dataInputDlg(&(g_StudioApp.m_dataInputDialogItems));
    dataInputDlg.exec();

    if (dataInputDlg.result() == QDialog::Accepted)
        g_StudioApp.SaveUIAFile(false);
}

//==============================================================================
/**
 *	EditPreferences: Displays the presentation settings property sheet with
 *					 the specified active page.
 *
 *	Used for editing the application and project settings.
 *
 *	@param	inPageIndex		The page index to select when displayed.
 */
void CMainFrame::EditPreferences(short inPageIndex)
{
    // Set the active page based on the inPageIndex
    m_propSheet.reset(new CStudioPreferencesPropSheet(tr("Studio Preferences"), this, inPageIndex));

    // Display the CStudioPreferencesPropSheet
    int thePrefsReturn = m_propSheet->exec();

    m_sceneView->onEditCameraChanged();

    if (thePrefsReturn == PREFS_RESET_DEFAULTS) {
        // Restore default values
        g_StudioApp.SetAutosetKeyframes(true); // Sets the preference as well
        CStudioPreferences::SetBoundingBoxesOn(true);
        CStudioPreferences::SetDisplayPivotPoint(true);
        CStudioPreferences::SetWireframeModeOn(true);
        CStudioPreferences::SetShowTooltips(true);
        CStudioPreferences::SetTimebarDisplayTime(false);
        g_StudioApp.GetCore()->GetDoc()->SetDefaultKeyframeInterpolation(true);
        CStudioPreferences::SetSnapRange(CStudioPreferences::DEFAULT_SNAPRANGE);
        CStudioPreferences::SetDefaultObjectLifetime(CStudioPreferences::DEFAULT_LIFETIME);
        CStudioPreferences::SetAdvancePropertyExpandedFlag(false);
        CStudioPreferences::SetPreviewConfig("");
        CStudioPreferences::SetPreviewProperty("", "");
        CStudioPreferences::SetDontShowGLVersionDialog(false);
        CStudioPreferences::SetDefaultClientSize(CStudioPreferences::DEFAULT_CLIENT_WIDTH,
                                                 CStudioPreferences::DEFAULT_CLIENT_HEIGHT);
        CStudioPreferences::SetTimeAdvanceAmount(CStudioPreferences::DEFAULT_TIME_ADVANCE);
        CStudioPreferences::SetBigTimeAdvanceAmount(CStudioPreferences::DEFAULT_BIG_TIME_ADVANCE);
        CStudioPreferences::SetTimelineSnappingGridActive(true);
        CStudioPreferences::SetTimelineSnappingGridResolution(SNAPGRID_SECONDS);
        CStudioPreferences::SetLegacyViewerActive(false);
        // Hide legacy viewer preview button
        m_ui->actionPreviewRuntime1->setVisible(false);
        CStudioPreferences::SetEditViewFillMode(true);
        CStudioPreferences::SetEditViewBackgroundColor(CStudioPreferences::EDITVIEW_DEFAULTBGCOLOR);
        CStudioPreferences::SetPreferredStartupView(
                    CStudioPreferences::PREFERREDSTARTUP_DEFAULTINDEX);
        CStudioPreferences::SetAutoSaveDelay(CStudioPreferences::DEFAULT_AUTOSAVE_DELAY);
        CStudioPreferences::SetAutoSavePreference(true);
        CStudioPreferences::setSelectorLineWidth(
                    (float)CStudioPreferences::DEFAULT_SELECTOR_WIDTH / 10.0f);
        CStudioPreferences::setSelectorLineLength(
                    (float)CStudioPreferences::DEFAULT_SELECTOR_LENGTH);

        RecheckSizingMode();
    } else if (thePrefsReturn == PREFS_RESET_LAYOUT) {
        onViewResetLayout();
    } else if (thePrefsReturn == PREFS_SETTINGS_RESTART) {
        QTimer::singleShot(0, this, &CMainFrame::handleRestart);
    }
}

//==============================================================================
/**
 *	OnToolAutosetkeys: Called when the Autoset Keyframe button is pressed.
 *	Calls the doc to turn off or on the Autoset Keyframe preference.
 */
void CMainFrame::OnToolAutosetkeys()
{
    // Toggle autoset keyframes to the opposite of what it's currently set as
    g_StudioApp.SetAutosetKeyframes(!CStudioPreferences::IsAutosetKeyframesOn());

    // Don't wait for regular update cycle to update the corresponding toolbar/menu checked status
    m_ui->actionAutoset_Keyframes->setChecked(CStudioPreferences::IsAutosetKeyframesOn());
}

//==============================================================================
/**
 *	OnUpdateToolAutosetkeys: Updates the UI associated with this button.
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolAutosetkeys()
{
    // If autoset keyframes is on
    m_ui->actionAutoset_Keyframes->setChecked(CStudioPreferences::IsAutosetKeyframesOn());
}

//==========================================================================
/**
 *	Called when the presentation is being played in Studio.  Updates the play
 *	button on the main frame.
 */
void CMainFrame::OnPlayStart()
{
    // Update the play button since this doesn't always happen automatically
    Q_EMIT playStateChanged(true);

    if (m_playbackFlag == false) {
        m_playbackFlag = true;
        m_playbackTimer->start();
    }
}

//==========================================================================
/**
 *	Called when the presentation stops being played in Studio.  Updates the play
 *	button on the main frame.
 */
void CMainFrame::OnPlayStop()
{
    // Update the play button since this doesn't always happen automatically
    Q_EMIT playStateChanged(false);

    if (m_playbackFlag == true) {
        m_playbackFlag = false;
        m_playbackTimer->stop();
    }
}

//==========================================================================
/**
 *	Called when the presentation time changes.  Not handled by this class,
 *	but included because the base class requires it to be implemented.
 */
void CMainFrame::OnTimeChanged(long inTime)
{
    if (m_paletteManager)
        m_paletteManager->onTimeChanged(inTime);
}

//==============================================================================
/**
 *	Handles pressing the play button.
 */
void CMainFrame::OnPlaybackPlay()
{
    g_StudioApp.PlaybackPlay();
}

//==============================================================================
/**
 *	Handles pressing of the stop button.
 */
void CMainFrame::OnPlaybackStop()
{
    g_StudioApp.PlaybackStopNoRestore();
}

//==============================================================================
/**
 *	Handles pressing the preview button.
 */
void CMainFrame::OnPlaybackPreview(const QString &viewerExeName, bool remote)
{
    if (remote && m_remoteDeploymentSender->isConnected()) {
        g_StudioApp.GetCore()->GetDispatch()->FireOnProgressBegin(
                    Q3DStudio::CString::fromQString(QObject::tr("Deploying to remote device...")),
                    "");
        CPreviewHelper::OnDeploy(*m_remoteDeploymentSender);
        g_StudioApp.GetCore()->GetDispatch()->FireOnProgressEnd();
    } else {
        CPreviewHelper::OnPreview(viewerExeName);
    }
}

void CMainFrame::OnPlaybackPreviewRuntime1()
{
    OnPlaybackPreview(QStringLiteral("Qt3DViewer"));
}

void CMainFrame::OnPlaybackPreviewRuntime2()
{
    OnPlaybackPreview(QStringLiteral("q3dsviewer"));
}

void CMainFrame::OnPlaybackPreviewRemote()
{
    OnPlaybackPreview(QStringLiteral("q3dsviewer"), true);
}

//==============================================================================
/**
 *	Handles the update ui message for the preview button.
 *	Adding more UI updating here would just be redundant.
 *	@param inCmdUI Pointer to the UI element that needs updating
 */
void CMainFrame::OnUpdatePlaybackPreview()
{
}

//==============================================================================
/**
 *	Handles the update ui message for the play button.  Does nothing because the
 *	button state is being updated manually in OnPlayStart() and OnPlayStop.
 *	Adding more UI updating here would just be redundant.
 *	@param inCmdUI Pointer to the UI element that needs updating
 */
void CMainFrame::OnUpdatePlaybackPlay()
{
}

//==============================================================================
/**
 *	Handles pressing the rewind button.
 */
void CMainFrame::OnPlaybackRewind()
{
    g_StudioApp.PlaybackRewind();
}

//==============================================================================
/**
 *	Handles the update ui message for the rewind button.  Does nothing because
 *	no additional ui handling is necessary for this button.
 *	@param inCmdUI Pointer to the UI element that needs updating
 */
void CMainFrame::OnUpdatePlaybackRewind()
{
}

//==============================================================================
/**
 *	Handles the update ui message for the stop button.  Doesn't do anything
 *	because no special ui handling is necessary for the stop button.
 *	@param inCmdUI Pointer to the UI element that needs updating
 */
void CMainFrame::OnUpdatePlaybackStop()
{
}

//==============================================================================
/**
 *	Registers all the keys it will need for shortcuts, also telsl children to register theirs
 *  @param inHotKeys the hotkeys to with which to register
 */
void CMainFrame::RegisterGlobalKeyboardShortcuts(CHotKeys *inHotKeys, QWidget *actionParent)
{
    // Default undo shortcut is Ctrl-Y, which is specified in main form. Let's add the common
    // alternate shortcut for redo, CTRL-SHIFT-Z
    ADD_GLOBAL_SHORTCUT(actionParent,
                        QKeySequence(Qt::ControlModifier | Qt::ShiftModifier | Qt::Key_Z),
                        CMainFrame::OnEditRedo);

    ADD_GLOBAL_SHORTCUT(actionParent,
                        QKeySequence(Qt::Key_Q),
                        CMainFrame::toggleSelectMode);

    for (int keyN = Qt::Key_1; keyN <= Qt::Key_9; keyN++) {
        ADD_GLOBAL_SHORTCUT(actionParent,
                            QKeySequence(Qt::CTRL | static_cast<Qt::Key>(keyN)),
                            CMainFrame::onCtrlNPressed);
    }
}

//==============================================================================
/**
 *	OnUpdateToolMove: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateToolMove()
{
    long theCurrentToolSettings = g_StudioApp.GetToolMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionPosition_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_MOVE
                                          && m_ui->actionPosition_Tool->isEnabled());
}

//==============================================================================
/**
 *	OnUpdateToolRotate: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolRotate()
{
    long theCurrentToolSettings = g_StudioApp.GetToolMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionRotation_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_ROTATE
                                          && m_ui->actionRotation_Tool->isEnabled());
}

//==============================================================================
/**
 *	OnUpdateToolScale: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolScale()
{
    long theCurrentToolSettings = g_StudioApp.GetToolMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionScale_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_SCALE
                                       && m_ui->actionScale_Tool->isEnabled());
}

//==============================================================================
/**
 *	OnUpdateToolScale: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolGlobalManipulators()
{
    StudioManipulationModes::Enum theMode = g_StudioApp.GetManipulationMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionLocal_Global_Manipulators->setChecked(
                theMode == StudioManipulationModes::Global
                && m_ui->actionLocal_Global_Manipulators->isEnabled());
}

//==============================================================================
/**
 *	OnToolMove: Called when the Move button is pressed.
 *	Sets the current tool mode and changes the cursor.
 */
void CMainFrame::OnToolMove()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_MOVE);
    m_sceneView->setToolMode(STUDIO_TOOLMODE_MOVE);
}

//==============================================================================
/**
 *	OnToolRotate: Called when the Rotate button is pressed.
 *	Sets the current tool mode and changes the cursor.
 */
void CMainFrame::OnToolRotate()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_ROTATE);
    m_sceneView->setToolMode(STUDIO_TOOLMODE_ROTATE);
}

//==============================================================================
/**
 *	OnToolScale: Called when the Scale button is pressed.
 *	Sets the current tool mode and changes the cursor.
 */
void CMainFrame::OnToolScale()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_SCALE);
    m_sceneView->setToolMode(STUDIO_TOOLMODE_SCALE);
}

void CMainFrame::OnToolGlobalManipulators()
{
    if (m_ui->actionLocal_Global_Manipulators->isChecked())
        g_StudioApp.SetManipulationMode(StudioManipulationModes::Global);
    else
        g_StudioApp.SetManipulationMode(StudioManipulationModes::Local);

    g_StudioApp.getRenderer().RequestRender();
}

//==============================================================================
/**
 *	OnUpdateToolGroupSelection: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolGroupSelection()
{
    long theCurrentSelectSettings = g_StudioApp.GetSelectMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionGroup_Select_Tool->setChecked(theCurrentSelectSettings == STUDIO_SELECTMODE_GROUP
                                              && m_ui->actionGroup_Select_Tool->isEnabled());
}

//==============================================================================
/**
 *	OnUpdateToolItemSelection: Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	tool mode, and whether or not the button is enabled.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
void CMainFrame::OnUpdateToolItemSelection()
{
    long theCurrentSelectSettings = g_StudioApp.GetSelectMode();

    // If the current tool mode matches this button
    // If the button is currently enabled
    m_ui->actionItem_Select_Tool->setChecked(theCurrentSelectSettings == STUDIO_SELECTMODE_ENTITY
                                             && m_ui->actionItem_Select_Tool->isEnabled());
}

//==============================================================================
/**
 *	Called when the edit camera Zoom Extent button is pressed.
 *	Inform the current active edit camera to toggle itself.
 */
void CMainFrame::OnEditCameraZoomExtent()
{
    if (g_StudioApp.getRenderer().GetEditCamera() >= 0)
        g_StudioApp.getRenderer().EditCameraZoomToFit();
    else
        g_StudioApp.SetAuthorZoom(!g_StudioApp.IsAuthorZoom());
}

//==============================================================================
/**
 *	Called when the "Zoom Extent" keyboard shortcut is pressed.
 *	Inform the current active edit camera to toggle itself.
 */
//==============================================================================
void CMainFrame::HandleEditCameraZoomExtent()
{
    OnEditCameraZoomExtent();
}

//==============================================================================
/**
 *	Called when the Pan Edit Camera button is pressed.
 *	Inform the current active edit camera on their tool mode.
 */
void CMainFrame::OnEditCameraPan()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_CAMERA_PAN);
    m_sceneView->setViewCursor(); // Just set cursor, we don't want to update previous tool
}

//==============================================================================
/**
 *	Called when the Rotate Edit Camera button is pressed.
 *	Inform the current active edit camera on their tool mode.
 */
void CMainFrame::OnEditCameraRotate()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_CAMERA_ROTATE);
    m_sceneView->setViewCursor(); // Just set cursor, we don't want to update previous tool
}

//==============================================================================
/**
 *	Called when the Zoom Edit Camera button is pressed.
 *	Inform the current active edit camera on their tool mode.
 */
void CMainFrame::OnEditCameraZoom()
{
    g_StudioApp.SetToolMode(STUDIO_TOOLMODE_CAMERA_ZOOM);
    m_sceneView->setViewCursor(); // Just set cursor, we don't want to update previous tool
}

//==============================================================================
/**
 *	Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	settings of the current edit camera tool.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateCameraZoomExtentAndAuthorZoom()
{
    if (m_sceneView.data() == GetActiveView() && !m_sceneView->isDeploymentView())
        m_ui->actionFit_Selected->setChecked(false);
    else
        m_ui->actionFit_Selected->setChecked(g_StudioApp.IsAuthorZoom());
}

//==============================================================================
/**
 *	Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	settings of the current edit camera tool.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateEditCameraPan()
{
    if (m_sceneView.data() == GetActiveView() && !m_sceneView->isDeploymentView()) {
        m_ui->actionPan_Tool->setEnabled(true);

        long theCurrentToolSettings = g_StudioApp.GetToolMode();
        m_ui->actionPan_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_CAMERA_PAN);
    } else {
        m_ui->actionPan_Tool->setEnabled(false);
        m_ui->actionPan_Tool->setChecked(false);
    }
}

//==============================================================================
/**
 *	Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	settings of the current edit camera tool.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateEditCameraRotate()
{
#if 0 // TODO: Disabled until UX decision is made if these buttons are needed at all or not
    if (m_SceneView == GetActiveView() && !m_SceneView->IsDeploymentView()
            && g_StudioApp.GetRenderer().DoesEditCameraSupportRotation(
                g_StudioApp.GetRenderer().GetEditCamera())) {
        m_ui->actionOrbit_Tool->setEnabled(true);

        long theCurrentToolSettings = g_StudioApp.GetToolMode();
        m_ui->actionOrbit_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_CAMERA_ROTATE);
    } else {
        m_ui->actionOrbit_Tool->setEnabled(false);
        m_ui->actionOrbit_Tool->setChecked(false);
    }
#endif
}

//==============================================================================
/**
 *	Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	settings of the current edit camera tool.
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateEditCameraZoom()
{
    if (m_sceneView.data() == GetActiveView() && !m_sceneView->isDeploymentView()) {
        m_ui->actionZoom_Tool->setEnabled(true);

        long theCurrentToolSettings = g_StudioApp.GetToolMode();
        m_ui->actionZoom_Tool->setChecked(theCurrentToolSettings == STUDIO_TOOLMODE_CAMERA_ZOOM);
    } else {
        m_ui->actionZoom_Tool->setEnabled(false);
        m_ui->actionZoom_Tool->setChecked(false);
    }
}

//==============================================================================
/**
 *	Called when the "Render geometry as solid/wireframe in edit view" button is pressed.
 *	Toggle the mode and update the studio preferences, also cache it in EditCameraContainer
 */
//==============================================================================
void CMainFrame::HandleEditViewFillModeKey()
{
    if (m_sceneView.data() == GetActiveView() && !m_sceneView->isDeploymentView()) {
        OnEditViewFillMode();
        bool theEditViewFillMode = g_StudioApp.getRenderer().IsEditLightEnabled();
        m_ui->actionShading_Mode->setChecked(theEditViewFillMode);
    }
}

//==============================================================================
/**
 *	Called when the "Render geometry as solid/wireframe in edit view" button is pressed.
 *	Toggle the mode and update the studio preferences, also cache it in EditCameraContainer
 */
//==============================================================================
void CMainFrame::OnEditViewFillMode()
{
    bool theEditViewFillMode = !g_StudioApp.getRenderer().IsEditLightEnabled();
    g_StudioApp.getRenderer().SetEnableEditLight(theEditViewFillMode);
}

//==============================================================================
/**
 *	Updates the UI associated with this button.
 *
 *	Checks or unchecks this button on the toolbar, depending on the current
 *	settings of the "Render geometry as solid/wireframe in edit view".
 *
 *	@param pCmdUI Pointer to the button that generated the message.
 */
//==============================================================================
void CMainFrame::OnUpdateEditViewFillMode()
{
    if (m_sceneView.data() == GetActiveView() && !m_sceneView->isDeploymentView()) {
        m_ui->actionShading_Mode->setEnabled(true);
        m_ui->actionShading_Mode->setChecked(g_StudioApp.getRenderer().IsEditLightEnabled());
    } else {
        m_ui->actionShading_Mode->setEnabled(false);
        m_ui->actionShading_Mode->setChecked(false);
    }
}

void CMainFrame::OnViewGuidesRulers()
{
    g_StudioApp.getRenderer().SetGuidesEnabled(!g_StudioApp.getRenderer().AreGuidesEnabled());
    g_StudioApp.GetCore()->GetDispatch()->FireAuthorZoomChanged();
    m_sceneView->onRulerGuideToggled();
}

void CMainFrame::OnUpdateViewGuidesRulers()
{
    m_ui->actionRulers_Guides->setEnabled(m_sceneView->isDeploymentView());
    m_ui->actionRulers_Guides->setChecked(g_StudioApp.getRenderer().AreGuidesEnabled());
}

void CMainFrame::OnClearGuides()
{
    g_StudioApp.clearGuides();
}

void CMainFrame::OnUpdateClearGuides()
{
    bool enable = g_StudioApp.getRenderer().AreGuidesEnabled()
            && g_StudioApp.getRenderer().AreGuidesEditable() && m_sceneView->isDeploymentView();

    m_ui->actionClear_Guides->setEnabled(enable);
}

void CMainFrame::OnLockGuides()
{
    g_StudioApp.getRenderer().SetGuidesEditable(!g_StudioApp.getRenderer().AreGuidesEditable());
}

void CMainFrame::OnUpdateLockGuides()
{
    bool enable = g_StudioApp.getRenderer().AreGuidesEnabled() && m_sceneView->isDeploymentView();
    m_ui->actionLock_Guides->setEnabled(enable);
    // Set to the inverse of guides editable.
    m_ui->actionLock_Guides->setChecked(!g_StudioApp.getRenderer().AreGuidesEditable());
}

void CMainFrame::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == WM_STUDIO_TIMER)
        g_StudioApp.getTickTock().ProcessMessages();
    QMainWindow::timerEvent(event);
}

void CMainFrame::onViewResetLayout()
{
    // Ask for a restart
    int theChoice = QMessageBox::question(this,
                                          tr("Restart Needed"),
                                          tr("Are you sure that you want to restore Qt 3D Studio "
                                             "layout? \nYour current layout will be lost, and "
                                             "Studio will restart."));

    // If "Yes" is clicked, delete window geometry and window state keys from QSettings
    if (theChoice == QMessageBox::Yes) {
        QSettings settings;
        QString geoKey = QStringLiteral("mainWindowGeometry") + QString::number(STUDIO_VERSION_NUM);
        QString stateKey = QStringLiteral("mainWindowState") + QString::number(STUDIO_VERSION_NUM);
        settings.remove(geoKey);
        settings.remove(stateKey);
        // Prevent saving geometry and state, and exit
        m_resettingLayout = true;
        QTimer::singleShot(0, this, &CMainFrame::handleRestart);
    }
}

void CMainFrame::OnViewAction()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_ACTION);
}

void CMainFrame::OnUpdateViewAction()
{
    m_ui->actionAction->setChecked(
                m_paletteManager->IsControlVisible(CPaletteManager::CONTROLTYPE_ACTION));
}

void CMainFrame::OnViewBasicObjects()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_BASICOBJECTS);
}

void CMainFrame::OnUpdateViewBasicObjects()
{
    m_ui->actionBasic_Objects->setChecked(m_paletteManager->IsControlVisible(
                                              CPaletteManager::CONTROLTYPE_BASICOBJECTS));
}

void CMainFrame::OnViewInspector()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_INSPECTOR);
}

void CMainFrame::OnUpdateViewInspector()
{
    m_ui->actionInspector->setChecked(
                m_paletteManager->IsControlVisible(CPaletteManager::CONTROLTYPE_INSPECTOR));
}

void CMainFrame::OnViewProject()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_PROJECT);
}

void CMainFrame::OnUpdateViewProject()
{
    m_ui->actionProject->setChecked(
                m_paletteManager->IsControlVisible(CPaletteManager::CONTROLTYPE_PROJECT));
}

void CMainFrame::OnViewSlide()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_SLIDE);
}

void CMainFrame::OnUpdateViewSlide()
{
    m_ui->actionSlide->setChecked(
                m_paletteManager->IsControlVisible(CPaletteManager::CONTROLTYPE_SLIDE)
                ? TRUE : FALSE);
}

//==============================================================================
/**
 *	Called when the View Inspector Palette menu item is chosen.
 */
void CMainFrame::OnViewTimeline()
{
    m_paletteManager->ToggleControl(CPaletteManager::CONTROLTYPE_TIMELINE);
}

//==============================================================================
/**
 *	Checks or unchecks the menu item depending on if the view is available or not.
 *	@param pCmdUI Pointer to the UI element that generated the message.
 */
void CMainFrame::OnUpdateViewTimeline()
{
    m_ui->actionTimeline->setChecked(
                m_paletteManager->IsControlVisible(CPaletteManager::CONTROLTYPE_TIMELINE));
}

//==============================================================================
/**
 *	Called when the View Inspector Palette menu item is chosen.
 */
void CMainFrame::OnViewBoundingBoxes()
{
    CStudioPreferences::SetBoundingBoxesOn(!CStudioPreferences::IsBoundingBoxesOn());
    g_StudioApp.getRenderer().RequestRender();
}

//==============================================================================
/**
 *	Checks or unchecks the menu item depending on if the view is available or not.
 *	@param pCmdUI Pointer to the UI element that generated the message.
 */
void CMainFrame::OnUpdateViewBoundingBoxes()
{
    m_ui->actionBounding_Boxes->setChecked(CStudioPreferences::IsBoundingBoxesOn());
}

//==============================================================================
/**
 *	Called when the View Pivot Point menu item is chosen.
 */
void CMainFrame::OnViewPivotPoint()
{
    CStudioPreferences::SetDisplayPivotPoint(!CStudioPreferences::ShouldDisplayPivotPoint());
    g_StudioApp.getRenderer().RequestRender();
}

//==============================================================================
/**
 *	Checks or unchecks the menu item depending on if the view is available or not.
 *	@param pCmdUI Pointer to the UI element that generated the message.
 */
void CMainFrame::OnUpdateViewPivotPoint()
{
    m_ui->actionPivot_Point->setChecked(CStudioPreferences::ShouldDisplayPivotPoint());
}

//==============================================================================
/**
 *	Called when the View Wireframe menu item is chosen.
 */
void CMainFrame::OnViewWireframe()
{
    CStudioPreferences::SetWireframeModeOn(!CStudioPreferences::IsWireframeModeOn());

    // Don't wait for regular update cycle to update the corresponding toolbar/menu checked status
    m_ui->actionWireframe->setChecked(CStudioPreferences::IsWireframeModeOn());

    g_StudioApp.getRenderer().RequestRender();
}

//==============================================================================
/**
 *	Checks or unchecks the menu item depending on if the view is available or not.
 *	@param pCmdUI Pointer to the UI element that generated the message.
 */
void CMainFrame::OnUpdateViewWireframe()
{
    m_ui->actionWireframe->setChecked(CStudioPreferences::IsWireframeModeOn());
}

//==============================================================================
/**
 *	Checks or unchecks the menu item depending whether tooltips should be shown
 *	or not.
 *	@param inCmdUI Pointer to the UI element that generated the message.
 */
void CMainFrame::OnUpdateViewTooltips()
{
    m_ui->actionTooltips->setChecked(CStudioPreferences::ShouldShowTooltips());
}

//==============================================================================
/**
 *	Called when the "View->Tooltips" menu item is chosen.  Toggles tooltips on
 *	and off for custom controls.
 */
void CMainFrame::OnViewTooltips()
{
    CStudioPreferences::SetShowTooltips(!CStudioPreferences::ShouldShowTooltips());
}

//==============================================================================
/**
 *	Called when the update message occurs for the Help->Help Topics menu item.
 *	If the help file exists, the menu item is enabled, otherwise it's disabled.
 *	@param inCmdUI UI element that generated the message
 */
void CMainFrame::OnUpdateHelpIndex()
{
    QFile theFile(g_StudioApp.m_pszHelpFilePath.toQString());
    m_ui->action_Reference_Manual->setEnabled(theFile.exists());
}

//==============================================================================
/**
 *	Handles the ID_HELP_INDEX command.  Opens the online help for Studio.
 */
void CMainFrame::OnHelpIndex()
{
    QFile theFile(g_StudioApp.m_pszHelpFilePath.toQString());
    if (theFile.exists())
        QDesktopServices::openUrl(QUrl::fromLocalFile(theFile.fileName()));
}

//==============================================================================
/**
 *	Handles the ID_HELP_VISIT_QT command.  Opens the Qt Web site.
 */
void CMainFrame::OnHelpVisitQt()
{
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://www.qt.io/3d-studio")));
}

//==============================================================================
/**
 *  Opens the tutorial.
 */
void CMainFrame::OnHelpOpenTutorial()
{
    StudioTutorialWidget tutorial(this, false, false);
    tutorial.exec();
}

//==============================================================================
/**
 * Handle the file revert menu option.
 */
void CMainFrame::OnFileRevert()
{
    g_StudioApp.OnRevert();
}

void CMainFrame::OnFileImportAssets()
{
    m_paletteManager->projectView()->assetImportAction(0);
}

void CMainFrame::OnFileConnectToDevice()
{
    if (m_remoteDeploymentSender->isConnected()) {
        g_StudioApp.GetCore()->GetDispatch()->FireOnProgressBegin(
                    Q3DStudio::CString::fromQString(
                        QObject::tr("Disconnecting from remote device...")), "");
        m_remoteDeploymentSender->disconnect();
    } else {
        QPair<QString, int> info = m_remoteDeploymentSender->initConnection();
        if (!info.first.isEmpty()) {
            g_StudioApp.GetCore()->GetDispatch()->FireOnProgressBegin(
                        Q3DStudio::CString::fromQString(
                            QObject::tr("Connecting to remote device...")), "");
            m_remoteDeploymentSender->connect(info);
        } else {
            m_ui->action_Connect_to_Device->setChecked(false);
        }
    }
}

//==============================================================================
/**
 * Handles the recent list.
 */
void CMainFrame::OnFileOpenRecent(int nID)
{
    g_StudioApp.OnFileOpenRecent(m_recentItems->GetItem(nID));
}

//==============================================================================
/**
 *	Tells the scene view to recheck its sizing mode and tells client to update
 */
void CMainFrame::RecheckSizingMode()
{
    m_sceneView->recheckSizingMode();
}

//==============================================================================
/**
 * Callback when a Core is opened or fails to open.
 */
void CMainFrame::OnOpenDocument(const Qt3DSFile &inFilename, bool inSucceeded)
{
    if (inSucceeded)
        m_recentItems->AddRecentItem(inFilename);
    else
        m_recentItems->RemoveRecentItem(inFilename);
}

//==============================================================================
/**
 * Callback when a Core is saved or fails to save.
 */
void CMainFrame::OnSaveDocument(const Qt3DSFile &inFilename, bool inSucceeded, bool inSaveCopy)
{
    if (!inSaveCopy)
        OnOpenDocument(inFilename, inSucceeded);
}

//==============================================================================
/**
 * Callback for when a the doc gets a new path
 */
void CMainFrame::OnDocumentPathChanged(const Qt3DSFile &inNewPath)
{
    QString theTitle = inNewPath.GetName().toQString();
    if (theTitle.isEmpty())
        theTitle = QObject::tr("Untitled");

    theTitle = theTitle + " - " + QObject::tr("Qt 3D Studio");

    // TODO: Move this whole pile to the studio app
    setWindowTitle(theTitle);

    if (inNewPath.Exists())
        m_recentItems->AddRecentItem(inNewPath);
}

void CMainFrame::OnShowSlide()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_SLIDE);
}

void CMainFrame::OnShowTimeline()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_TIMELINE);
}

void CMainFrame::OnShowBasic()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_BASICOBJECTS);
}

void CMainFrame::OnShowProject()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_PROJECT);
}

void CMainFrame::OnShowAction()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_ACTION);
}

void CMainFrame::OnShowInspector()
{
    m_paletteManager->ShowControl(CPaletteManager::CONTROLTYPE_INSPECTOR);
}

void CMainFrame::OnConnectionChanged(bool connected)
{
    g_StudioApp.GetCore()->GetDispatch()->FireOnProgressEnd();
    m_ui->action_Connect_to_Device->setChecked(connected);
    m_ui->actionRemote_Preview->setEnabled(connected);
}

TimelineWidget *CMainFrame::getTimelineWidget() const
{
    WidgetControl *control = static_cast<WidgetControl *>
            (m_paletteManager->GetControl(CPaletteManager::CONTROLTYPE_TIMELINE)->widget());
    return static_cast<TimelineWidget *>(control->getControl());
}

CRecentItems *CMainFrame::GetRecentItems()
{
    return m_recentItems.data();
}

QWidget *CMainFrame::GetActiveView()
{
    return centralWidget();
}

CPlayerWnd *CMainFrame::GetPlayerWnd() const
{
    return m_sceneView->getPlayerWnd();
}

bool CMainFrame::eventFilter(QObject *obj, QEvent *event)
{
    switch (event->type()) {
    case QEvent::ToolTip: {
        if (CStudioPreferences::ShouldShowTooltips())
            event->ignore();
        else
            return true;
        break;
    }
    case QEvent::KeyPress: {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_Tab) {
            if (m_paletteManager->tabNavigateFocusedWidget(true))
                return true;
        } else if (ke->key() == Qt::Key_Backtab) {
            if (m_paletteManager->tabNavigateFocusedWidget(false))
                return true;
        }
        break;
    }
    default:
        break;
    }
    return QMainWindow::eventFilter(obj, event);
}

void CMainFrame::handleGeometryAndState(bool save)
{
    if (m_resettingLayout)
        return;

    QSettings settings;
    QString geoKey = QStringLiteral("mainWindowGeometry") + QString::number(STUDIO_VERSION_NUM);
    QString stateKey = QStringLiteral("mainWindowState") + QString::number(STUDIO_VERSION_NUM);
    if (save) {
        settings.setValue(geoKey, saveGeometry());
        settings.setValue(stateKey, saveState(STUDIO_VERSION_NUM));
    } else {
        restoreGeometry(settings.value(geoKey).toByteArray());
        restoreState(settings.value(stateKey).toByteArray(), STUDIO_VERSION_NUM);
    }
}

void CMainFrame::handleRestart()
{
    QStringList presentationFile = QStringList(g_StudioApp.GetCore()->GetDoc()
                                               ->GetDocumentPath().GetAbsolutePath().toQString());
    close();
    QProcess::startDetached(qApp->arguments()[0], presentationFile);
}

void CMainFrame::initializeGeometryAndState()
{
    QSettings settings;
    QString stateKey = QStringLiteral("mainWindowState") + QString::number(STUDIO_VERSION_NUM);
    if (!settings.contains(stateKey)) {
        // On first run, save and restore geometry and state. For some reason they are both needed
        // to avoid a bug with palettes resizing to their original size when window is resized or
        // something in a palette is edited.
        handleGeometryAndState(true);
    }
    handleGeometryAndState(false);
}

void CMainFrame::toggleSelectMode()
{
    if (m_ui->actionItem_Select_Tool->isChecked())
        m_sceneView->onToolGroupSelection();
    else
        m_sceneView->onToolItemSelection();
}

void CMainFrame::onActionActive(bool active)
{
    m_actionActive = active;
    m_ui->actionDelete->setEnabled(!active);
    m_ui->action_Copy->setEnabled(!active);
    m_ui->action_Cut->setEnabled(!active);
    m_ui->action_Paste->setEnabled(!active);
}

void CMainFrame::showScene()
{
    if (!m_sceneView.data()->isVisible()) {
        setCentralWidget(m_sceneView.data());
        m_sceneView.data()->setVisible(true);
    }
}

void CMainFrame::onSlideActive(bool active)
{
    m_slideActive = active;
}