-
Notifications
You must be signed in to change notification settings - Fork 380
/
MainForm.cs
4871 lines (4227 loc) · 148 KB
/
MainForm.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO.Pipes;
using BizHawk.Common;
using BizHawk.Common.BufferExtensions;
using BizHawk.Common.PathExtensions;
using BizHawk.Common.StringExtensions;
using BizHawk.Client.Common;
using BizHawk.Bizware.BizwareGL;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.Base_Implementations;
using BizHawk.Emulation.Cores;
using BizHawk.Emulation.Cores.Arcades.MAME;
using BizHawk.Emulation.Cores.Calculators.TI83;
using BizHawk.Emulation.Cores.Computers.AppleII;
using BizHawk.Emulation.Cores.Computers.Commodore64;
using BizHawk.Emulation.Cores.Consoles.NEC.PCE;
using BizHawk.Emulation.Cores.Consoles.Nintendo.Ares64;
using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES;
using BizHawk.Emulation.Cores.Consoles.SNK;
using BizHawk.Emulation.Cores.Nintendo.BSNES;
using BizHawk.Emulation.Cores.Nintendo.Gameboy;
using BizHawk.Emulation.Cores.Nintendo.GBA;
using BizHawk.Emulation.Cores.Nintendo.N64;
using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Cores.Nintendo.Sameboy;
using BizHawk.Emulation.Cores.Nintendo.SNES;
using BizHawk.Emulation.Cores.Nintendo.SNES9X;
using BizHawk.Emulation.Cores.Sony.PSX;
using BizHawk.Client.EmuHawk.ToolExtensions;
using BizHawk.Client.EmuHawk.CoreExtensions;
using BizHawk.Client.EmuHawk.CustomControls;
using BizHawk.Common.CollectionExtensions;
using BizHawk.WinForms.Controls;
namespace BizHawk.Client.EmuHawk
{
public partial class MainForm : FormBase, IDialogParent, IMainFormForApi, IMainFormForTools, IMainFormForRetroAchievements
{
private static readonly FilesystemFilterSet EmuHawkSaveStatesFSFilterSet = new(FilesystemFilter.EmuHawkSaveStates);
private static readonly FilesystemFilterSet LibretroCoresFSFilterSet = new(new FilesystemFilter("Libretro Cores", new[] { OSTailoredCode.IsUnixHost ? "so" : "dll" }))
{
AppendAllFilesEntry = false,
};
private void MainForm_Load(object sender, EventArgs e)
{
UpdateWindowTitle();
foreach (var (groupLabel, appliesTo, coreNames) in Config.CorePickerUIData.Select(static tuple => (GroupLabel: tuple.AppliesTo[0], tuple.AppliesTo, tuple.CoreNames))
.OrderBy(static tuple => tuple.GroupLabel))
{
var submenu = new ToolStripMenuItem { Text = groupLabel };
void ClickHandler(object clickSender, EventArgs clickArgs)
{
var coreName = ((ToolStripMenuItem) clickSender).Text;
foreach (var system in appliesTo)
{
if (Emulator.SystemId == system && Emulator.Attributes().CoreName != coreName) FlagNeedsReboot();
Config.PreferredCores[system] = coreName;
}
}
submenu.DropDownItems.AddRange(coreNames.Select(coreName => {
var entry = new ToolStripMenuItem { Text = coreName };
entry.Click += ClickHandler;
return (ToolStripItem) entry;
}).ToArray());
submenu.DropDownOpened += (openedSender, _) =>
{
Config.PreferredCores.TryGetValue(groupLabel, out var preferred);
foreach (ToolStripMenuItem entry in ((ToolStripMenuItem) openedSender).DropDownItems) entry.Checked = entry.Text == preferred;
};
CoresSubMenu.DropDownItems.Add(submenu);
}
CoresSubMenu.DropDownItems.Add(new ToolStripSeparator { AutoSize = true });
var GBInSGBMenuItem = new ToolStripMenuItem { Text = "GB in SGB" };
GBInSGBMenuItem.Click += (_, _) =>
{
Config.GbAsSgb ^= true;
if (Emulator.SystemId is VSystemID.Raw.GB or VSystemID.Raw.GBC or VSystemID.Raw.SGB) FlagNeedsReboot();
};
CoresSubMenu.DropDownItems.Add(GBInSGBMenuItem);
var setLibretroCoreToolStripMenuItem = new ToolStripMenuItem { Text = "Set Libretro Core..." };
setLibretroCoreToolStripMenuItem.Click += (_, _) => RunLibretroCoreChooser();
CoresSubMenu.DropDownItems.Add(setLibretroCoreToolStripMenuItem);
CoresSubMenu.DropDownOpened += (_, _) => GBInSGBMenuItem.Checked = Config.GbAsSgb;
ToolStripMenuItemEx recentCoreSettingsSubmenu = new() { Text = "Recent" };
recentCoreSettingsSubmenu.DropDownItems.AddRange(CreateCoreSettingsSubmenus().ToArray());
ToolStripMenuItemEx noRecentsItem = new() { Enabled = false, Text = "(N/A)" };
recentCoreSettingsSubmenu.DropDownItems.Add(noRecentsItem);
recentCoreSettingsSubmenu.DropDownOpening += (_, _) =>
{
foreach (ToolStripItem submenu in recentCoreSettingsSubmenu.DropDownItems) submenu.Visible = Config.RecentCores.Contains(submenu.Text);
noRecentsItem.Visible = Config.RecentCores.Count is 0;
};
ToolStripMenuItemEx consolesCoreSettingsSubmenu = new() { Text = "For Consoles" };
ToolStripMenuItemEx handheldsCoreSettingsSubmenu = new() { Text = "For Handhelds" };
ToolStripMenuItemEx pcsCoreSettingsSubmenu = new() { Text = "For PCs" };
ToolStripMenuItemEx otherCoreSettingsSubmenu = new() { Text = "Other" };
foreach (var submenu in CreateCoreSettingsSubmenus(includeDupes: true).OrderBy(submenu => submenu.Text))
{
var parentMenu = (VSystemCategory) submenu.Tag switch
{
VSystemCategory.Consoles => consolesCoreSettingsSubmenu,
VSystemCategory.Handhelds => handheldsCoreSettingsSubmenu,
VSystemCategory.PCs => pcsCoreSettingsSubmenu,
_ => otherCoreSettingsSubmenu
};
parentMenu.DropDownItems.Add(submenu);
}
foreach (var submenu in new[] { consolesCoreSettingsSubmenu, handheldsCoreSettingsSubmenu, pcsCoreSettingsSubmenu, otherCoreSettingsSubmenu })
{
if (submenu.DropDownItems.Count is 0)
{
submenu.DropDownItems.Add(new ToolStripMenuItemEx { Text = "(none)" });
submenu.Enabled = false;
}
}
ConfigSubMenu.DropDownItems.Insert(
ConfigSubMenu.DropDownItems.IndexOf(CoresSubMenu) + 1,
new ToolStripMenuItemEx
{
DropDownItems =
{
recentCoreSettingsSubmenu,
new ToolStripSeparatorEx { AutoSize = true },
consolesCoreSettingsSubmenu,
handheldsCoreSettingsSubmenu,
pcsCoreSettingsSubmenu,
otherCoreSettingsSubmenu,
},
Text = "Core Settings",
});
// Hide Status bar icons and general StatusBar prep
MainStatusBar.Padding = new Padding(MainStatusBar.Padding.Left, MainStatusBar.Padding.Top, MainStatusBar.Padding.Left, MainStatusBar.Padding.Bottom); // Workaround to remove extra padding on right
PlayRecordStatusButton.Visible = false;
AVIStatusLabel.Visible = false;
SetPauseStatusBarIcon();
Tools.UpdateCheatRelatedTools(null, null);
RebootStatusBarIcon.Visible = false;
UpdateNotification.Visible = false;
_statusBarDiskLightOnImage = Properties.Resources.LightOn;
_statusBarDiskLightOffImage = Properties.Resources.LightOff;
_linkCableOn = Properties.Resources.Connect16X16;
_linkCableOff = Properties.Resources.NoConnect16X16;
UpdateCoreStatusBarButton();
if (Config.FirstBoot)
{
ProfileFirstBootLabel.Visible = true;
}
HandleToggleLightAndLink();
SetStatusBar();
_stateSlots.Update(Emulator, MovieSession.Movie, SaveStatePrefix());
// New version notification
UpdateChecker.CheckComplete += (s2, e2) =>
{
if (IsDisposed)
{
return;
}
this.BeginInvoke(() => { UpdateNotification.Visible = UpdateChecker.IsNewVersionAvailable; });
};
UpdateChecker.GlobalConfig = Config;
UpdateChecker.BeginCheck(); // Won't actually check unless enabled by user
// open requested ext. tool
var requestedExtToolDll = _argParser.openExtToolDll;
if (requestedExtToolDll != null)
{
var found = ExtToolManager.ToolStripItems.Where(static item => item.Enabled)
.Select(static item => (ExternalToolManager.MenuItemInfo) item.Tag)
.FirstOrNull(info => info.AsmFilename == requestedExtToolDll
|| Path.GetFileName(info.AsmFilename) == requestedExtToolDll
|| Path.GetFileNameWithoutExtension(info.AsmFilename) == requestedExtToolDll);
if (found is not null) found.Value.TryLoad();
else Console.WriteLine($"requested ext. tool dll {requestedExtToolDll} could not be loaded");
}
#if DEBUG
AddDebugMenu();
#endif
}
static MainForm()
{
// If this isn't here, then our assembly resolving hacks wont work due to the check for MainForm.INTERIM
// its.. weird. don't ask.
}
public CoreComm CreateCoreComm()
{
var cfp = new CoreFileProvider(
this,
FirmwareManager,
Config.PathEntries,
Config.FirmwareUserSpecifications);
var prefs = CoreComm.CorePreferencesFlags.None;
if (Config.SkipWaterboxIntegrityChecks)
prefs = CoreComm.CorePreferencesFlags.WaterboxMemoryConsistencyCheck;
// can't pass self as IDialogParent :(
return new CoreComm(
message => this.ModalMessageBox(message, "Warning", EMsgBoxIcon.Warning),
AddOnScreenMessage,
cfp,
prefs);
}
private void SetImages()
{
OpenRomMenuItem.Image = Properties.Resources.OpenFile;
RecentRomSubMenu.Image = Properties.Resources.Recent;
CloseRomMenuItem.Image = Properties.Resources.Close;
PreviousSlotMenuItem.Image = Properties.Resources.MoveLeft;
NextSlotMenuItem.Image = Properties.Resources.MoveRight;
ReadonlyMenuItem.Image = Properties.Resources.ReadOnly;
RecentMovieSubMenu.Image = Properties.Resources.Recent;
RecordMovieMenuItem.Image = Properties.Resources.Record;
PlayMovieMenuItem.Image = Properties.Resources.Play;
StopMovieMenuItem.Image = Properties.Resources.Stop;
PlayFromBeginningMenuItem.Image = Properties.Resources.Restart;
ImportMoviesMenuItem.Image = Properties.Resources.Import;
SaveMovieMenuItem.Image = Properties.Resources.SaveAs;
SaveMovieAsMenuItem.Image = Properties.Resources.SaveAs;
StopMovieWithoutSavingMenuItem.Image = Properties.Resources.Stop;
RecordAVMenuItem.Image = Properties.Resources.Record;
ConfigAndRecordAVMenuItem.Image = Properties.Resources.Avi;
StopAVIMenuItem.Image = Properties.Resources.Stop;
ScreenshotMenuItem.Image = Properties.Resources.Camera;
PauseMenuItem.Image = Properties.Resources.Pause;
RebootCoreMenuItem.Image = Properties.Resources.Reboot;
SwitchToFullscreenMenuItem.Image = Properties.Resources.Fullscreen;
ControllersMenuItem.Image = Properties.Resources.GameController;
HotkeysMenuItem.Image = Properties.Resources.HotKeys;
DisplayConfigMenuItem.Image = Properties.Resources.TvIcon;
SoundMenuItem.Image = Properties.Resources.Audio;
PathsMenuItem.Image = Properties.Resources.CopyFolder;
FirmwaresMenuItem.Image = Properties.Resources.Pcb;
MessagesMenuItem.Image = Properties.Resources.MessageConfig;
AutofireMenuItem.Image = Properties.Resources.Lightning;
RewindOptionsMenuItem.Image = Properties.Resources.Previous;
ProfilesMenuItem.Image = Properties.Resources.Profile;
SaveConfigMenuItem.Image = Properties.Resources.Save;
LoadConfigMenuItem.Image = Properties.Resources.LoadConfig;
(ToolBoxMenuItem.Image, /*ToolBoxMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(ToolBox)]
= (/*ToolBox.ToolIcon.ToBitmap()*/Properties.Resources.ToolBox, "Tool Box");
(RamWatchMenuItem.Image, /*RamWatchMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(RamWatch)]
= (/*RamWatch.ToolIcon.ToBitmap()*/Properties.Resources.Watch, "RAM Watch");
(RamSearchMenuItem.Image, /*RamSearchMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(RamSearch)]
= (/*RamSearch.ToolIcon.ToBitmap()*/Properties.Resources.Search, "RAM Search");
(LuaConsoleMenuItem.Image, /*LuaConsoleMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(LuaConsole)]
= (/*LuaConsole.ToolIcon.ToBitmap()*/Properties.Resources.TextDoc, "Lua Console");
(TAStudioMenuItem.Image, /*TAStudioMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(TAStudio)]
= (/*TAStudio.ToolIcon.ToBitmap()*/Properties.Resources.TAStudio, "TAStudio");
(HexEditorMenuItem.Image, /*HexEditorMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(HexEditor)]
= (/*HexEditor.ToolIcon.ToBitmap()*/Properties.Resources.Poke, "Hex Editor");
(TraceLoggerMenuItem.Image, /*TraceLoggerMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(TraceLogger)]
= (/*TraceLogger.ToolIcon.ToBitmap()*/Properties.Resources.Pencil, "Trace Logger");
(DebuggerMenuItem.Image, /*DebuggerMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(GenericDebugger)]
= (/*GenericDebugger.ToolIcon.ToBitmap()*/Properties.Resources.Bug, "Debugger");
(CodeDataLoggerMenuItem.Image, /*CodeDataLoggerMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(CDL)]
= (/*CDL.ToolIcon.ToBitmap()*/Properties.Resources.CdLogger, "Code Data Logger");
(VirtualPadMenuItem.Image, /*VirtualPadMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(VirtualpadTool)]
= (/*VirtualpadTool.ToolIcon.ToBitmap()*/Properties.Resources.GameController, "Virtual Pads");
(BasicBotMenuItem.Image, /*BasicBotMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(BasicBot)]
= (/*BasicBot.ToolIcon.ToBitmap()*/Properties.Resources.BasicBotBit, "Basic Bot");
(CheatsMenuItem.Image, /*CheatsMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(Cheats)]
= (/*Cheats.ToolIcon.ToBitmap()*/Properties.Resources.Freeze, "Cheats");
(GameSharkConverterMenuItem.Image, /*GameSharkConverterMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(GameShark)]
= (/*GameShark.ToolIcon.ToBitmap()*/Properties.Resources.Shark, "Cheat Code Converter");
(MultiDiskBundlerFileMenuItem.Image, /*MultiDiskBundlerFileMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(MultiDiskBundler)]
= (/*MultiDiskBundler.ToolIcon.ToBitmap()*/Properties.Resources.SaveConfig, "Multi-disk Bundler");
NesControllerSettingsMenuItem.Image = Properties.Resources.GameController;
NESGraphicSettingsMenuItem.Image = Properties.Resources.TvIcon;
NESSoundChannelsMenuItem.Image = Properties.Resources.Audio;
(KeypadMenuItem.Image, /*KeypadMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(TI83KeyPad)]
= (/*TI83KeyPad.ToolIcon.ToBitmap()*/Properties.Resources.Calculator, "TI-83 Virtual KeyPad");
PSXControllerSettingsMenuItem.Image = Properties.Resources.GameController;
SNESControllerConfigurationMenuItem.Image = Properties.Resources.GameController;
(SnesGfxDebuggerMenuItem.Image, /*SnesGfxDebuggerMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(SNESGraphicsDebugger)]
= (/*SNESGraphicsDebugger.ToolIcon.ToBitmap()*/Properties.Resources.Bug, "Graphics Debugger");
ColecoControllerSettingsMenuItem.Image = Properties.Resources.GameController;
N64PluginSettingsMenuItem.Image = Properties.Resources.Monitor;
N64ControllerSettingsMenuItem.Image = Properties.Resources.GameController;
IntVControllerSettingsMenuItem.Image = Properties.Resources.GameController;
OnlineHelpMenuItem.Image = Properties.Resources.Help;
ForumsMenuItem.Image = Properties.Resources.TAStudio;
(FeaturesMenuItem.Image, /*FeaturesMenuItem.Text*/_) = ToolManager.IconAndNameCache[typeof(CoreFeatureAnalysis)]
= (/*CoreFeatureAnalysis.ToolIcon.ToBitmap()*/Properties.Resources.KitchenSink, "Core Features");
AboutMenuItem.Image = Properties.Resources.CorpHawkSmall;
DumpStatusButton.Image = Properties.Resources.Blank;
PlayRecordStatusButton.Image = Properties.Resources.Blank;
PauseStatusButton.Image = Properties.Resources.Blank;
RebootStatusBarIcon.Image = Properties.Resources.Reboot;
AVIStatusLabel.Image = Properties.Resources.Blank;
LedLightStatusLabel.Image = Properties.Resources.LightOff;
KeyPriorityStatusLabel.Image = Properties.Resources.Both;
CoreNameStatusBarButton.Image = Properties.Resources.CorpHawkSmall;
ProfileFirstBootLabel.Image = Properties.Resources.Profile;
LinkConnectStatusBarButton.Image = Properties.Resources.Connect16X16;
OpenRomContextMenuItem.Image = Properties.Resources.OpenFile;
LoadLastRomContextMenuItem.Image = Properties.Resources.Recent;
StopAVContextMenuItem.Image = Properties.Resources.Stop;
RecordMovieContextMenuItem.Image = Properties.Resources.Record;
PlayMovieContextMenuItem.Image = Properties.Resources.Play;
RestartMovieContextMenuItem.Image = Properties.Resources.Restart;
StopMovieContextMenuItem.Image = Properties.Resources.Stop;
LoadLastMovieContextMenuItem.Image = Properties.Resources.Recent;
StopNoSaveContextMenuItem.Image = Properties.Resources.Stop;
SaveMovieContextMenuItem.Image = Properties.Resources.SaveAs;
SaveMovieAsContextMenuItem.Image = Properties.Resources.SaveAs;
UndoSavestateContextMenuItem.Image = Properties.Resources.Undo;
toolStripMenuItem6.Image = Properties.Resources.GameController;
toolStripMenuItem7.Image = Properties.Resources.HotKeys;
toolStripMenuItem8.Image = Properties.Resources.TvIcon;
toolStripMenuItem9.Image = Properties.Resources.Audio;
toolStripMenuItem10.Image = Properties.Resources.CopyFolder;
toolStripMenuItem11.Image = Properties.Resources.Pcb;
toolStripMenuItem12.Image = Properties.Resources.MessageConfig;
toolStripMenuItem13.Image = Properties.Resources.Lightning;
toolStripMenuItem14.Image = Properties.Resources.Previous;
toolStripMenuItem66.Image = Properties.Resources.Save;
toolStripMenuItem67.Image = Properties.Resources.LoadConfig;
ScreenshotContextMenuItem.Image = Properties.Resources.Camera;
CloseRomContextMenuItem.Image = Properties.Resources.Close;
}
public MainForm(
ParsedCLIFlags cliFlags,
IGL gl,
Func<string> getConfigPath,
Func<Config> getGlobalConfig,
Action<Sound> updateGlobalSound,
string[] args,
out IMovieSession movieSession,
out bool exitEarly)
{
movieSession = null;
exitEarly = false;
_getGlobalConfig = getGlobalConfig;
if (Config.SingleInstanceMode)
{
if (SingleInstanceInit(args))
{
exitEarly = true;
return;
}
}
//do this threaded stuff early so it has plenty of time to run in background
Database.InitializeDatabase(
bundledRoot: Path.Combine(PathUtils.ExeDirectoryPath, "gamedb"),
userRoot: Path.Combine(PathUtils.DataDirectoryPath, "gamedb"),
silent: true);
BootGodDb.Initialize(Path.Combine(PathUtils.ExeDirectoryPath, "gamedb"));
MAMEMachineDB.Initialize(Path.Combine(PathUtils.ExeDirectoryPath, "gamedb"));
_argParser = cliFlags;
_getConfigPath = getConfigPath;
GL = gl;
_updateGlobalSound = updateGlobalSound;
InputManager = new InputManager
{
GetMainFormMouseInfo = () =>
{
var b = Control.MouseButtons;
return (
Control.MousePosition,
MouseWheelTracker,
(b & MouseButtons.Left) != 0,
(b & MouseButtons.Middle) != 0,
(b & MouseButtons.Right) != 0,
(b & MouseButtons.XButton1) != 0,
(b & MouseButtons.XButton2) != 0
);
}
};
FirmwareManager = new FirmwareManager();
movieSession = MovieSession = new MovieSession(
Config.Movies,
Config.PathEntries.MovieBackupsAbsolutePath(),
this,
QuickBmpFile,
PauseEmulator,
SetMainformMovieInfo);
void MainForm_MouseClick(object sender, MouseEventArgs e)
{
AutohideCursor(false);
if (Config.ShowContextMenu && e.Button == MouseButtons.Right)
{
MainFormContextMenu.Show(PointToScreen(new Point(e.X, e.Y + MainformMenu.Height)));
}
}
void MainForm_MouseMove(object sender, MouseEventArgs e) => AutohideCursor(false);
void MainForm_MouseWheel(object sender, MouseEventArgs e) => MouseWheelTracker += e.Delta;
MouseClick += MainForm_MouseClick;
MouseMove += MainForm_MouseMove;
InitializeComponent();
Icon = Properties.Resources.Logo;
SetImages();
#if !DEBUG
ZXSpectrumExportSnapshotMenuItemMenuItem.Enabled = false;
ZXSpectrumExportSnapshotMenuItemMenuItem.Visible = false;
#endif
#if AVI_SUPPORT
SynclessRecordingMenuItem.Click += (_, _) => new SynclessRecordingTools(Config, Game, this).Run();
#else
SynclessRecordingMenuItem.Enabled = false;
#endif
Game = GameInfo.NullInstance;
_throttle = new Throttle();
Emulator = new NullEmulator();
UpdateStatusSlots();
UpdateKeyPriorityIcon();
// TODO GL - a lot of disorganized wiring-up here
// installed separately on Unix (via package manager or from https://developer.nvidia.com/cg-toolkit-download), look in $PATH
_presentationPanel = new PresentationPanel(
Config,
GL,
ToggleFullscreen,
MainForm_MouseClick,
MainForm_MouseMove,
MainForm_MouseWheel)
{
GraphicsControl = { MainWindow = true }
};
DisplayManager = new DisplayManager(Config, Emulator, InputManager, MovieSession, GL, _presentationPanel, () => DisableSecondaryThrottling);
Controls.Add(_presentationPanel);
Controls.SetChildIndex(_presentationPanel, 0);
// set up networking before ApiManager (in ToolManager)
byte[] NetworkingTakeScreenshot()
=> (byte[]) new ImageConverter().ConvertTo(MakeScreenshotImage().ToSysdrawingBitmap(), typeof(byte[]));
NetworkingHelpers = (
_argParser.HTTPAddresses is var (httpGetURL, httpPostURL)
? new HttpCommunication(NetworkingTakeScreenshot, httpGetURL, httpPostURL)
: null,
new MemoryMappedFiles(NetworkingTakeScreenshot, _argParser.MMFFilename),
_argParser.SocketAddress is var (socketIP, socketPort)
? new SocketServer(NetworkingTakeScreenshot, socketIP, socketPort)
: null
);
ExtToolManager = new(
Config,
() => (Emulator.SystemId, Game.Hash),
(toolPath, customFormTypeName, skipExtToolWarning) => Tools!.LoadExternalToolForm(
toolPath: toolPath,
customFormTypeName: customFormTypeName,
skipExtToolWarning: skipExtToolWarning) is not null);
Tools = new ToolManager(this, Config, DisplayManager, ExtToolManager, InputManager, Emulator, MovieSession, Game);
// TODO GL - move these event handlers somewhere less obnoxious line in the On* overrides
Load += (o, e) =>
{
AllowDrop = true;
DragEnter += FormDragEnter;
DragDrop += FormDragDrop;
};
Closing += (o, e) =>
{
if (Tools.AskSave())
{
// zero 03-nov-2015 - close game after other steps. tools might need to unhook themselves from a core.
MovieSession.StopMovie();
Tools.Close();
CloseGame();
SaveConfig();
}
else
{
e.Cancel = true;
}
};
ResizeBegin += (o, e) =>
{
_inResizeLoop = true;
Sound?.StopSound();
};
Resize += (_, _) => UpdateWindowTitle();
ResizeEnd += (o, e) =>
{
_inResizeLoop = false;
UpdateWindowTitle();
if (_presentationPanel != null)
{
_presentationPanel.Resized = true;
}
Sound?.StartSound();
};
Input.Instance = new Input(
Handle,
() => Config,
yieldAlt => ActiveForm switch
{
null => Config.AcceptBackgroundInput // none of our forms are focused, check the background input config
? Config.AcceptBackgroundInputControllerOnly
? AllowInput.OnlyController
: AllowInput.All
: AllowInput.None,
TAStudio when yieldAlt => AllowInput.None,
FormBase { BlocksInputWhenFocused: false } => AllowInput.All,
ControllerConfig => AllowInput.All,
HotkeyConfig => AllowInput.All,
LuaWinform { BlocksInputWhenFocused: false } => AllowInput.All,
_ => AllowInput.None
}
);
InitControls();
InputManager.ResetMainControllers(_autofireNullControls);
InputManager.AutofireStickyXorAdapter.SetOnOffPatternFromConfig(Config.AutofireOn, Config.AutofireOff);
var savedOutputMethod = Config.SoundOutputMethod;
if (savedOutputMethod is ESoundOutputMethod.Dummy) Config.SoundOutputMethod = HostCapabilityDetector.HasDirectX ? ESoundOutputMethod.DirectSound : ESoundOutputMethod.OpenAL;
try
{
Sound = new Sound(Handle, Config, () => Emulator.VsyncRate());
}
catch
{
if (savedOutputMethod is not ESoundOutputMethod.Dummy)
{
ShowMessageBox(
owner: null,
text: savedOutputMethod is ESoundOutputMethod.DirectSound
? "Couldn't initialize DirectSound! Things may go poorly for you. Try changing your sound driver to 44.1khz instead of 48khz in mmsys.cpl."
: "Couldn't initialize sound device! Try changing the output method in Sound config.",
caption: "Initialization Error",
EMsgBoxIcon.Error);
}
Config.SoundOutputMethod = ESoundOutputMethod.Dummy;
Sound = new Sound(Handle, Config, () => Emulator.VsyncRate());
}
Sound.StartSound();
InputManager.SyncControls(Emulator, MovieSession, Config);
CheatList = new CheatCollection(this, Config.Cheats);
CheatList.Changed += Tools.UpdateCheatRelatedTools;
RewireSound();
// Workaround for windows, location is -32000 when minimized, if they close it during this time, that's what gets saved
if (Config.MainWndx == -32000)
{
Config.MainWndx = 0;
}
if (Config.MainWndy == -32000)
{
Config.MainWndy = 0;
}
if (Config.MainWndx != -1 && Config.MainWndy != -1 && Config.SaveWindowPosition)
{
Location = new Point(Config.MainWndx, Config.MainWndy);
}
if (Config.MainFormStayOnTop) TopMost = true;
if (_argParser.cmdRom != null)
{
// Commandline should always override auto-load
var ioa = OpenAdvancedSerializer.ParseWithLegacy(_argParser.cmdRom);
if (ioa is OpenAdvanced_OpenRom oaor) ioa = new OpenAdvanced_OpenRom { Path = oaor.Path.MakeAbsolute() }; // fixes #3224; should this be done for all the IOpenAdvanced types? --yoshi
_ = LoadRom(ioa.SimplePath, new LoadRomArgs { OpenAdvanced = ioa });
if (Game.IsNullInstance())
{
ShowMessageBox(owner: null, $"Failed to load {_argParser.cmdRom} specified on commandline");
}
}
else if (Config.RecentRoms.AutoLoad && !Config.RecentRoms.Empty)
{
LoadMostRecentROM();
}
Config.VideoWriterAudioSyncEffective = _argParser.audiosync ?? Config.VideoWriterAudioSync;
_autoDumpLength = _argParser._autoDumpLength;
if (_argParser.cmdMovie != null)
{
_suppressSyncSettingsWarning = true; // We don't want to be nagged if we are attempting to automate
if (Game.IsNullInstance())
{
OpenRom();
}
// If user picked a game, then do the commandline logic
if (!Game.IsNullInstance())
{
var movie = MovieSession.Get(_argParser.cmdMovie);
MovieSession.ReadOnly = true;
// if user is dumping and didn't supply dump length, make it as long as the loaded movie
if (_autoDumpLength == 0)
{
_autoDumpLength = movie.InputLogLength;
}
// Copy pasta from drag & drop
if (MovieImport.IsValidMovieExtension(Path.GetExtension(_argParser.cmdMovie)))
{
ProcessMovieImport(_argParser.cmdMovie, true);
}
else
{
StartNewMovie(movie, false);
Config.RecentMovies.Add(_argParser.cmdMovie);
}
_suppressSyncSettingsWarning = false;
}
}
else if (Config.RecentMovies.AutoLoad && !Config.RecentMovies.Empty)
{
if (Game.IsNullInstance())
{
OpenRom();
}
// If user picked a game, then do the autoload logic
if (!Game.IsNullInstance())
{
if (File.Exists(Config.RecentMovies.MostRecent))
{
StartNewMovie(MovieSession.Get(Config.RecentMovies.MostRecent), false);
}
else
{
Config.RecentMovies.HandleLoadError(this, Config.RecentMovies.MostRecent);
}
}
}
if (_argParser.startFullscreen || Config.StartFullscreen)
{
_needsFullscreenOnLoad = true;
}
if (!Game.IsNullInstance())
{
if (_argParser.cmdLoadState != null)
{
_ = LoadState(
path: _argParser.cmdLoadState,
userFriendlyStateName: Path.GetFileName(_argParser.cmdLoadState));
}
else if (_argParser.cmdLoadSlot != null)
{
_ = LoadQuickSave(_argParser.cmdLoadSlot.Value);
}
else if (Config.AutoLoadLastSaveSlot)
{
_ = LoadstateCurrentSlot();
}
}
if (_argParser.UserdataUnparsedPairs is {} pairs) foreach (var (k, v) in pairs)
{
MovieSession.UserBag[k] = v switch
{
"true" => true,
"false" => false,
_ when int.TryParse(v, out var i) => i,
_ when double.TryParse(v, out var d) => d,
_ => v
};
}
//start Lua Console if requested in the command line arguments
if (_argParser.luaConsole)
{
Tools.Load<LuaConsole>();
}
//load Lua Script if requested in the command line arguments
if (_argParser.luaScript != null)
{
Tools.LuaConsole.LoadLuaFile(_argParser.luaScript.MakeAbsolute());
}
SetStatusBar();
if (Config.StartPaused)
{
PauseEmulator();
}
// start dumping, if appropriate
if (_argParser.cmdDumpType != null && _argParser.cmdDumpName != null)
{
RecordAv(_argParser.cmdDumpType, _argParser.cmdDumpName);
}
SetMainformMovieInfo();
SynchChrome();
if (Config.RAAutostart)
{
OpenRetroAchievements();
}
_presentationPanel.Control.Paint += (o, e) =>
{
// I would like to trigger a repaint here, but this isn't done yet
};
if (!Config.SkipOutdatedOsCheck && OSTailoredCode.HostWindowsVersion is not null)
{
var (winVersion, win10PlusVersion) = OSTailoredCode.HostWindowsVersion.Value;
var message = winVersion switch
{
// OSTailoredCode.WindowsVersion._11 when win10PlusVersion! < new Version(10, 0, 22621) => $"Quick reminder: Your copy of Windows 11 (build {win10PlusVersion.Build}) is no longer supported by Microsoft.\nEmuHawk will probably continue working, but please update to at least 21H2 for increased security.",
OSTailoredCode.WindowsVersion._11 => null,
OSTailoredCode.WindowsVersion._10 when win10PlusVersion! < new Version(10, 0, 19044) => $"Quick reminder: Your copy of Windows 10 (build {win10PlusVersion.Build}) is no longer supported by Microsoft.\nEmuHawk will probably continue working, but please update to at least 21H2 for increased security.",
OSTailoredCode.WindowsVersion._10 => null,
_ => $"Quick reminder: Windows {winVersion.ToString().RemovePrefix('_').Replace("_", ".")} is no longer supported by Microsoft.\nEmuHawk will probably continue working, but please get a new operating system for increased security (either Windows 10+ or a GNU+Linux distro)."
};
if (message is not null)
{
#if DEBUG
Console.WriteLine(message);
#else
Load += (_, _) => Config.SkipOutdatedOsCheck = this.ShowMessageBox2($"{message}\n\nSkip this reminder from now on?");
#endif
}
}
}
private readonly bool _suppressSyncSettingsWarning;
public override bool BlocksInputWhenFocused { get; } = false;
public int ProgramRunLoop()
{
// needs to be done late, after the log console snaps on top
// fullscreen should snap on top even harder!
if (_needsFullscreenOnLoad)
{
_needsFullscreenOnLoad = false;
ToggleFullscreen();
}
// Simply exit the program if the version is asked for
if (_argParser.printVersion)
{
// Print the version
Console.WriteLine(VersionInfo.GetEmuVersion());
// Return and leave
return _exitCode;
}
// incantation required to get the program reliably on top of the console window
// we might want it in ToggleFullscreen later, but here, it needs to happen regardless
BringToFront();
Activate();
BringToFront();
InitializeFpsData();
for (; ; )
{
Input.Instance.Update();
// handle events and dispatch as a hotkey action, or a hotkey button, or an input button
// ...but prepare haptics first, those get read in ProcessInput
var finalHostController = InputManager.ControllerInputCoalescer;
InputManager.ActiveController.PrepareHapticsForHost(finalHostController);
ProcessInput(
_hotkeyCoalescer,
finalHostController,
InputManager.ClientControls.SearchBindings,
InputManager.ActiveController.HasBinding);
InputManager.ClientControls.LatchFromPhysical(_hotkeyCoalescer);
InputManager.ActiveController.LatchFromPhysical(finalHostController);
InputManager.ActiveController.ApplyAxisConstraints(
(Emulator is N64 && Config.N64UseCircularAnalogConstraint) ? "Natural Circle" : null);
InputManager.ActiveController.OR_FromLogical(InputManager.ClickyVirtualPadController);
InputManager.AutoFireController.LatchFromPhysical(finalHostController);
if (InputManager.ClientControls["Autohold"])
{
InputManager.ToggleStickies();
}
else if (InputManager.ClientControls["Autofire"])
{
InputManager.ToggleAutoStickies();
}
// autohold/autofire must not be affected by the following inputs
InputManager.ActiveController.Overrides(InputManager.ButtonOverrideAdapter);
if (Tools.Has<LuaConsole>())
{
Tools.LuaConsole.ResumeScripts(false);
}
StepRunLoop_Core();
StepRunLoop_Throttle();
Render();
// HACK: RAIntegration might peek at memory during messages
// we need this to allow memory access here, otherwise it will deadlock
var raMemHack = (RA as RAIntegration)?.ThisIsTheRAMemHack();
raMemHack?.Enter();
CheckMessages();
// RA == null possibly due MainForm Dispose disposing RA (which case Exit is not valid anymore)
// RA != null possibly due to RA object being created (which case raMemHack is null, as RA was null before)
if (RA is not null) raMemHack?.Exit();
if (_exitRequestPending)
{
_exitRequestPending = false;
Close();
}
if (IsDisposed || _windowClosedAndSafeToExitProcess)
{
break;
}
if (Config.DispSpeedupFeatures != 0)
{
Thread.Sleep(0);
}
}
Shutdown();
return _exitCode;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
// NOTE: this gets called twice sometimes. once by using() in Program.cs and once from winforms internals when the form is closed...
if (DisplayManager != null)
{
DisplayManager.Dispose();
DisplayManager = null;
}
RA?.Dispose();
RA = null;
if (disposing)
{
components?.Dispose();
SingleInstanceDispose();
}
base.Dispose(disposing);
}
private bool _emulatorPaused;
public bool EmulatorPaused
{
get => _emulatorPaused;
private set
{
_didMenuPause = false; // overwritten where relevant
if (_emulatorPaused && !value) // Unpausing
{
InitializeFpsData();
}
_emulatorPaused = value;
OnPauseChanged?.Invoke(_emulatorPaused);
}
}
public bool BlockFrameAdvance { get; set; }
public event Action<bool> OnPauseChanged;
public string CurrentlyOpenRom { get; private set; } // todo - delete me and use only args instead
public LoadRomArgs CurrentlyOpenRomArgs { get; private set; }
public bool PauseAvi { get; set; }
public bool PressFrameAdvance { get; set; }
public bool FrameInch { get; set; }
public bool HoldFrameAdvance { get; set; } // necessary for tastudio > button
public bool PressRewind { get; set; } // necessary for tastudio < button
public bool FastForward { get; set; }
/// <summary>
/// Disables updates for video/audio, and enters "turbo" mode.
/// Can be used to replicate Gens-rr's "latency compensation" that involves:
/// <list type="bullet">
/// <item><description>Saving a no-framebuffer state that is stored in RAM</description></item>
/// <item><description>Emulating forth for some frames with updates disabled</description></item>
/// <item><description><list type="bullet">
/// <item><description>Optionally hacking in-game memory
/// (like camera position, to show off-screen areas)</description></item>
/// </list></description></item>
/// <item><description>Updating the screen</description></item>
/// <item><description>Loading the no-framebuffer state from RAM</description></item>
/// </list>
/// The most common use case is CamHack for Sonic games.
/// Accessing this from Lua allows to keep internal code hacks to minimum.
/// <list type="bullet">
/// <item><description><see cref="ClientLuaLibrary.InvisibleEmulation(bool)"/></description></item>
/// <item><description><see cref="ClientLuaLibrary.SeekFrame(int)"/></description></item>
/// </list>
/// </summary>
public bool InvisibleEmulation { get; set; }
private long MouseWheelTracker;
private int? _pauseOnFrame;
public int? PauseOnFrame // If set, upon completion of this frame, the client wil pause
{
get => _pauseOnFrame;
set
{
bool wasTurboSeeking = IsTurboSeeking;
_pauseOnFrame = value;
SetPauseStatusBarIcon();
if (wasTurboSeeking && value == null) // TODO: make an Event handler instead, but the logic here is that after turbo seeking, tools will want to do a real update when the emulator finally pauses
{
Tools.UpdateToolsBefore();
Tools.UpdateToolsAfter();
}
}
}
public bool IsSeeking => PauseOnFrame.HasValue;
private bool IsTurboSeeking => PauseOnFrame.HasValue && Config.TurboSeek;
public bool IsTurboing => InputManager.ClientControls["Turbo"] || IsTurboSeeking;
/// <summary>
/// Used to disable secondary throttling (e.g. vsync, audio) for unthrottled modes or when the primary (clock) throttle is taking over (e.g. during fast forward/rewind).
/// </summary>
public static bool DisableSecondaryThrottling { get; set; }
public void AddOnScreenMessage(string message, int? duration = null) => OSD.AddMessage(message, duration);
public void ClearHolds()
{
InputManager.StickyXorAdapter.ClearStickies();
InputManager.AutofireStickyXorAdapter.ClearStickies();
if (Tools.Has<VirtualpadTool>())
{
Tools.VirtualPad.ClearVirtualPadHolds();
}
}
public void FlagNeedsReboot()
{
RebootStatusBarIcon.Visible = true;
AddOnScreenMessage("Core reboot needed for this setting");
}
/// <remarks>don't use this, use <see cref="Emulator"/></remarks>
private IEmulator _emulator;