aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Gtk3/UI/MainWindow.cs
blob: b10dfe3f9e6ed9f0108577ff79f4cec51adc0aad (plain) (blame)
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
using Gtk;
using LibHac.Common;
using LibHac.Common.Keys;
using LibHac.Ncm;
using LibHac.Ns;
using LibHac.Tools.FsSystem;
using LibHac.Tools.FsSystem.NcaUtils;
using Ryujinx.Audio.Backends.Dummy;
using Ryujinx.Audio.Backends.OpenAL;
using Ryujinx.Audio.Backends.SDL2;
using Ryujinx.Audio.Backends.SoundIo;
using Ryujinx.Audio.Integration;
using Ryujinx.Common;
using Ryujinx.Common.Configuration;
using Ryujinx.Common.Configuration.Multiplayer;
using Ryujinx.Common.Logging;
using Ryujinx.Common.SystemInterop;
using Ryujinx.Cpu;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.GAL.Multithreading;
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.HOS;
using Ryujinx.HLE.HOS.Services.Account.Acc;
using Ryujinx.HLE.HOS.SystemState;
using Ryujinx.Input.GTK3;
using Ryujinx.Input.HLE;
using Ryujinx.Input.SDL2;
using Ryujinx.Modules;
using Ryujinx.UI.App.Common;
using Ryujinx.UI.Applet;
using Ryujinx.UI.Common;
using Ryujinx.UI.Common.Configuration;
using Ryujinx.UI.Common.Helper;
using Ryujinx.UI.Helper;
using Ryujinx.UI.Widgets;
using Ryujinx.UI.Windows;
using Silk.NET.Vulkan;
using SPB.Graphics.Vulkan;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GUI = Gtk.Builder.ObjectAttribute;
using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState;

namespace Ryujinx.UI
{
    public class MainWindow : Window
    {
        private readonly VirtualFileSystem _virtualFileSystem;
        private readonly ContentManager _contentManager;
        private readonly AccountManager _accountManager;
        private readonly LibHacHorizonManager _libHacHorizonManager;

        private UserChannelPersistence _userChannelPersistence;

        private HLE.Switch _emulationContext;

        private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;

        private readonly GtkHostUIHandler _uiHandler;
        private readonly AutoResetEvent _deviceExitStatus;
        private readonly ListStore _tableStore;

        private bool _updatingGameTable;
        private bool _gameLoaded;
        private bool _ending;

        private ApplicationData _currentApplicationData = null;

        private string _lastScannedAmiiboId = "";
        private bool _lastScannedAmiiboShowAll = false;

        public readonly ApplicationLibrary ApplicationLibrary;
        public RendererWidgetBase RendererWidget;
        public InputManager InputManager;

        public bool IsFocused;

#pragma warning disable CS0169, CS0649, IDE0044, IDE0051 // Field is never assigned to, Add readonly modifier, Remove unused private member

        [GUI] public MenuItem ExitMenuItem;
        [GUI] public MenuItem UpdateMenuItem;
        [GUI] MenuBar _menuBar;
        [GUI] Box _footerBox;
        [GUI] Box _statusBar;
        [GUI] MenuItem _optionMenu;
        [GUI] MenuItem _manageUserProfiles;
        [GUI] MenuItem _fileMenu;
        [GUI] MenuItem _loadApplicationFile;
        [GUI] MenuItem _loadApplicationFolder;
        [GUI] MenuItem _appletMenu;
        [GUI] MenuItem _actionMenu;
        [GUI] MenuItem _pauseEmulation;
        [GUI] MenuItem _resumeEmulation;
        [GUI] MenuItem _stopEmulation;
        [GUI] MenuItem _simulateWakeUpMessage;
        [GUI] MenuItem _scanAmiibo;
        [GUI] MenuItem _takeScreenshot;
        [GUI] MenuItem _hideUI;
        [GUI] MenuItem _fullScreen;
        [GUI] CheckMenuItem _startFullScreen;
        [GUI] CheckMenuItem _showConsole;
        [GUI] CheckMenuItem _favToggle;
        [GUI] MenuItem _firmwareInstallDirectory;
        [GUI] MenuItem _firmwareInstallFile;
        [GUI] MenuItem _fileTypesSubMenu;
        [GUI] Label _fifoStatus;
        [GUI] CheckMenuItem _iconToggle;
        [GUI] CheckMenuItem _developerToggle;
        [GUI] CheckMenuItem _appToggle;
        [GUI] CheckMenuItem _timePlayedToggle;
        [GUI] CheckMenuItem _versionToggle;
        [GUI] CheckMenuItem _lastPlayedToggle;
        [GUI] CheckMenuItem _fileExtToggle;
        [GUI] CheckMenuItem _pathToggle;
        [GUI] CheckMenuItem _fileSizeToggle;
        [GUI] CheckMenuItem _nspShown;
        [GUI] CheckMenuItem _pfs0Shown;
        [GUI] CheckMenuItem _xciShown;
        [GUI] CheckMenuItem _ncaShown;
        [GUI] CheckMenuItem _nroShown;
        [GUI] CheckMenuItem _nsoShown;
        [GUI] Label _gpuBackend;
        [GUI] Label _dockedMode;
        [GUI] Label _aspectRatio;
        [GUI] Label _gameStatus;
        [GUI] TreeView _gameTable;
        [GUI] TreeSelection _gameTableSelection;
        [GUI] ScrolledWindow _gameTableWindow;
        [GUI] Label _gpuName;
        [GUI] Label _progressLabel;
        [GUI] Label _firmwareVersionLabel;
        [GUI] Gtk.ProgressBar _progressBar;
        [GUI] Box _viewBox;
        [GUI] Label _vSyncStatus;
        [GUI] Label _volumeStatus;
        [GUI] Box _listStatusBox;
        [GUI] Label _loadingStatusLabel;
        [GUI] Gtk.ProgressBar _loadingStatusBar;

#pragma warning restore CS0649, IDE0044, CS0169, IDE0051

        public MainWindow() : this(new Builder("Ryujinx.Gtk3.UI.MainWindow.glade")) { }

