-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
1063 lines (993 loc) · 45.9 KB
/
Copy pathProgram.cs
File metadata and controls
1063 lines (993 loc) · 45.9 KB
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
// SPDX-License-Identifier: GPL-2.0-or-later
// © itsnateai
using EQSwitch.Config;
using EQSwitch.Core;
using EQSwitch.UI;
namespace EQSwitch;
static class Program
{
// Single-instance mutex to prevent multiple copies running
private static Mutex? _mutex;
[STAThread]
static void Main(string[] args)
{
// --test-migrate <input-json> — run ConfigVersionMigrator on the file and write
// <input>.migrated.json next to it. Exits without showing UI. Used by scripted
// migration test fixtures under _tests/migration/.
if (args.Length >= 2 && args[0] == "--test-migrate")
{
try
{
var inputPath = args[1];
var inputJson = File.ReadAllText(inputPath);
var (migratedJson, didMigrate) = ConfigVersionMigrator.MigrateIfNeeded(inputJson);
var outputPath = inputPath + ".migrated.json";
File.WriteAllText(outputPath, migratedJson);
File.WriteAllText(inputPath + ".test-result.txt",
$"input={inputPath}\noutput={outputPath}\nmigrated={didMigrate}\n");
}
catch (Exception ex)
{
File.WriteAllText(args[1] + ".test-result.txt", $"ERROR: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}\n");
}
return;
}
// --test-split <input-v3-json> — deserialize accounts[] into LoginAccount[],
// run LoginAccountSplitter, and write the split result to <input>.split.json.
// The fixture harness asserts this output matches the migrator's accountsV4 /
// charactersV4 keys so the two code paths can't drift silently.
if (args.Length >= 2 && args[0] == "--test-split")
{
try
{
var inputPath = args[1];
var inputJson = File.ReadAllText(inputPath);
var options = new System.Text.Json.JsonSerializerOptions
{
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
};
var root = System.Text.Json.Nodes.JsonNode.Parse(inputJson)?.AsObject();
var accountsArray = root?["accounts"]?.ToJsonString() ?? "[]";
var legacyAccounts = System.Text.Json.JsonSerializer.Deserialize<List<EQSwitch.Models.LoginAccount>>(
accountsArray, options) ?? new List<EQSwitch.Models.LoginAccount>();
var (v4Accounts, v4Characters) = EQSwitch.Config.LoginAccountSplitter.Split(legacyAccounts);
var splitOutput = new System.Text.Json.Nodes.JsonObject
{
["accounts"] = System.Text.Json.Nodes.JsonNode.Parse(
System.Text.Json.JsonSerializer.Serialize(v4Accounts, options)),
["characters"] = System.Text.Json.Nodes.JsonNode.Parse(
System.Text.Json.JsonSerializer.Serialize(v4Characters, options)),
};
File.WriteAllText(inputPath + ".split.json", splitOutput.ToJsonString(
new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
}
catch (Exception ex)
{
File.WriteAllText(args[1] + ".test-result.txt", $"ERROR (split): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}\n");
}
return;
}
// --test-autologin [alias] [--timeout N] — launch a real EQ client, drive
// full auto-login, monitor phase, kill the process, and verify zero SEH
// in the native mq2_bridge dispatch path. Used by the v8 Step 2B
// verification loop and any future native-path change. Works in both
// Debug and Release builds because a failing login is a shippable bug.
//
// Returns:
// 0 = login completed + zero native-path SEH in log (PASS)
// 1 = login didn't reach charselect (timeout or fault)
// 2 = login completed BUT log has SEH occurrences
// 3 = config / account not found
if (args.Length >= 1 && args[0] == "--test-autologin")
{
int exitCode;
try
{
exitCode = Core.TestAutoLoginRunner.Run(args);
}
catch (Exception ex)
{
Console.Error.WriteLine($"TestAutoLoginRunner CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
#if !DEBUG
// v3.15.10: test CLI flags (--test-character-selector / --test-config-validate /
// --test-key-input-writer / --test-shm-layout / --test-charselect-reader) are
// Debug-only by design — the tests live in Core/*Tests.cs which the csproj
// excludes from Release builds (avoids ~50KB of bloat and Console output
// surface in the shipped 155MB single-file binary). `--test-autologin` above
// is the exception: it ships in Release because a failing autologin is a
// shippable bug a user would want to diagnose.
//
// Without this guard, `--test-foo` in Release would silently fall through to
// the normal tray-app launch path — confusing for anyone running the flag
// expecting a test runner. Exit cleanly with a distinct code instead so a
// calling shell can tell the flag was rejected (vs the app launching).
if (args.Length >= 1
&& args[0].StartsWith("--test-", StringComparison.Ordinal)
&& args[0] != "--test-autologin")
{
// No console attached in WinExe Release, so a Console.Error.WriteLine
// wouldn't be visible — but the exit code is observable to the calling
// shell ($LASTEXITCODE in PowerShell, $? in bash via && / ||).
Environment.Exit(3);
return;
}
#endif
#if DEBUG
// --test-character-selector — run Core/CharacterSelectorTests.RunAll() and
// exit with its return code. Used to gate Phase 5b's pure decision helper.
if (args.Length >= 1 && args[0] == "--test-character-selector")
{
int exitCode;
try
{
exitCode = Core.CharacterSelectorTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"CharacterSelectorTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-dpi-baseline — run Core/DpiBaselineTests.RunAll(): asserts every UI Form
// inherits EqSwitchForm (the 96-DPI baseline). Guards the DPI retrofit from regressing
// when new forms are added.
if (args.Length >= 1 && args[0] == "--test-dpi-baseline")
{
int exitCode;
try
{
exitCode = Core.DpiBaselineTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"DpiBaselineTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-schema — run Core/EqClientSchemaTests.RunAll(): validates the
// eqclient.ini SettingDescriptor table (no duplicate (section,key), toggle polarity,
// numeric range, default round-trip). Phase 0 of the EQ Client Settings overhaul
// (docs/specs/2026-06-06-eqclient-settings-overhaul.md).
if (args.Length >= 1 && args[0] == "--test-eqclient-schema")
{
int exitCode;
try
{
exitCode = Core.EqClientSchemaTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EqClientSchemaTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-inidoc — run Core/EqClientIniDocumentTests.RunAll(): validates the
// section-aware INI engine (correct-section read/write, in-section insert not EOF, mirror
// writes). Phase 1 of the EQ Client Settings overhaul.
if (args.Length >= 1 && args[0] == "--test-eqclient-inidoc")
{
int exitCode;
try
{
exitCode = Core.EqClientIniDocumentTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EqClientIniDocumentTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-save — run UI/DiagRender.RunEqClientSaveRoundtrip(): constructs the EQ
// Client Settings main window against a temp INI and proves the Save path (touch-gated write,
// correct section + mirror, no clobber of untouched/unmanaged keys, no ghost). Phase 1.
if (args.Length >= 1 && args[0] == "--test-eqclient-save")
{
int exitCode;
try
{
exitCode = UI.DiagRender.RunEqClientSaveRoundtrip();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EqClientSaveRoundtrip CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-enforce — run UI/DiagRender.RunEnforceOverridesSmoke(): proves the narrowed
// launch writer enforces Operational keys (WindowedMode/Maximized) but no longer re-stamps
// Bucket-2 keys (eqgame-wins). Closes Phase 1's launch-path residual.
if (args.Length >= 1 && args[0] == "--test-eqclient-enforce")
{
int exitCode;
try
{
exitCode = UI.DiagRender.RunEnforceOverridesSmoke();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EnforceOverridesSmoke CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-chatspam-save — run UI/DiagRender.RunEqChatSpamSaveRoundtrip(): constructs
// the Chat Spam window against a temp INI and proves Phase 2's touch-gated Save (only changed
// filters written; absent/untouched keys NOT inserted — i.e. no write-all; unmanaged preserved;
// no ghost). Phase 2 of the EQ Client Settings overhaul.
if (args.Length >= 1 && args[0] == "--test-eqclient-chatspam-save")
{
int exitCode;
try
{
exitCode = UI.DiagRender.RunEqChatSpamSaveRoundtrip();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EqChatSpamSaveRoundtrip CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-eqclient-particles-save — run UI/DiagRender.RunEqParticlesSaveRoundtrip(): constructs
// the Particles window against a temp INI and proves Phase 4's touch-gated Save incl. the new
// engine slider↔float path (drag a slider -> 6-decimal write; absent/untouched NOT inserted;
// unmanaged preserved; no ghost). Phase 4 of the EQ Client Settings overhaul.
if (args.Length >= 1 && args[0] == "--test-eqclient-particles-save")
{
int exitCode;
try
{
exitCode = UI.DiagRender.RunEqParticlesSaveRoundtrip();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EqParticlesSaveRoundtrip CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-font-dispose — run Core/FontDisposeOwnershipTests.RunAll(): asserts
// DisposeControlFonts frees only owned fonts, never inherited/Control.DefaultFont.
// Guards the button-click "Parameter is not valid" crash class from regressing.
if (args.Length >= 1 && args[0] == "--test-font-dispose")
{
int exitCode;
try
{
exitCode = Core.FontDisposeOwnershipTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"FontDisposeOwnershipTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --diag-render-form <Name> [--out dir] [--tab N] [--scale F] [--hold] — DEBUG-only
// DPI verification harness: render ONE form in isolation + screenshot it to a PNG so a
// high-DPI Sandbox (or scaled display) captures how it looks at 125%/150% without a human
// driving the live tray app. The layout-container rebuild is verified through this — see
// UI/DiagRender.cs. Returns (doesn't Environment.Exit) — it runs its own Application loop.
if (args.Length >= 1 && args[0] == "--diag-render-form")
{
UI.DiagRender.Run(args);
return;
}
// --test-dispose-cycle [FormName] — DEBUG-only: build a real form, Show+Dispose it, then
// create a fresh TextBox/ComboBox — reproduces the "Parameter is not valid" disposed-font
// crash at the form level (a direct grid/dialog font dispose freeing a shared/default font).
// The static FontDisposeOwnershipTests can't reach this; default form = ProcessManagerForm.
if (args.Length >= 1 && args[0] == "--test-dispose-cycle")
{
int exitCode;
try { exitCode = UI.DiagRender.RunDisposeCycle(args.Length >= 2 ? args[1] : "ProcessManagerForm"); }
catch (Exception ex)
{
Console.Error.WriteLine($"DisposeCycle CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-lazy-save — DEBUG-only: runtime repro + guard for the lazy-tab refactor (Video + Accounts
// build on first view). Verifies that clicking Save WITHOUT opening Video/Accounts preserves all
// their config fields — the unbuilt tabs are built + populated from _config by EnsureAllTabsBuilt
// before ApplySettings reads them (an identity round-trip, no clobber-to-default). Red->green repro
// for the lazy-save corruption class; see UI/DiagRender.cs RunLazySave.
if (args.Length >= 1 && args[0] == "--test-lazy-save")
{
int exitCode;
try { exitCode = UI.DiagRender.RunLazySave(); }
catch (Exception ex)
{
Console.Error.WriteLine($"LazySave CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-config-validate — run Core/AppConfigValidateTests.RunAll() and
// exit with its return code.
if (args.Length >= 1 && args[0] == "--test-config-validate")
{
int exitCode;
try
{
exitCode = Core.AppConfigValidateTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"AppConfigValidateTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-quicklogin — run Core/QuickLoginSlotTests.RunAll() and exit with its
// return code. Guards the v3.23.0 typed Quick Login slot format (char:/acct:
// round-trip + legacy bare back-compat) that the tray dispatch depends on.
if (args.Length >= 1 && args[0] == "--test-quicklogin")
{
int exitCode;
try
{
exitCode = Core.QuickLoginSlotTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"QuickLoginSlotTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-team-dedup — run Core/TeamLoginDeduperTests.RunAll() and exit with its
// return code. Guards the v3.23.4 launch-time same-login dedup that backstops
// FireTeam (two slots resolving to one login must not both fire — EQ kicks the dup).
if (args.Length >= 1 && args[0] == "--test-team-dedup")
{
int exitCode;
try
{
exitCode = Core.TeamLoginDeduperTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"TeamLoginDeduperTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-team-slot-resolver — run Core/TeamSlotResolverTests.RunAll() and exit with its
// return code. Guards the v3.24.15 typed/legacy-bare team-slot routing shared by FireTeam
// and the Teams display paths (acct:Name stays selectable even when a same-name Character
// exists — the "eisley account hidden in Configure Teams" fix).
if (args.Length >= 1 && args[0] == "--test-team-slot-resolver")
{
int exitCode;
try
{
exitCode = Core.TeamSlotResolverTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"TeamSlotResolverTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-update-assets — run Core/UpdateAssetMatchTests.RunAll() and exit with its
// return code. Guards the v3.24.18 dual-asset self-update matching: canonical vs
// versioned zip predicates (versioned requires a version-shaped suffix) and the
// SHA256SUMS parser keyed off the exact chosen asset name (anti-shadowing, fail-closed).
if (args.Length >= 1 && args[0] == "--test-update-assets")
{
int exitCode;
try
{
exitCode = Core.UpdateAssetMatchTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"UpdateAssetMatchTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-window-mode-style — run Core/WindowModeStyleTests.RunAll() and
// exit with its return code. Guards the WindowMode → GWL_STYLE mapping
// (Fullscreen=WS_POPUP, Windowed=WS_CAPTION) added in v3.22.81 Phase 2.
if (args.Length >= 1 && args[0] == "--test-window-mode-style")
{
int exitCode;
try
{
exitCode = Core.WindowModeStyleTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"WindowModeStyleTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-key-input-writer — run Core/KeyInputWriterTests.RunAll() and
// exit with its return code. Guards the hotfix v3 MMF write-order contract.
if (args.Length >= 1 && args[0] == "--test-key-input-writer")
{
int exitCode;
try
{
exitCode = Core.KeyInputWriterTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"KeyInputWriterTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-shm-layout — verify C# SharedKeyState struct layout matches
// Native/key_shm.h. Fails fast if a refactor drifts either side.
if (args.Length >= 1 && args[0] == "--test-shm-layout")
{
int exitCode;
try
{
exitCode = Core.ShmLayoutTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"ShmLayoutTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-charselect-reader — exercise CharSelectReader against simulated
// bridge writes (gate / latch / single-char fallback / recycled-PID safety).
// No external eqgame.exe needed — uses fake PIDs + paired MemoryMappedFile views.
if (args.Length >= 1 && args[0] == "--test-charselect-reader")
{
int exitCode;
try
{
exitCode = Core.CharSelectReaderTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"CharSelectReaderTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-outer-rect-math — exercise WindowManager.ComputeOuterRectFromBleeds
// against Win10 / Win11 / clamp / asymmetric / neg-origin scenarios.
// Guards the v3.22.45 fix for the Win11 DWM-bleed "vertical seam + desktop
// sliver" bug from regressing. No HWNDs / no IWindowsApi mock — pure math.
if (args.Length >= 1 && args[0] == "--test-outer-rect-math")
{
int exitCode;
try
{
exitCode = Core.OuterRectMathTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"OuterRectMathTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-window-clamp — run Core/WindowManagerClampTests.RunAll() and exit
// with its return code. Guards the mode-dependent adjacency-clamp branch
// (Windowed SKIPS ClampBleedsForAdjacency / Fullscreen APPLIES it) that the
// pure-static OuterRectMathTests cannot reach. Added v3.22.83 follow-up.
if (args.Length >= 1 && args[0] == "--test-window-clamp")
{
int exitCode;
try
{
exitCode = Core.WindowManagerClampTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"WindowManagerClampTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-frame-correction — run Core/FrameCorrectionTests.RunAll() and exit.
// Guards the v3.22.84 WinEQ2 measure-don't-predict read-back correction
// (WindowManager.TryComputeReadbackCorrection) via a fake IWindowsApi: a live
// client overshooting the monitor must be corrected to land flush, and an
// already-flush / Fullscreen / garbage-read window must be a no-op.
if (args.Length >= 1 && args[0] == "--test-frame-correction")
{
int exitCode;
try
{
exitCode = Core.FrameCorrectionTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"FrameCorrectionTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-frame-cache — run Core/FrameCacheTests.RunAll() and exit. Guards the
// v3.22.88 measured-frame cache: a warm cache builds the first-paint SHM rect from
// the MEASURED frame (flush, no zone-in snap); a miss / wrong-DPI / Fullscreen /
// insane / null cache falls back to the AdjustWindowRectEx prediction (today's
// behavior); a sane read-back measurement is persisted (write-on-change), an insane
// one is not; the on-disk cache round-trips and drops corrupt entries on load.
if (args.Length >= 1 && args[0] == "--test-frame-cache")
{
int exitCode;
try
{
exitCode = Core.FrameCacheTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"FrameCacheTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-swap-cover — run Core/SwapCoverOrderingTests.RunAll() and exit. Guards the
// v3.24.1 incoming-first HWND_TOP plant (taskbar-flicker fix): on the multimon swap
// path (coverPrimaryFirst:true) ArrangeMultiMonitor must plant the primary-bound
// (slot-0) client at HWND_TOP covering primary BEFORE the DeferWindowPos batch, and
// do nothing when coverPrimaryFirst:false. A recording IWindowsApi fake verifies the
// plant's params + that it precedes the batch commit.
if (args.Length >= 1 && args[0] == "--test-swap-cover")
{
int exitCode;
try
{
exitCode = Core.SwapCoverOrderingTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"SwapCoverOrderingTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-effective-bounds — run Core/EffectiveSlotBoundsTests.RunAll() and exit. Guards
// the multimonitor sizing authority (WindowManager.EffectiveSlotBounds) across the
// cross-hardware config matrix: single/matched/mismatched/4K/primary-bigger/slot-wrap/
// auto-hide/asymmetric-fit + CoverAll-vs-ShowTaskbars. The v3.24.10 load-bearing
// invariant: LOCK-SIZE + BOTTOM-ANCHOR — both windows take the primary's size; the 2nd is
// bottom-anchored to its work bottom (ShowTaskbars, butts taskbar) or full bottom (CoverAll).
if (args.Length >= 1 && args[0] == "--test-effective-bounds")
{
int exitCode;
try
{
exitCode = Core.EffectiveSlotBoundsTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"EffectiveSlotBoundsTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-compact-slots — run Core/MonitorSlotPackerTests.RunAll() and exit. Guards the
// v3.24.12 orphan-rescue compaction (MonitorSlotPacker.Compact): when the primary-monitor
// client closes, the survivor must re-pack onto the freed primary, preserving relative
// order, tie-broken by PID, wrapping modulo monitorCount for the 3+-client overflow case.
// Pure-map test only; the real gate is a live close-primary-watch-orphan-jump smoke.
if (args.Length >= 1 && args[0] == "--test-compact-slots")
{
int exitCode;
try
{
exitCode = Core.MonitorSlotPackerTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"MonitorSlotPackerTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
// --test-hotkey-keyname — run Core/HotkeyKeyNameTests.RunAll() and exit. Guards the
// hotkey display↔resolve round-trip: SettingsForm.FormatHotkeyKeyName(Keys) must emit
// the canonical name HotkeyManager.ResolveVK can turn back into a non-zero VK. Locks
// the 2026-06-03 fix where bare keys (\ ]) were rejected and number-row keys ("D1")
// didn't resolve, so a "set" hotkey silently never fired.
if (args.Length >= 1 && args[0] == "--test-hotkey-keyname")
{
int exitCode;
try
{
exitCode = Core.HotkeyKeyNameTests.RunAll();
}
catch (Exception ex)
{
Console.Error.WriteLine($"HotkeyKeyNameTests CRASHED: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
exitCode = 2;
}
Environment.Exit(exitCode);
return;
}
#endif
// Enforce single instance
const string mutexName = "EQSwitch_SingleInstance_SoD";
_mutex = new Mutex(true, mutexName, out bool createdNew);
// After self-update, the old instance may still be shutting down
if (!createdNew && args.Contains("--after-update"))
{
for (int i = 0; i < 10 && !createdNew; i++)
{
Thread.Sleep(500);
_mutex.Dispose();
_mutex = new Mutex(true, mutexName, out createdNew);
}
}
if (!createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FloatingTooltip.Show("EQSwitch is already running. Check your system tray.", 4000);
// Brief delay so tooltip is visible before process exits
Thread.Sleep(4200);
return;
}
bool isAfterUpdate = args.Contains("--after-update");
FileLogger.Initialize();
CleanupUpdateArtifacts();
// SystemAware DPI mode — restored 2026-05-19 after v3.22.19's
// PerMonitorV2 experiment introduced regressions in single-screen
// mode (windows bugged into Fullscreen mode on team launch) and
// didn't fix the multi-monitor cross-DPI positioning anyway.
// Per Nate's directive: "if trying to match other monitor DPI is
// bugging us then just goal on making the multimonitor constant
// and working flawless and dont worry about extending the 2nd
// monitor to cover it". The per-monitor slim flag still ships as
// an architectural framework for future revisits, but the runtime
// behavior is now back to v3.22.18 baseline.
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Set an app-managed default font. Without this, controls use the
// static Control.DefaultFont (SystemFonts.DefaultFont) which gets
// invalidated during runtime — possibly by display change events,
// DPI context switches, or GDI+ cleanup in this tray-only app.
// Controls then throw "Parameter is not valid" on construction.
Application.SetDefaultFont(new Font("Segoe UI", 9f));
// Catch UI thread exceptions BEFORE WinForms tries to show ThreadExceptionDialog
// (which itself crashes due to GDI+ font corruption, hiding the real error)
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += (_, e) =>
{
FileLogger.Error("UI thread exception (original)", e.Exception);
try
{
MessageBox.Show(
$"EQSwitch encountered an error:\n\n{e.Exception.GetType().Name}: {e.Exception.Message}\n\n{e.Exception.StackTrace}",
"EQSwitch Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch
{
// If even MessageBox fails (GDI+ corruption), at least we logged it
}
};
try
{
var config = ConfigManager.Load();
// First-run: show EQ path picker
bool isNewUser = false;
if (config.IsFirstRun)
{
using var dialog = new FirstRunDialog();
if (dialog.ShowDialog() != DialogResult.OK)
return; // User cancelled — don't start
config.EQPath = dialog.SelectedEQPath;
config.IsFirstRun = false;
isNewUser = true;
// Seed EQ client settings from actual ini so AppConfig reflects reality
// instead of hardcoded defaults — prevents silent overwrites on first Save
if (!string.IsNullOrEmpty(config.EQPath))
{
var iniPath = Path.Combine(config.EQPath, "eqclient.ini");
config.EQClientIni = EQClientIniConfig.SeedFromIni(iniPath);
}
// v3.22.91: SeedFromIni copies the user's eqclient.ini verbatim, which
// may include WindowedMode=FALSE. Validate() pins the required
// ForceWindowedMode=true invariant BEFORE this first-run Save persists
// it — without this, a false would land on disk until the next launch's
// Load→Validate. (Closes the SeedFromIni→Save gap a verifier flagged.)
config.Validate();
ConfigManager.Save(config);
ConfigManager.FlushSave();
}
var processManager = new ProcessManager(config);
var trayApp = new TrayManager(config, processManager);
// Ensure cleanup on any exit path (not just tray menu Exit)
Application.ApplicationExit += (_, _) => trayApp.Dispose();
trayApp.Initialize();
// Auto-open Settings on first run so new users can configure
if (isNewUser)
trayApp.OpenSettingsAfterDelay();
// Show confirmation after successful self-update (delayed so tray is ready).
// Intentionally calls FloatingTooltip.Show directly — bypasses
// TrayManager.ShowBalloon and the AppConfig.ShowTooltips toggle so
// the post-update confirmation always surfaces, even when the user
// has muted status tooltips.
if (isAfterUpdate)
{
var postUpdateTimer = new System.Windows.Forms.Timer { Interval = 1500 };
postUpdateTimer.Tick += (_, _) =>
{
postUpdateTimer.Stop();
postUpdateTimer.Dispose();
var version = System.Reflection.Assembly.GetExecutingAssembly()
.GetName().Version?.ToString(3) ?? "?";
FloatingTooltip.Show($"✅ EQSwitch updated to v{version}!", 5000);
};
postUpdateTimer.Start();
}
// v3.22.29 Items 6+7: write .ok startup sentinel(s) once the tray
// is up and the message pump has been ticking for a few seconds.
// CleanupUpdateArtifacts gates .old removal on these sentinels, so
// if the NEW binary crashes during init before this Timer fires,
// .old persists across the next launch and the torn-state branch
// can restore it. 5s gives the WinForms loop time to absorb any
// first-tick GDI/COM exceptions that a sentinel-on-launch would
// miss.
var sentinelTimer = new System.Windows.Forms.Timer { Interval = 5000 };
sentinelTimer.Tick += (_, _) =>
{
sentinelTimer.Stop();
sentinelTimer.Dispose();
UpdateDialog.WriteStartupSentinel();
};
sentinelTimer.Start();
// --test-update: simulate update flow without hitting GitHub
#if DEBUG
if (args.Contains("--test-update"))
{
UpdateDialog.TestMode = true;
var timer = new System.Windows.Forms.Timer { Interval = 500 };
timer.Tick += (_, _) =>
{
timer.Stop();
timer.Dispose();
using var dlg = new UpdateDialog();
dlg.ShowDialog();
};
timer.Start();
}
#endif
Application.Run();
}
catch (Exception ex)
{
FileLogger.Error("Fatal error", ex);
MessageBox.Show(
$"EQSwitch encountered a fatal error:\n\n{ex.Message}",
"EQSwitch Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
ConfigManager.FlushSave();
ConfigManager.Shutdown();
FileLogger.Shutdown();
if (createdNew) _mutex?.ReleaseMutex();
_mutex?.Dispose();
}
}
private static void CleanupUpdateArtifacts()
{
var dir = AppDomain.CurrentDomain.BaseDirectory;
// Torn-state recovery set — mirrors UpdateDialog's `files` swap list. uninstall.bat
// (bundled in the zip since v3.24.18, self-updated since v3.24.19) is included so a
// hard crash between Phase A
// and Phase B can't silently lose it. It is intentionally ABSENT from `oldFiles` below
// (no .ok-gated rollback retention — a text file never "proves it runs"); its `.old` is
// cleaned via `alwaysCleanup` instead.
var updateables = new[] { "EQSwitch.exe", "eqswitch-hook.dll", "eqswitch-di8.dll", "uninstall.bat" };
// Torn-state recovery: any updateable missing while its `.old` sibling
// exists indicates an update was interrupted (hard crash / power loss
// between Phase A's `localPath → .old` move and Phase B's `.new →
// localPath` move). Restore from `.old` to get back to the previous
// working install.
//
// v3.22.29 verifier-found gap (Opus T3 #6): the prior version only
// restored EQSwitch.exe and left hook.dll / di8.dll in whatever torn
// state the interrupt produced. Fixed there by restoring all three
// updateables symmetrically — but only when EXE was the one missing.
//
// v3.22.30 verifier-found gap (T3 Opus, same-day cascade): the gate
// was still `if (!File.Exists(exePath))`, so a Phase-B-mid-loop crash
// where Phase B committed EQSwitch.exe but didn't commit a DLL left
// the exe present with the DLL missing — the recovery branch
// skipped, and the `.ok`-gated `.old` cleanup below then DELETED the
// missing DLL's `.old` sibling (because the previous launch's `.ok`
// sentinel was still present, never cleared by the in-progress
// Phase B which crashed before reaching the post-swap `.ok` delete).
// Result: new exe + missing DLLs + no recovery sources = bricked
// install. Widened the gate to fire whenever ANY updateable is
// missing-while-.old-exists.
bool tornState = false;
foreach (var fname in updateables)
{
var fullPath = Path.Combine(dir, fname);
if (!File.Exists(fullPath) && File.Exists(fullPath + ".old"))
{
tornState = true;
break;
}
}
if (tornState)
{
foreach (var fname in updateables)
{
var fullPath = Path.Combine(dir, fname);
var oldPath = fullPath + ".old";
if (!File.Exists(fullPath) && File.Exists(oldPath))
{
try
{
File.Move(oldPath, fullPath);
FileLogger.Warn($"Recovered {fname} from .old after interrupted update.");
}
catch (Exception ex)
{
FileLogger.Error($"Failed to recover {fname} from .old: {ex.Message}");
}
}
}
return;
}
// v3.22.29 Items 6+7: .old cleanup is now gated on the .ok startup
// sentinel for each updateable file. The new binary writes the
// sentinel ~5s after Application.Run starts (see Program.Main); if
// the new binary crashed during init the sentinel was never written
// and .old persists, giving us a recovery path that doesn't require
// a user rebuilding from GitHub.
//
// Per-file pairing:
// EQSwitch.exe.old kept until EQSwitch.exe.ok exists
// eqswitch-hook.dll.old kept until eqswitch-hook.dll.ok exists
// eqswitch-di8.dll.old kept until eqswitch-di8.dll.ok exists
// .new and update.zip artifacts are always safe to remove (incomplete
// download or interrupted extract — never the user's only good copy).
var oldFiles = new[] { "EQSwitch.exe.old", "eqswitch-hook.dll.old", "eqswitch-di8.dll.old" };
// uninstall.bat.old joins the always-cleanup set rather than the .ok-gated `oldFiles`
// set: a text file has no "new binary proved it can start" rollback semantics, so there
// is nothing to gate its retention on (and gating it would emit a misleading "new binary
// did not finish init" Warn every update). Safe by ordering — the torn-state branch above
// runs and returns FIRST, so by the time we reach here every updateable (incl.
// uninstall.bat) is present, making its `.old` dead weight rather than a recovery source.
var alwaysCleanup = new[]
{
"EQSwitch.exe.new", "eqswitch-hook.dll.new", "eqswitch-di8.dll.new",
"uninstall.bat.old", "uninstall.bat.new",