Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
508 lines (446 loc) · 18.4 KB
/
Copy pathProgram.cs
File metadata and controls
508 lines (446 loc) · 18.4 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
using System.Runtime.InteropServices;
using System.Text;
using HidSharp;
using Nefarius.ViGEm.Client;
using Nefarius.ViGEm.Client.Exceptions;
using Nefarius.ViGEm.Client.Targets;
using Nefarius.ViGEm.Client.Targets.Xbox360;
namespace X360EMU;
internal static class Program
{
private static readonly CancellationTokenSource Cts = new();
private static HidHideManager _hidHide = null!;
private static TrayContext? _tray;
private static int _cleaned;
private static readonly StringBuilder CliOut = new();
[STAThread]
private static int Main(string[] args)
{
bool cliMode = args.Contains("--help") || args.Contains("-h") ||
args.Contains("--status") || args.Contains("--unhide") ||
args.Contains("--startup");
if (cliMode) AttachConsole(-1); // reuse the terminal we were launched from, if any
_hidHide = new HidHideManager();
if (args.Contains("--help") || args.Contains("-h"))
{
PrintHelp();
return FlushCli(0);
}
if (args.Contains("--unhide"))
{
if (!_hidHide.IsInstalled)
{
Out("[.] HidHide is not installed - nothing to unhide.");
return FlushCli(0);
}
bool restoredLeftovers = _hidHide.TryRestoreLeftovers();
int removed = _hidHide.ForceUnhideDualSense();
Out(restoredLeftovers
? $"[+] Restored previous session's HidHide state ({removed} extra DualSense entries removed)."
: $"[+] Removed {removed} DualSense entries from the HidHide block list.");
return FlushCli(0);
}
if (args.Contains("--startup"))
{
int idx = Array.IndexOf(args, "--startup");
string mode = idx + 1 < args.Length ? args[idx + 1].ToLowerInvariant() : "";
switch (mode)
{
case "on":
StartupManager.Enable();
Out($"[+] Start with Windows: enabled ({Environment.ProcessPath})");
break;
case "off":
StartupManager.Disable();
Out("[+] Start with Windows: disabled");
break;
default:
Out("[x] Usage: --startup on | --startup off");
return FlushCli(1);
}
return FlushCli(0);
}
if (args.Contains("--status"))
{
PrintStatus();
return FlushCli(0);
}
// ---- default mode: tray app ----
using var mutex = new Mutex(true, "X360EMU_SingleInstance", out bool firstInstance);
if (!firstInstance)
{
MessageBox.Show("X360EMU is already running - look for the green icon in the system tray.",
"X360EMU", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
bool noHide = args.Contains("--no-hide");
int runSeconds = 0;
for (int i = 0; i < args.Length - 1; i++)
if (args[i] == "--seconds" && int.TryParse(args[i + 1], out var s))
runSeconds = s;
AppDomain.CurrentDomain.ProcessExit += (_, _) => Cleanup();
AppDomain.CurrentDomain.UnhandledException += (_, _) => Cleanup();
Microsoft.Win32.SystemEvents.SessionEnded += (_, _) => { Cts.Cancel(); Cleanup(); };
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
_tray = new TrayContext(() => Cts.Cancel());
if (runSeconds > 0)
Cts.CancelAfter(TimeSpan.FromSeconds(runSeconds));
var worker = new Thread(() => Worker(noHide)) { IsBackground = false, Name = "emu-worker" };
worker.Start();
Application.Run(_tray); // blocks until ExitApp()
Cleanup(); // idempotent safety net
return 0;
}
private static void Worker(bool noHide)
{
try
{
if (HidHideManager.HasLeftoverState && _hidHide.IsInstalled)
{
Log("[!] Previous session did not exit cleanly - restoring HidHide state first...");
_hidHide.TryRestoreLeftovers();
}
ViGEmClient vigem;
try
{
vigem = new ViGEmClient();
}
catch (VigemBusNotFoundException)
{
Log("[x] ViGEmBus driver not found.");
MessageBox.Show(
"ViGEmBus driver not found - the virtual Xbox 360 pad cannot be created.\n\n" +
"Install it with: winget install Nefarius.ViGEmBus (then reboot)",
"X360EMU", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
bool hideEnabled = !noHide;
if (hideEnabled && !_hidHide.IsInstalled)
{
Log("[!] HidHide driver not installed - the DualSense will stay visible to games (double input possible).");
Log(" Install it: winget install Nefarius.HidHide");
hideEnabled = false;
}
if (hideEnabled)
{
try
{
string exe = Environment.ProcessPath!;
_hidHide.EnsureAppAllowed(exe);
Log("[+] HidHide: X360EMU is on the allow-list (keeps reading the hidden pad)");
}
catch (Exception ex)
{
Log($"[!] HidHide configuration failed: {ex.Message}");
Log(" Try running as administrator. Continuing WITHOUT hiding.");
hideEnabled = false;
}
}
try
{
RunLoop(vigem, hideEnabled);
}
finally
{
Cleanup();
vigem.Dispose();
}
Log("[+] Exited cleanly - DualSense visibility restored.");
}
catch (Exception ex)
{
Log($"[x] Fatal error: {ex}");
Cleanup();
}
finally
{
_tray?.ExitApp();
}
}
private static void RunLoop(ViGEmClient vigem, bool hideEnabled)
{
bool printedWaiting = false;
while (!Cts.IsCancellationRequested)
{
var device = DeviceList.Local
.GetHidDevices(DualSense.VendorId)
.FirstOrDefault(d => DualSense.ProductIds.Contains(d.ProductID));
if (device is null)
{
if (!printedWaiting)
{
Log("[.] Waiting for a DualSense (USB or Bluetooth)...");
_tray?.SetStatus("X360EMU - waiting for a DualSense...");
printedWaiting = true;
}
Cts.Token.WaitHandle.WaitOne(1500);
continue;
}
printedWaiting = false;
try
{
ServeDevice(vigem, device, hideEnabled);
}
catch (Exception ex) when (!Cts.IsCancellationRequested)
{
Log($"[!] Controller session ended: {ex.Message}");
Cts.Token.WaitHandle.WaitOne(500);
}
}
}
private static void ServeDevice(ViGEmClient vigem, HidDevice device, bool hideEnabled)
{
bool bluetooth = device.GetMaxInputReportLength() >= 78;
string transport = bluetooth ? "Bluetooth" : "USB";
Log($"[+] DualSense found ({transport})");
if (!device.TryOpen(out HidStream stream))
{
Log("[!] Could not open the controller (grabbed by another app?). Retrying...");
Cts.Token.WaitHandle.WaitOne(1500);
return;
}
using (stream)
{
stream.ReadTimeout = 3000;
if (bluetooth)
TryEnableFullReports(device, stream);
if (hideEnabled)
{
string? instanceId = DeviceInterface.GetInstanceId(device.DevicePath);
if (instanceId is null)
{
Log("[!] Could not resolve the device instance id - NOT hiding this controller.");
}
else
{
try
{
_hidHide.HideInstance(instanceId);
Log($"[+] Hidden from other apps: {instanceId}");
}
catch (Exception ex)
{
Log($"[!] Could not hide the controller: {ex.Message} (try running as administrator)");
}
}
}
var pad = vigem.CreateXbox360Controller();
pad.AutoSubmitReport = false;
int maxOut = device.GetMaxOutputReportLength();
byte seq = 0;
byte motorL = 0, motorR = 0;
byte sentL = 0xFF, sentR = 0xFF;
bool lowBattery = false;
var outLock = new object();
void SendOutput(bool setupRelease = false)
{
lock (outLock)
{
var (r, g, b) = lowBattery ? ((byte)96, (byte)0, (byte)0) : ((byte)0, (byte)32, (byte)128);
byte[] rep = DualSense.BuildOutputReport(bluetooth, seq, motorL, motorR,
r, g, b, playerLeds: 0x04, setupRelease, maxOut);
seq = (byte)((seq + 1) & 0x0F);
stream.Write(rep);
sentL = motorL;
sentR = motorR;
}
}
pad.FeedbackReceived += (_, e) =>
{
motorL = e.LargeMotor;
motorR = e.SmallMotor;
try
{
if (e.LargeMotor != sentL || e.SmallMotor != sentR)
SendOutput();
}
catch { /* device may be mid-disconnect */ }
};
pad.Connect();
Log("[+] Virtual Xbox 360 controller connected");
_tray?.SetStatus($"X360EMU - active ({transport})");
try
{
if (bluetooth) SendOutput(setupRelease: true); // release BT pairing-blink first
SendOutput(); // lightbar + player-1 LED
}
catch (Exception ex)
{
Log($"[!] Output report failed (rumble/LED may not work): {ex.Message}");
}
var buf = new byte[Math.Max(device.GetMaxInputReportLength(), 78)];
var st = new DualSenseState();
int lastBattery = -2;
try
{
while (!Cts.IsCancellationRequested)
{
int n;
try
{
n = stream.Read(buf);
}
catch (TimeoutException) { continue; }
catch (IOException) { break; }
catch (ObjectDisposedException) { break; }
if (n <= 0) break;
if (!DualSense.Parse(buf, n, bluetooth, ref st)) continue;
MapToPad(in st, pad);
pad.SubmitReport();
if (st.BatteryPercent >= 0 && st.BatteryPercent != lastBattery)
{
lastBattery = st.BatteryPercent;
bool nowLow = st.BatteryPercent <= 15 && !st.Charging;
if (nowLow != lowBattery)
{
lowBattery = nowLow;
try { SendOutput(); } catch { /* best effort */ }
}
string chg = st.Charging ? ", charging" : st.FullyCharged ? ", full" : "";
_tray?.SetStatus($"X360EMU - active ({transport}), battery {st.BatteryPercent}%{chg}");
}
}
}
finally
{
try { pad.Disconnect(); } catch { /* already gone */ }
(pad as IDisposable)?.Dispose();
}
if (!Cts.IsCancellationRequested)
{
Log("[!] Controller disconnected - waiting for reconnect...");
_tray?.SetStatus("X360EMU - controller disconnected, waiting...");
}
}
}
/// <summary>Over BT the pad boots in a simplified report mode; reading feature report 0x05 switches it to full 0x31 reports.</summary>
private static void TryEnableFullReports(HidDevice device, HidStream stream)
{
try
{
var buf = new byte[Math.Max(41, device.GetMaxFeatureReportLength())];
buf[0] = 0x05;
stream.GetFeature(buf);
}
catch (Exception ex)
{
Log($"[!] Could not switch to full Bluetooth reports ({ex.Message}) - using simplified input (no battery info).");
}
}
private static void MapToPad(in DualSenseState st, IXbox360Controller pad)
{
pad.SetAxisValue(Xbox360Axis.LeftThumbX, AxisX(st.LX));
pad.SetAxisValue(Xbox360Axis.LeftThumbY, AxisY(st.LY));
pad.SetAxisValue(Xbox360Axis.RightThumbX, AxisX(st.RX));
pad.SetAxisValue(Xbox360Axis.RightThumbY, AxisY(st.RY));
pad.SetSliderValue(Xbox360Slider.LeftTrigger, st.L2);
pad.SetSliderValue(Xbox360Slider.RightTrigger, st.R2);
pad.SetButtonState(Xbox360Button.A, st.Cross);
pad.SetButtonState(Xbox360Button.B, st.Circle);
pad.SetButtonState(Xbox360Button.X, st.Square);
pad.SetButtonState(Xbox360Button.Y, st.Triangle);
pad.SetButtonState(Xbox360Button.LeftShoulder, st.L1);
pad.SetButtonState(Xbox360Button.RightShoulder, st.R1);
pad.SetButtonState(Xbox360Button.LeftThumb, st.L3);
pad.SetButtonState(Xbox360Button.RightThumb, st.R3);
pad.SetButtonState(Xbox360Button.Start, st.Options);
pad.SetButtonState(Xbox360Button.Back, st.Create || st.TouchClick);
pad.SetButtonState(Xbox360Button.Guide, st.PS);
int h = st.DpadHat;
pad.SetButtonState(Xbox360Button.Up, h is 7 or 0 or 1);
pad.SetButtonState(Xbox360Button.Right, h is >= 1 and <= 3);
pad.SetButtonState(Xbox360Button.Down, h is >= 3 and <= 5);
pad.SetButtonState(Xbox360Button.Left, h is >= 5 and <= 7);
}
// HID axes: 0..255, Y grows downward. XInput: -32768..32767, Y grows upward.
private static short AxisX(byte v) => (short)(v * 257 - 32768);
private static short AxisY(byte v) => (short)Math.Clamp(32767 - v * 257, -32768, 32767);
private static void Cleanup()
{
if (Interlocked.Exchange(ref _cleaned, 1) == 1) return;
try { _hidHide.RestoreAll(); } catch { /* best effort */ }
}
/// <summary>Runtime log: goes to the tray status window (and to the console when one is attached).</summary>
private static void Log(string line)
{
Console.WriteLine(line); // no-op when there is no console
_tray?.AppendLog(line);
}
// ---- CLI output plumbing (--status / --unhide / --help) ----
private static void Out(string s)
{
Console.WriteLine(s);
CliOut.AppendLine(s);
}
/// <summary>When launched with no console at all (e.g. from Explorer), show the CLI output in a message box.</summary>
private static int FlushCli(int code)
{
nint stdout = GetStdHandle(-11);
if (stdout is 0 or -1 && GetConsoleWindow() == 0)
MessageBox.Show(CliOut.ToString(), "X360EMU", MessageBoxButtons.OK, MessageBoxIcon.Information);
return code;
}
private static void PrintStatus()
{
try
{
using var v = new ViGEmClient();
Out("[+] ViGEmBus driver: installed");
}
catch (Exception)
{
Out("[x] ViGEmBus driver: NOT installed -> winget install Nefarius.ViGEmBus");
}
if (_hidHide.IsInstalled)
{
Out($"[+] HidHide driver: installed (cloaking {(_hidHide.IsActive ? "ACTIVE" : "inactive")})");
foreach (var id in _hidHide.Blocked)
Out($" blocked: {id}");
foreach (var p in _hidHide.AllowedApps)
Out($" allowed: {p}");
}
else
{
Out("[x] HidHide driver: NOT installed -> winget install Nefarius.HidHide");
}
Out($"[{(StartupManager.IsEnabled ? '+' : '.')}] Start with Windows: {(StartupManager.IsEnabled ? "enabled" : "disabled")}");
var pads = DeviceList.Local.GetHidDevices(DualSense.VendorId)
.Where(d => DualSense.ProductIds.Contains(d.ProductID)).ToList();
if (pads.Count == 0)
{
Out("[.] No DualSense connected.");
}
foreach (var d in pads)
{
bool bt = d.GetMaxInputReportLength() >= 78;
string? inst = DeviceInterface.GetInstanceId(d.DevicePath);
Out($"[+] DualSense ({(bt ? "Bluetooth" : "USB")}): {inst ?? d.DevicePath}");
}
}
private static void PrintHelp()
{
Out("""
Usage: X360EMU [options]
(no options) Run in the system tray: DualSense -> virtual Xbox 360 pad,
DualSense hidden from every other app, restored on exit.
Double-click the tray icon for status/log, right-click to exit.
--no-hide Emulate without hiding the DualSense (double input possible).
--unhide Repair mode: remove all DualSense entries from HidHide and exit.
Use this if a crash/kill left the controller invisible.
--status Show driver + controller + HidHide state and exit.
--startup on Launch automatically at Windows sign-in (per-user, no admin).
--startup off Remove the automatic launch. Also togglable in the tray menu.
--seconds N Auto-exit after N seconds (testing).
--help This text.
Requires the ViGEmBus and HidHide drivers (winget install Nefarius.ViGEmBus / Nefarius.HidHide).
""");
}
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern nint GetConsoleWindow();
[DllImport("kernel32.dll")]
private static extern nint GetStdHandle(int nStdHandle);
}