        private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("_mainWin"))
        {
            builder.Autoconnect(this);

            // Apply custom theme if needed.
            ThemeHelper.ApplyTheme();

            SetWindowSizePosition();

            Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.UI.Common.Resources.Logo_Ryujinx.png");
            Title = $"Ryujinx {Program.Version}";

            // Hide emulation context status bar.
            _statusBar.Hide();

            // Instantiate HLE objects.
            _virtualFileSystem = VirtualFileSystem.CreateInstance();
            _libHacHorizonManager = new LibHacHorizonManager();

            _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
            _libHacHorizonManager.InitializeArpServer();
            _libHacHorizonManager.InitializeBcatServer();
            _libHacHorizonManager.InitializeSystemClients();

            // Save data created before we supported extra data in directory save data will not work properly if
            // given empty extra data. Luckily some of that extra data can be created using the data from the
            // save data indexer, which should be enough to check access permissions for user saves.
            // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
            // Consider removing this at some point in the future when we don't need to worry about old saves.
            VirtualFileSystem.FixExtraData(_libHacHorizonManager.RyujinxClient);

            _contentManager = new ContentManager(_virtualFileSystem);
            _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient, CommandLineState.Profile);
            _userChannelPersistence = new UserChannelPersistence();

            IntegrityCheckLevel checkLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks
                ? IntegrityCheckLevel.ErrorOnInvalid
                : IntegrityCheckLevel.None;

            // Instantiate GUI objects.
            ApplicationLibrary = new ApplicationLibrary(_virtualFileSystem, checkLevel)
            {
                DesiredLanguage = ConfigurationState.Instance.System.Language,
            };
            _uiHandler = new GtkHostUIHandler(this);
            _deviceExitStatus = new AutoResetEvent(false);

            WindowStateEvent += WindowStateEvent_Changed;
            DeleteEvent += Window_Close;
            FocusInEvent += MainWindow_FocusInEvent;
            FocusOutEvent += MainWindow_FocusOutEvent;

            ApplicationLibrary.ApplicationAdded += Application_Added;
            ApplicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;

            _fileMenu.StateChanged += FileMenu_StateChanged;
            _actionMenu.StateChanged += ActionMenu_StateChanged;
            _optionMenu.StateChanged += OptionMenu_StateChanged;

            _gameTable.ButtonReleaseEvent += Row_Clicked;
            _fullScreen.Activated += FullScreen_Toggled;

            RendererWidgetBase.StatusUpdatedEvent += Update_StatusBar;

            ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
            ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
            ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
            ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;

            ConfigurationState.Instance.Multiplayer.Mode.Event += UpdateMultiplayerMode;
            ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateMultiplayerLanInterfaceId;

            if (ConfigurationState.Instance.UI.StartFullscreen)
            {
                _startFullScreen.Active = true;
            }

            _showConsole.Active = ConfigurationState.Instance.UI.ShowConsole.Value;
            _showConsole.Visible = ConsoleHelper.SetConsoleWindowStateSupported;

            _actionMenu.Sensitive = false;
            _pauseEmulation.Sensitive = false;
            _resumeEmulation.Sensitive = false;

            _nspShown.Active = ConfigurationState.Instance.UI.ShownFileTypes.NSP.Value;
            _pfs0Shown.Active = ConfigurationState.Instance.UI.ShownFileTypes.PFS0.Value;
            _xciShown.Active = ConfigurationState.Instance.UI.ShownFileTypes.XCI.Value;
            _ncaShown.Active = ConfigurationState.Instance.UI.ShownFileTypes.NCA.Value;
            _nroShown.Active = ConfigurationState.Instance.UI.ShownFileTypes.NRO.Value;
            _nsoShown.Active = ConfigurationState.Instance.UI.ShownFileTypes.NSO.Value;

            _nspShown.Toggled += NSP_Shown_Toggled;
            _pfs0Shown.Toggled += PFS0_Shown_Toggled;
            _xciShown.Toggled += XCI_Shown_Toggled;
            _ncaShown.Toggled += NCA_Shown_Toggled;
            _nroShown.Toggled += NRO_Shown_Toggled;
            _nsoShown.Toggled += NSO_Shown_Toggled;

            _fileTypesSubMenu.Visible = FileAssociationHelper.IsTypeAssociationSupported;

            if (ConfigurationState.Instance.UI.GuiColumns.FavColumn)
            {
                _favToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.IconColumn)
            {
                _iconToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.AppColumn)
            {
                _appToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.DevColumn)
            {
                _developerToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.VersionColumn)
            {
                _versionToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.TimePlayedColumn)
            {
                _timePlayedToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.LastPlayedColumn)
            {
                _lastPlayedToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.FileExtColumn)
            {
                _fileExtToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.FileSizeColumn)
            {
                _fileSizeToggle.Active = true;
            }
            if (ConfigurationState.Instance.UI.GuiColumns.PathColumn)
            {
                _pathToggle.Active = true;
            }

            _favToggle.Toggled += Fav_Toggled;
            _iconToggle.Toggled += Icon_Toggled;
            _appToggle.Toggled += App_Toggled;
            _developerToggle.Toggled += Developer_Toggled;
            _versionToggle.Toggled += Version_Toggled;
            _timePlayedToggle.Toggled += TimePlayed_Toggled;
            _lastPlayedToggle.Toggled += LastPlayed_Toggled;
            _fileExtToggle.Toggled += FileExt_Toggled;
            _fileSizeToggle.Toggled += FileSize_Toggled;
            _pathToggle.Toggled += Path_Toggled;

            _gameTable.Model = _tableStore = new ListStore(
                typeof(bool),
                typeof(Gdk.Pixbuf),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(string),
                typeof(BlitStruct<ApplicationControlProperty>));

            _tableStore.SetSortFunc(5, SortHelper.TimePlayedSort);
            _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort);
            _tableStore.SetSortFunc(8, SortHelper.FileSizeSort);

            int columnId = ConfigurationState.Instance.UI.ColumnSort.SortColumnId;
            bool ascending = ConfigurationState.Instance.UI.ColumnSort.SortAscending;

            _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending);

            _gameTable.EnableSearch = true;
            _gameTable.SearchColumn = 2;
            _gameTable.SearchEqualFunc = (model, col, key, iter) => !((string)model.GetValue(iter, col)).Contains(key, StringComparison.InvariantCultureIgnoreCase);

            _hideUI.Label = _hideUI.Label.Replace("SHOWUIKEY", ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI.ToString());

            UpdateColumns();

            ConfigurationState.Instance.UI.GameDirs.Event += (sender, args) =>
            {
                if (args.OldValue != args.NewValue)
                {
                    UpdateGameTable();
                }
            };

            Task.Run(RefreshFirmwareLabel);

            InputManager = new InputManager(new GTK3KeyboardDriver(this), new SDL2GamepadDriver());
        }

        private void UpdateMultiplayerLanInterfaceId(object sender, ReactiveEventArgs<string> args)
        {
            if (_emulationContext != null)
            {
                _emulationContext.Configuration.MultiplayerLanInterfaceId = args.NewValue;
            }
        }

        private void UpdateMultiplayerMode(object sender, ReactiveEventArgs<MultiplayerMode> args)
        {
            if (_emulationContext != null)
            {
                _emulationContext.Configuration.MultiplayerMode = args.NewValue;
            }
        }

        private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
        {
            if (_emulationContext != null)
            {
                _emulationContext.Configuration.IgnoreMissingServices = args.NewValue;
            }
        }

        private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
        {
            if (_emulationContext != null)
            {
                _emulationContext.Configuration.AspectRatio = args.NewValue;
            }
        }

        private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
        {
            _emulationContext?.System.ChangeDockedModeState(e.NewValue);
        }

        private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
        {
            _emulationContext?.SetVolume(e.NewValue);
        }

        private void WindowStateEvent_Changed(object o, WindowStateEventArgs args)
        {
            _fullScreen.Label = args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen) ? "Exit Fullscreen" : "Enter Fullscreen";
        }

        private void MainWindow_FocusOutEvent(object o, FocusOutEventArgs args)
        {
            IsFocused = false;
        }

        private void MainWindow_FocusInEvent(object o, FocusInEventArgs args)
        {
            IsFocused = true;
        }

        private void UpdateColumns()
        {
            foreach (TreeViewColumn column in _gameTable.Columns)
            {
                _gameTable.RemoveColumn(column);
            }

            CellRendererToggle favToggle = new();
            favToggle.Toggled += FavToggle_Toggled;

            if (ConfigurationState.Instance.UI.GuiColumns.FavColumn)
            {
                _gameTable.AppendColumn("Fav", favToggle, "active", 0);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.IconColumn)
            {
                _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.AppColumn)
            {
                _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.DevColumn)
            {
                _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.VersionColumn)
            {
                _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.TimePlayedColumn)
            {
                _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.LastPlayedColumn)
            {
                _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.FileExtColumn)
            {
                _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.FileSizeColumn)
            {
                _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
            }
            if (ConfigurationState.Instance.UI.GuiColumns.PathColumn)
            {
                _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
            }

            foreach (TreeViewColumn column in _gameTable.Columns)
            {
                switch (column.Title)
                {
                    case "Fav":
                        column.SortColumnId = 0;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Application":
                        column.SortColumnId = 2;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Developer":
                        column.SortColumnId = 3;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Version":
                        column.SortColumnId = 4;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Time Played":
                        column.SortColumnId = 5;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Last Played":
                        column.SortColumnId = 6;
                        column.Clicked += Column_Clicked;
                        break;
                    case "File Ext":
                        column.SortColumnId = 7;
                        column.Clicked += Column_Clicked;
                        break;
                    case "File Size":
                        column.SortColumnId = 8;
                        column.Clicked += Column_Clicked;
                        break;
                    case "Path":
                        column.SortColumnId = 9;
                        column.Clicked += Column_Clicked;
                        break;
                }
            }
        }

        protected override void OnDestroyed()
        {
            InputManager.Dispose();
        }

        private void InitializeSwitchInstance()
        {
            _virtualFileSystem.ReloadKeySet();

            IRenderer renderer;

            if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
            {
                string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value;
                renderer = new Graphics.Vulkan.VulkanRenderer(Vk.GetApi(), CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu);
            }
            else
            {
                renderer = new Graphics.OpenGL.OpenGLRenderer();
            }

            BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;

            bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);

            if (threadedGAL)
            {
                renderer = new ThreadedRenderer(renderer);
            }

            Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {threadedGAL}");

            IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();

            if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
            {
                if (SDL2HardwareDeviceDriver.IsSupported)
                {
                    deviceDriver = new SDL2HardwareDeviceDriver();
                }
                else
                {
                    Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");

                    if (OpenALHardwareDeviceDriver.IsSupported)
                    {
                        Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");

                        ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
                        SaveConfig();

                        deviceDriver = new OpenALHardwareDeviceDriver();
                    }
                    else
                    {
                        Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");

                        if (SoundIoHardwareDeviceDriver.IsSupported)
                        {
                            Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");

                            ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
                            SaveConfig();

                            deviceDriver = new SoundIoHardwareDeviceDriver();
                        }
                        else
                        {
                            Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
                        }
                    }
                }
            }
            else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
            {
                if (SoundIoHardwareDeviceDriver.IsSupported)
                {
                    deviceDriver = new SoundIoHardwareDeviceDriver();
                }
                else
                {
                    Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, trying to fall back to SDL2.");

                    if (SDL2HardwareDeviceDriver.IsSupported)
                    {
                        Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");

                        ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
                        SaveConfig();

                        deviceDriver = new SDL2HardwareDeviceDriver();
                    }
                    else
                    {
                        Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");

                        if (OpenALHardwareDeviceDriver.IsSupported)
                        {
                            Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");

                            ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
                            SaveConfig();

                            deviceDriver = new OpenALHardwareDeviceDriver();
                        }
                        else
                        {
                            Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, falling back to dummy audio out.");
                        }
                    }
                }
            }
            else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
            {
                if (OpenALHardwareDeviceDriver.IsSupported)
                {
                    deviceDriver = new OpenALHardwareDeviceDriver();
                }
                else
                {
                    Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SDL2.");

                    if (SDL2HardwareDeviceDriver.IsSupported)
                    {
                        Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");

                        ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
                        SaveConfig();

                        deviceDriver = new SDL2HardwareDeviceDriver();
                    }
                    else
                    {
                        Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to SoundIO.");

                        if (SoundIoHardwareDeviceDriver.IsSupported)
                        {
                            Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");

                            ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
                            SaveConfig();

                            deviceDriver = new SoundIoHardwareDeviceDriver();
                        }
                        else
                        {
                            Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
                        }
                    }
                }
            }

            var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value
                ? HLE.MemoryConfiguration.MemoryConfiguration8GiB
                : HLE.MemoryConfiguration.MemoryConfiguration4GiB;

            IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;

            HLE.HLEConfiguration configuration = new(_virtualFileSystem,
                _libHacHorizonManager,
                _contentManager,
                _accountManager,
                _userChannelPersistence,
                renderer,
                deviceDriver,
                memoryConfiguration,
                _uiHandler,
                (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
                (RegionCode)ConfigurationState.Instance.System.Region.Value,
                ConfigurationState.Instance.Graphics.EnableVsync,
                ConfigurationState.Instance.System.EnableDockedMode,
                ConfigurationState.Instance.System.EnablePtc,
                ConfigurationState.Instance.System.EnableInternetAccess,
                fsIntegrityCheckLevel,
                ConfigurationState.Instance.System.FsGlobalAccessLogMode,
                ConfigurationState.Instance.System.SystemTimeOffset,
                ConfigurationState.Instance.System.TimeZone,
                ConfigurationState.Instance.System.MemoryManagerMode,
                ConfigurationState.Instance.System.IgnoreMissingServices,
                ConfigurationState.Instance.Graphics.AspectRatio,
                ConfigurationState.Instance.System.AudioVolume,
                ConfigurationState.Instance.System.UseHypervisor,
                ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value,
                ConfigurationState.Instance.Multiplayer.Mode);

            _emulationContext = new HLE.Switch(configuration);
        }

        private SurfaceKHR CreateVulkanSurface(Instance instance, Vk vk)
        {
            return new SurfaceKHR((ulong)((VulkanRenderer)RendererWidget).CreateWindowSurface(instance.Handle));
        }

        private void SetupProgressUIHandlers()
        {
            if (_emulationContext.Processes.ActiveApplication.DiskCacheLoadState != null)
            {
                _emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged -= ProgressHandler;
                _emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged += ProgressHandler;
            }

            _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
            _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
        }

        private void ProgressHandler<T>(T state, int current, int total) where T : Enum
        {
            bool visible;
            string label;

            switch (state)
            {
                case LoadState ptcState:
                    visible = ptcState != LoadState.Loaded;
                    label = $"PTC : {current}/{total}";
                    break;
                case ShaderCacheLoadingState shaderCacheState:
                    visible = shaderCacheState != ShaderCacheLoadingState.Loaded;
                    label = $"Shaders : {current}/{total}";
                    break;
                default:
                    throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
            }

            Application.Invoke(delegate
            {
                _loadingStatusLabel.Text = label;
                _loadingStatusBar.Fraction = total > 0 ? (double)current / total : 0;
                _loadingStatusBar.Visible = visible;
                _loadingStatusLabel.Visible = visible;
            });
        }

        public void UpdateGameTable()
        {
            if (_updatingGameTable || _gameLoaded)
            {
                return;
            }

            _updatingGameTable = true;

            _tableStore.Clear();

            Thread applicationLibraryThread = new(() =>
            {
                ApplicationLibrary.DesiredLanguage = ConfigurationState.Instance.System.Language;
                ApplicationLibrary.LoadApplications(ConfigurationState.Instance.UI.GameDirs);

                _updatingGameTable = false;
            })
            {
                Name = "GUI.ApplicationLibraryThread",
                IsBackground = true,
            };
            applicationLibraryThread.Start();
        }

        [Conditional("RELEASE")]
        public void PerformanceCheck()
        {
            if (ConfigurationState.Instance.Logger.EnableTrace.Value)
            {
                MessageDialog debugWarningDialog = new(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                {
                    Title = "Ryujinx - Warning",
                    Text = "You have trace logging enabled, which is designed to be used by developers only.",
                    SecondaryText = "For optimal performance, it's recommended to disable trace logging. Would you like to disable trace logging now?",
                };

                if (debugWarningDialog.Run() == (int)ResponseType.Yes)
                {
                    ConfigurationState.Instance.Logger.EnableTrace.Value = false;
                    SaveConfig();
                }

                debugWarningDialog.Dispose();
            }

            if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
            {
                MessageDialog shadersDumpWarningDialog = new(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                {
                    Title = "Ryujinx - Warning",
                    Text = "You have shader dumping enabled, which is designed to be used by developers only.",
                    SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?",
                };

                if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
                {
                    ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
                    SaveConfig();
                }

                shadersDumpWarningDialog.Dispose();
            }
        }

        private bool LoadApplication(string path, ulong applicationId, bool isFirmwareTitle)
        {
            SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();

            if (!SetupValidator.CanStartApplication(_contentManager, path, out UserError userError))
            {
                if (SetupValidator.CanFixStartApplication(_contentManager, path, userError, out firmwareVersion))
                {
                    string message = $"Would you like to install the firmware embedded in this game? (Firmware {firmwareVersion.VersionString})";

                    ResponseType responseDialog = (ResponseType)GtkDialog.CreateConfirmationDialog("No Firmware Installed", message).Run();

                    if (responseDialog != ResponseType.Yes || !SetupValidator.TryFixStartApplication(_contentManager, path, userError, out _))
                    {
                        UserErrorDialog.CreateUserErrorDialog(userError);

                        return false;
                    }

                    // Tell the user that we installed a firmware for them.

                    firmwareVersion = _contentManager.GetCurrentFirmwareVersion();

                    RefreshFirmwareLabel();

                    message = $"No installed firmware was found but Ryujinx was able to install firmware {firmwareVersion.VersionString} from the provided game.\nThe emulator will now start.";

                    GtkDialog.CreateInfoDialog($"Firmware {firmwareVersion.VersionString} was installed", message);
                }
                else
                {
                    UserErrorDialog.CreateUserErrorDialog(userError);

                    return false;
                }
            }

            Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");

            if (isFirmwareTitle)
            {
                Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");

                return _emulationContext.LoadNca(path);
            }

            if (Directory.Exists(path))
            {
                string[] romFsFiles = Directory.GetFiles(path, "*.istorage");

                if (romFsFiles.Length == 0)
                {
                    romFsFiles = Directory.GetFiles(path, "*.romfs");
                }

                if (romFsFiles.Length > 0)
                {
                    Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");

                    return _emulationContext.LoadCart(path, romFsFiles[0]);
                }

                Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");

                return _emulationContext.LoadCart(path);
            }

            if (File.Exists(path))
            {
                switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
                {
                    case ".xci":
                        Logger.Info?.Print(LogClass.Application, "Loading as XCI.");

                        return _emulationContext.LoadXci(path, applicationId);
                    case ".nca":
                        Logger.Info?.Print(LogClass.Application, "Loading as NCA.");

                        return _emulationContext.LoadNca(path);
                    case ".nsp":
                    case ".pfs0":
                        Logger.Info?.Print(LogClass.Application, "Loading as NSP.");

                        return _emulationContext.LoadNsp(path, applicationId);
                    default:
                        Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
                        try
                        {
                            return _emulationContext.LoadProgram(path);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");

                            return false;
                        }
                }
            }

            Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");

            return false;
        }

        public void RunApplication(ApplicationData application, bool startFullscreen = false)
        {
            if (_gameLoaded)
            {
                GtkDialog.CreateInfoDialog("A game has already been loaded", "Please stop emulation or close the emulator before launching another game.");
            }
            else
            {
                PerformanceCheck();

                Logger.RestartTime();

                RendererWidget = CreateRendererWidget();

                SwitchToRenderWidget(startFullscreen);

                InitializeSwitchInstance();

                UpdateGraphicsConfig();

                bool isFirmwareTitle = false;

                if (application.Path.StartsWith("@SystemContent"))
                {
                    application.Path = VirtualFileSystem.SwitchPathToSystemPath(application.Path);

                    isFirmwareTitle = true;
                }

                if (!LoadApplication(application.Path, application.Id, isFirmwareTitle))
                {
                    _emulationContext.Dispose();
                    SwitchToGameTable();

                    return;
                }

                SetupProgressUIHandlers();

                _currentApplicationData = application;

                _deviceExitStatus.Reset();

                Thread windowThread = new(CreateGameWindow)
                {
                    Name = "GUI.WindowThread",
                };

                windowThread.Start();

                _gameLoaded = true;
                _actionMenu.Sensitive = true;
                UpdateMenuItem.Sensitive = false;

                _lastScannedAmiiboId = "";

                _firmwareInstallFile.Sensitive = false;
                _firmwareInstallDirectory.Sensitive = false;

                DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Processes.ActiveApplication.ProgramIdText,
                                                              _emulationContext.Processes.ActiveApplication.ApplicationControlProperties.Title[(int)_emulationContext.System.State.DesiredTitleLanguage].NameString.ToString());

                ApplicationLibrary.LoadAndSaveMetaData(_emulationContext.Processes.ActiveApplication.ProgramIdText, appMetadata =>
                {
                    appMetadata.UpdatePreGame();
                });
            }
        }

        private RendererWidgetBase CreateRendererWidget()
        {
            if (ConfigurationState.Instance.Graphics.GraphicsBackend == GraphicsBackend.Vulkan)
            {
                return new VulkanRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
            }
            else
            {
                return new OpenGLRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
            }
        }

        private void SwitchToRenderWidget(bool startFullscreen = false)
        {
            _viewBox.Remove(_gameTableWindow);
            RendererWidget.Expand = true;
            _viewBox.Child = RendererWidget;

            RendererWidget.ShowAll();
            EditFooterForGameRenderer();

            if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
            {
                ToggleExtraWidgets(false);
            }
            else if (startFullscreen || ConfigurationState.Instance.UI.StartFullscreen.Value)
            {
                FullScreen_Toggled(null, null);
            }
        }

        private void SwitchToGameTable()
        {
            if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
            {
                ToggleExtraWidgets(true);
            }

            RendererWidget.Exit();

            if (RendererWidget.Window != Window && RendererWidget.Window != null)
            {
                RendererWidget.Window.Dispose();
            }

            RendererWidget.Dispose();

            if (OperatingSystem.IsWindows())
            {
                _windowsMultimediaTimerResolution?.Dispose();
                _windowsMultimediaTimerResolution = null;
            }

            DisplaySleep.Restore();

            _viewBox.Remove(RendererWidget);
            _viewBox.Add(_gameTableWindow);

            _gameTableWindow.Expand = true;

            Window.Title = $"Ryujinx {Program.Version}";

            _emulationContext = null;
            _gameLoaded = false;
            RendererWidget = null;

            DiscordIntegrationModule.SwitchToMainMenu();

            RecreateFooterForMenu();

            UpdateColumns();
            UpdateGameTable();

            RefreshFirmwareLabel();
            HandleRelaunch();
        }

        private void CreateGameWindow()
        {
            if (OperatingSystem.IsWindows())
            {
                _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
            }

            DisplaySleep.Prevent();

            RendererWidget.Initialize(_emulationContext);

            RendererWidget.WaitEvent.WaitOne();

            RendererWidget.Start();

            _emulationContext.Dispose();
            _deviceExitStatus.Set();

            // NOTE: Everything that is here will not be executed when you close the UI.
            Application.Invoke(delegate
            {
                SwitchToGameTable();
            });
        }

        private void RecreateFooterForMenu()
        {
            _listStatusBox.Show();
            _statusBar.Hide();
        }

        private void EditFooterForGameRenderer()
        {
            _listStatusBox.Hide();
            _statusBar.Show();
        }

        public void ToggleExtraWidgets(bool show)
        {
            if (RendererWidget != null)
            {
                if (show)
                {
                    _menuBar.ShowAll();
                    _footerBox.Show();
                    _statusBar.Show();
                }
                else
                {
                    _menuBar.Hide();
                    _footerBox.Hide();
                }
            }
        }

        private void UpdateGameMetadata(string titleId)
        {
            if (_gameLoaded)
            {
                ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
                {
                    appMetadata.UpdatePostGame();
                });
            }
        }

        public static void UpdateGraphicsConfig()
        {
            int resScale = ConfigurationState.Instance.Graphics.ResScale;
            float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;

            Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
            Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
            Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
            Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
            Graphics.Gpu.GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression;
            Graphics.Gpu.GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE;
        }

        public void UpdateInternetAccess()
        {
            if (_gameLoaded)
            {
                _emulationContext.Configuration.EnableInternetAccess = ConfigurationState.Instance.System.EnableInternetAccess.Value;
            }
        }

        public static void SaveConfig()
        {
            ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
        }

        private void End()
        {
            if (_ending)
            {
                return;
            }

            _ending = true;

            if (_emulationContext != null)
            {
                UpdateGameMetadata(_emulationContext.Processes.ActiveApplication.ProgramIdText);

                if (RendererWidget != null)
                {
                    // We tell the widget that we are exiting.
                    RendererWidget.Exit();

                    // Wait for the other thread to dispose the HLE context before exiting.
                    _deviceExitStatus.WaitOne();
                    RendererWidget.Dispose();
                }
            }

            Dispose();

            Program.Exit();
            Application.Quit();
        }

        //
        // Events
        //
        private void Application_Added(object sender, ApplicationAddedEventArgs args)
        {
            Application.Invoke(delegate
            {
                _tableStore.AppendValues(
                    args.AppData.Favorite,
                    new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
                    $"{args.AppData.Name}\n{args.AppData.IdString.ToUpper()}",
                    args.AppData.Developer,
                    args.AppData.Version,
                    args.AppData.TimePlayedString,
                    args.AppData.LastPlayedString,
                    args.AppData.FileExtension,
                    args.AppData.FileSizeString,
                    args.AppData.Path,
                    args.AppData.ControlHolder);
            });
        }

        private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
        {
            Application.Invoke(delegate
            {
                _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
                float barValue = 0;

                if (args.NumAppsFound != 0)
                {
                    barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
                }

                _progressBar.Fraction = barValue;

                // Reset the vertical scrollbar to the top when titles finish loading
                if (args.NumAppsLoaded == args.NumAppsFound)
                {
                    _gameTableWindow.Vadjustment.Value = 0;
                }
            });
        }

        private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
        {
            Application.Invoke(delegate
            {
                _gameStatus.Text = args.GameStatus;
                _fifoStatus.Text = args.FifoStatus;
                _gpuName.Text = args.GpuName;
                _dockedMode.Text = args.DockedMode;
                _aspectRatio.Text = args.AspectRatio;
                _gpuBackend.Text = args.GpuBackend;
                _volumeStatus.Text = GetVolumeLabelText(args.Volume);

                if (args.VSyncEnabled)
                {
                    _vSyncStatus.Attributes = new Pango.AttrList();
                    _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
                }
                else
                {
                    _vSyncStatus.Attributes = new Pango.AttrList();
                    _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
                }
            });
        }

        private void FavToggle_Toggled(object sender, ToggledArgs args)
        {
            _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));

            string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
            bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);

            _tableStore.SetValue(treeIter, 0, newToggleValue);

            ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
            {
                appMetadata.Favorite = newToggleValue;
            });
        }

        private void Column_Clicked(object sender, EventArgs args)
        {
            TreeViewColumn column = (TreeViewColumn)sender;

            ConfigurationState.Instance.UI.ColumnSort.SortColumnId.Value = column.SortColumnId;
            ConfigurationState.Instance.UI.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;

            SaveConfig();
        }

        private void Row_Activated(object sender, RowActivatedArgs args)
        {
            _gameTableSelection.GetSelected(out TreeIter treeIter);

            ApplicationData application = new()
            {
                Favorite = (bool)_tableStore.GetValue(treeIter, 0),
                Name = ((string)_tableStore.GetValue(treeIter, 2)).Split('\n')[0],
                Id = ulong.Parse(((string)_tableStore.GetValue(treeIter, 2)).Split('\n')[1], NumberStyles.HexNumber),
                Developer = (string)_tableStore.GetValue(treeIter, 3),
                Version = (string)_tableStore.GetValue(treeIter, 4),
                TimePlayed = ValueFormatUtils.ParseTimeSpan((string)_tableStore.GetValue(treeIter, 5)),
                LastPlayed = ValueFormatUtils.ParseDateTime((string)_tableStore.GetValue(treeIter, 6)),
                FileExtension = (string)_tableStore.GetValue(treeIter, 7),
                FileSize = ValueFormatUtils.ParseFileSize((string)_tableStore.GetValue(treeIter, 8)),
                Path = (string)_tableStore.GetValue(treeIter, 9),
                ControlHolder = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10),
            };

            RunApplication(application);
        }

        private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
        {
            _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;

            Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {_emulationContext.EnableDeviceVsync}");
        }

        private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
        {
            ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
        }

        private static string GetVolumeLabelText(float volume)
        {
            string icon = volume == 0 ? "🔇" : "🔊";

            return $"{icon} {(int)(volume * 100)}%";
        }

        private void VolumeStatus_Clicked(object sender, ButtonReleaseEventArgs args)
        {
            if (_emulationContext != null)
            {
                if (_emulationContext.IsAudioMuted())
                {
                    _emulationContext.SetVolume(ConfigurationState.Instance.System.AudioVolume);
                }
                else
                {
                    _emulationContext.SetVolume(0);
                }
            }
        }

        private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
        {
            AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;

            ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames<AspectRatio>().Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
        }

        private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
        {
            if (args.Event.Button != 3 /* Right Click */)
            {
                return;
            }

            _gameTableSelection.GetSelected(out TreeIter treeIter);

            if (treeIter.UserData == IntPtr.Zero)
            {
                return;
            }

            ApplicationData application = new()
            {
                Favorite = (bool)_tableStore.GetValue(treeIter, 0),
                Name = ((string)_tableStore.GetValue(treeIter, 2)).Split('\n')[0],
                Id = ulong.Parse(((string)_tableStore.GetValue(treeIter, 2)).Split('\n')[1], NumberStyles.HexNumber),
                Developer = (string)_tableStore.GetValue(treeIter, 3),
                Version = (string)_tableStore.GetValue(treeIter, 4),
                TimePlayed = ValueFormatUtils.ParseTimeSpan((string)_tableStore.GetValue(treeIter, 5)),
                LastPlayed = ValueFormatUtils.ParseDateTime((string)_tableStore.GetValue(treeIter, 6)),
                FileExtension = (string)_tableStore.GetValue(treeIter, 7),
                FileSize = ValueFormatUtils.ParseFileSize((string)_tableStore.GetValue(treeIter, 8)),
                Path = (string)_tableStore.GetValue(treeIter, 9),
                ControlHolder = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10),
            };

            _ = new GameTableContextMenu(this, _virtualFileSystem, _accountManager, _libHacHorizonManager.RyujinxClient, application);
        }

        private void Load_Application_File(object sender, EventArgs args)
        {
            using FileChooserNative fileChooser = new("Choose the file to open", this, FileChooserAction.Open, "Open", "Cancel");

            FileFilter filter = new()
            {
                Name = "Switch Executables",
            };
            filter.AddPattern("*.xci");
            filter.AddPattern("*.nsp");
            filter.AddPattern("*.pfs0");
            filter.AddPattern("*.nca");
            filter.AddPattern("*.nro");
            filter.AddPattern("*.nso");

            fileChooser.AddFilter(filter);

            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                if (ApplicationLibrary.TryGetApplicationsFromFile(fileChooser.Filename,
                        out List<ApplicationData> applications))
                {
                    RunApplication(applications[0]);
                }
                else
                {
                    GtkDialog.CreateErrorDialog("No applications found in selected file.");
                }
            }
        }

        private void Load_Application_Folder(object sender, EventArgs args)
        {
            using FileChooserNative fileChooser = new("Choose the folder to open", this, FileChooserAction.SelectFolder, "Open", "Cancel");

            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                ApplicationData applicationData = new()
                {
                    Name = System.IO.Path.GetFileNameWithoutExtension(fileChooser.Filename),
                    Path = fileChooser.Filename,
                };

                RunApplication(applicationData);
            }
        }

        private void FileMenu_StateChanged(object o, StateChangedArgs args)
        {
            _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3;
            _loadApplicationFile.Sensitive = _emulationContext == null;
            _loadApplicationFolder.Sensitive = _emulationContext == null;
        }

        private void Load_Mii_Edit_Applet(object sender, EventArgs args)
        {
            string contentPath = _contentManager.GetInstalledContentPath(0x0100000000001009, StorageId.BuiltInSystem, NcaContentType.Program);

            ApplicationData applicationData = new()
            {
                Name = "miiEdit",
                Id = 0x0100000000001009ul,
                Path = contentPath,
            };

            RunApplication(applicationData);
        }

        private void Open_Ryu_Folder(object sender, EventArgs args)
        {
            OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
        }

        private void OpenLogsFolder_Pressed(object sender, EventArgs args)
        {
            string logPath = AppDataManager.GetOrCreateLogsDir();
            if (!string.IsNullOrEmpty(logPath))
            {
                OpenHelper.OpenFolder(logPath);
            }
        }

        private void Exit_Pressed(object sender, EventArgs args)
        {
            if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
            {
                SaveWindowSizePosition();
                End();
            }
        }

        private void Window_Close(object sender, DeleteEventArgs args)
        {
            if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
            {
                SaveWindowSizePosition();
                End();
            }
            else
            {
                args.RetVal = true;
            }
        }

        private void SetWindowSizePosition()
        {
            DefaultWidth = ConfigurationState.Instance.UI.WindowStartup.WindowSizeWidth;
            DefaultHeight = ConfigurationState.Instance.UI.WindowStartup.WindowSizeHeight;

            Move(ConfigurationState.Instance.UI.WindowStartup.WindowPositionX, ConfigurationState.Instance.UI.WindowStartup.WindowPositionY);

            if (ConfigurationState.Instance.UI.WindowStartup.WindowMaximized)
            {
                Maximize();
            }
        }

        private void SaveWindowSizePosition()
        {
            GetSize(out int windowWidth, out int windowHeight);
            GetPosition(out int windowXPos, out int windowYPos);

            ConfigurationState.Instance.UI.WindowStartup.WindowMaximized.Value = IsMaximized;
            ConfigurationState.Instance.UI.WindowStartup.WindowSizeWidth.Value = windowWidth;
            ConfigurationState.Instance.UI.WindowStartup.WindowSizeHeight.Value = windowHeight;
            ConfigurationState.Instance.UI.WindowStartup.WindowPositionX.Value = windowXPos;
            ConfigurationState.Instance.UI.WindowStartup.WindowPositionY.Value = windowYPos;

            SaveConfig();
        }

        private void StopEmulation_Pressed(object sender, EventArgs args)
        {
            if (_emulationContext != null)
            {
                UpdateGameMetadata(_emulationContext.Processes.ActiveApplication.ProgramIdText);
            }

            _pauseEmulation.Sensitive = false;
            _resumeEmulation.Sensitive = false;
            UpdateMenuItem.Sensitive = true;
            RendererWidget?.Exit();
        }

        private void PauseEmulation_Pressed(object sender, EventArgs args)
        {
            _pauseEmulation.Sensitive = false;
            _resumeEmulation.Sensitive = true;
            _emulationContext.System.TogglePauseEmulation(true);
            Title = TitleHelper.ActiveApplicationTitle(_emulationContext.Processes.ActiveApplication, Program.Version, "Paused");
            Logger.Info?.Print(LogClass.Emulation, "Emulation was paused");
        }

        private void ResumeEmulation_Pressed(object sender, EventArgs args)
        {
            _pauseEmulation.Sensitive = true;
            _resumeEmulation.Sensitive = false;
            _emulationContext.System.TogglePauseEmulation(false);
            Title = TitleHelper.ActiveApplicationTitle(_emulationContext.Processes.ActiveApplication, Program.Version);
            Logger.Info?.Print(LogClass.Emulation, "Emulation was resumed");
        }

        public void ActivatePauseMenu()
        {
            _pauseEmulation.Sensitive = true;
            _resumeEmulation.Sensitive = false;
        }

        public void TogglePause()
        {
            _pauseEmulation.Sensitive ^= true;
            _resumeEmulation.Sensitive ^= true;
            _emulationContext.System.TogglePauseEmulation(_resumeEmulation.Sensitive);
        }

        private void Installer_File_Pressed(object o, EventArgs args)
        {
            FileChooserNative fileChooser = new("Choose the firmware file to open", this, FileChooserAction.Open, "Open", "Cancel");

            FileFilter filter = new()
            {
                Name = "Switch Firmware Files",
            };
            filter.AddPattern("*.zip");
            filter.AddPattern("*.xci");

            fileChooser.AddFilter(filter);

            HandleInstallerDialog(fileChooser);
        }

        private void Installer_Directory_Pressed(object o, EventArgs args)
        {
            FileChooserNative directoryChooser = new("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Open", "Cancel");

            HandleInstallerDialog(directoryChooser);
        }

        private void HandleInstallerDialog(FileChooserNative fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    if (firmwareVersion is null)
                    {
                        GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");

                        return;
                    }

                    string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";

                    SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "\n\nDo you want to continue?";

                    ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();

                    MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");

                    if (responseInstallDialog == ResponseType.Yes)
                    {
                        Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new(() =>
                        {
                            Application.Invoke(delegate
                            {
                                waitingDialog.Run();

                            });

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    string message = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    GtkDialog.CreateInfoDialog(dialogTitle, message);
                                    Logger.Info?.Print(LogClass.Application, message);

                                    // Purge Applet Cache.

                                    DirectoryInfo miiEditorCacheFolder = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));

                                    if (miiEditorCacheFolder.Exists)
                                    {
                                        miiEditorCacheFolder.Delete(true);
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    GtkDialog.CreateErrorDialog(ex.Message);
                                });
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        })
                        {
                            Name = "GUI.FirmwareInstallerThread",
                        };
                        thread.Start();
                    }
                }
                catch (MissingKeyException ex)
                {
                    Logger.Error?.Print(LogClass.Application, ex.ToString());
                    UserErrorDialog.CreateUserErrorDialog(UserError.FirmwareParsingFailed);
                }
                catch (Exception ex)
                {
                    GtkDialog.CreateErrorDialog(ex.Message);
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }

        private void RefreshFirmwareLabel()
        {
            SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();

            Application.Invoke(delegate
            {
                _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
            });
        }

        private void InstallFileTypes_Pressed(object sender, EventArgs e)
        {
            if (FileAssociationHelper.Install())
            {
                GtkDialog.CreateInfoDialog("Install file types", "File types successfully installed!");
            }
            else
            {
                GtkDialog.CreateErrorDialog("Failed to install file types.");
            }
        }

        private void UninstallFileTypes_Pressed(object sender, EventArgs e)
        {
            if (FileAssociationHelper.Uninstall())
            {
                GtkDialog.CreateInfoDialog("Uninstall file types", "File types successfully uninstalled!");
            }
            else
            {
                GtkDialog.CreateErrorDialog("Failed to uninstall file types.");
            }
        }

        private void HandleRelaunch()
        {
            if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
            {
                _userChannelPersistence.ShouldRestart = false;

                RunApplication(_currentApplicationData);
            }
            else
            {
                // otherwise, clear state.
                _userChannelPersistence = new UserChannelPersistence();
                _currentApplicationData = null;
                _actionMenu.Sensitive = false;
                _firmwareInstallFile.Sensitive = true;
                _firmwareInstallDirectory.Sensitive = true;
            }
        }

        private void FullScreen_Toggled(object sender, EventArgs args)
        {
            if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
            {
                Fullscreen();

                ToggleExtraWidgets(false);
            }
            else
            {
                Unfullscreen();

                ToggleExtraWidgets(true);
            }
        }

        private void StartFullScreen_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.StartFullscreen.Value = _startFullScreen.Active;

            SaveConfig();
        }

        private void ShowConsole_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShowConsole.Value = _showConsole.Active;

            SaveConfig();
        }

        private void OptionMenu_StateChanged(object o, StateChangedArgs args)
        {
            _manageUserProfiles.Sensitive = _emulationContext == null;
        }

        private void Settings_Pressed(object sender, EventArgs args)
        {
            SettingsWindow settingsWindow = new(this, _virtualFileSystem, _contentManager);

            settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor));
            settingsWindow.Show();
        }

        private void HideUI_Pressed(object sender, EventArgs args)
        {
            ToggleExtraWidgets(false);
        }

        private void ManageCheats_Pressed(object sender, EventArgs args)
        {
            var window = new CheatWindow(
                _virtualFileSystem,
                _emulationContext.Processes.ActiveApplication.ProgramId,
                _emulationContext.Processes.ActiveApplication.ApplicationControlProperties
                    .Title[(int)_emulationContext.System.State.DesiredTitleLanguage].NameString.ToString(),
                _currentApplicationData.Path);

            window.Destroyed += CheatWindow_Destroyed;
            window.Show();
        }

        private void CheatWindow_Destroyed(object sender, EventArgs e)
        {
            _emulationContext.EnableCheats();
            (sender as CheatWindow).Destroyed -= CheatWindow_Destroyed;
        }

        private void ManageUserProfiles_Pressed(object sender, EventArgs args)
        {
            UserProfilesManagerWindow userProfilesManagerWindow = new(_accountManager, _contentManager, _virtualFileSystem);

            userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor));
            userProfilesManagerWindow.Show();
        }

        private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
        {
            _emulationContext?.System.SimulateWakeUpMessage();
        }

        private void ActionMenu_StateChanged(object o, StateChangedArgs args)
        {
            _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _);
            _takeScreenshot.Sensitive = _emulationContext != null;
        }

        private void Scan_Amiibo(object sender, EventArgs args)
        {
            if (_emulationContext.System.SearchingForAmiibo(out int deviceId))
            {
                AmiiboWindow amiiboWindow = new()
                {
                    LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll,
                    LastScannedAmiiboId = _lastScannedAmiiboId,
                    DeviceId = deviceId,
                    TitleId = _emulationContext.Processes.ActiveApplication.ProgramIdText.ToUpper(),
                };

                amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent;

                amiiboWindow.Show();
            }
            else
            {
                GtkDialog.CreateInfoDialog($"Amiibo", "The game is currently not ready to receive Amiibo scan data. Ensure that you have an Amiibo-compatible game open and ready to receive Amiibo scan data.");
            }
        }

        private void Take_Screenshot(object sender, EventArgs args)
        {
            if (_emulationContext != null && RendererWidget != null)
            {
                RendererWidget.ScreenshotRequested = true;
            }
        }

        private void AmiiboWindow_DeleteEvent(object sender, DeleteEventArgs args)
        {
            if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok)
            {
                _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId;
                _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll;

                _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid);
            }
        }

        private void Update_Pressed(object sender, EventArgs args)
        {
            if (Updater.CanUpdate(true))
            {
                Updater.BeginParse(this, true).ContinueWith(task =>
                {
                    Logger.Error?.Print(LogClass.Application, $"Updater error: {task.Exception}");
                }, TaskContinuationOptions.OnlyOnFaulted);
            }
        }

        private void About_Pressed(object sender, EventArgs args)
        {
            AboutWindow aboutWindow = new();

            aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor));
            aboutWindow.Show();
        }

        private void Fav_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.FavColumn.Value = _favToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void Icon_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.IconColumn.Value = _iconToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void App_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.AppColumn.Value = _appToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void Developer_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.DevColumn.Value = _developerToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void Version_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.VersionColumn.Value = _versionToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void TimePlayed_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void LastPlayed_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void FileExt_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void FileSize_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void Path_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.GuiColumns.PathColumn.Value = _pathToggle.Active;

            SaveConfig();
            UpdateColumns();
        }

        private void NSP_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.NSP.Value = _nspShown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void PFS0_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.PFS0.Value = _pfs0Shown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void XCI_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.XCI.Value = _xciShown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void NCA_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.NCA.Value = _ncaShown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void NRO_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.NRO.Value = _nroShown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void NSO_Shown_Toggled(object sender, EventArgs args)
        {
            ConfigurationState.Instance.UI.ShownFileTypes.NSO.Value = _nsoShown.Active;

            SaveConfig();
            UpdateGameTable();
        }

        private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
        {
            UpdateGameTable();
        }
    }
}