Repository navigation
Expand file tree
/
Copy pathMain.cs
More file actions
373 lines (321 loc) · 13.2 KB
/
Copy pathMain.cs
File metadata and controls
373 lines (321 loc) · 13.2 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
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
namespace DateEverythingAccess
{
internal static class PluginMetadata
{
internal const string Guid = "com.amock.dateeverythingaccess";
internal const string Name = "Date Everything Access";
internal const string Version = "1.3";
}
[BepInPlugin(PluginMetadata.Guid, PluginMetadata.Name, PluginMetadata.Version)]
public class Main : BaseUnityPlugin
{
private const int VkF1 = 0x70;
private const int VkF8 = 0x77;
private const int VkF9 = 0x78;
private const int WmHotkey = 0x0312;
private const int WmQuit = 0x0012;
private const uint ModControl = 0x0002;
private const uint ModShift = 0x0004;
private const uint ModAlt = 0x0001;
private const uint ModNoRepeat = 0x4000;
private const int HelpHotkeyId = 1;
private const int DebugHotkeyId = 2;
private const int SettingsHotkeyId = 3;
private const int CoverageSweepHotkeyId = 13;
// NOTE: Repeat-last (`), look-around (L), object tracker (O), objective tracker (Ctrl+O),
// and auto-walk (Alt+O) are NO LONGER global OS hotkeys. Bare letter/backtick keys registered
// via RegisterHotKey would be swallowed from ALL text input (name/save entry) while the game is
// focused, so they are polled in AccessibilityWatcher.Update instead and suppressed while a text
// field or the settings menu has focus. Only F-key / Ctrl combos remain global below.
private Thread _hotkeyThread;
private volatile bool _hotkeyThreadRunning;
private uint _hotkeyThreadId;
private bool _applicationQuitting;
private bool _cleanupCompleted;
private Harmony _harmony;
public static bool DebugMode { get; private set; }
public static ManualLogSource Log { get; private set; }
public static Main Instance { get; private set; }
public static bool IsShuttingDown { get; private set; }
public static string RuntimeAssemblyPath { get; private set; }
public static string RuntimeAssemblySha256 { get; private set; }
public static string RuntimeBuildStamp { get; private set; }
[DllImport("user32.dll", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll", SetLastError = true)]
private static extern sbyte GetMessage(out NativeMessage lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostThreadMessage(uint idThread, uint msg, UIntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(int vKey);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
private void Awake()
{
Instance = this;
Log = Logger;
InitializeRuntimeBuildMetadata();
ScreenReader.Initialize();
Loc.Initialize();
ModConfig.Initialize(Config);
_harmony = new Harmony("com.amock.dateeverythingaccess");
_harmony.PatchAll();
Application.quitting += OnApplicationQuitting;
StartHotkeyThread();
AccessibilityWatcher.EnsureCreated();
Logger.LogInfo("Date Everything Access initialized version=" + PluginMetadata.Version);
Logger.LogInfo(
"Runtime build metadata stamp=" + GetRuntimeBuildStamp() +
" assemblyPath=" + (RuntimeAssemblyPath ?? "<null>"));
ScreenReader.Say(Loc.Get("mod_loaded"));
Logger.LogInfo("Startup announcement queued");
}
internal static string GetRuntimeBuildStamp()
{
return string.IsNullOrWhiteSpace(RuntimeBuildStamp)
? PluginMetadata.Version + "|uninitialized"
: RuntimeBuildStamp;
}
internal static string TryComputeFileSha256(string path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return null;
try
{
using (var stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete))
using (var sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", string.Empty);
}
}
catch (Exception ex)
{
Log?.LogWarning("Failed to compute SHA256 for " + path + ": " + ex.Message);
return null;
}
}
private static void InitializeRuntimeBuildMetadata()
{
try
{
string assemblyPath = typeof(Main).Assembly.Location;
RuntimeAssemblyPath = assemblyPath;
string lastWriteUtc = File.Exists(assemblyPath)
? File.GetLastWriteTimeUtc(assemblyPath).ToString("o")
: "missing";
RuntimeAssemblySha256 = TryComputeFileSha256(assemblyPath) ?? "unavailable";
RuntimeBuildStamp =
PluginMetadata.Version +
"|utc=" + lastWriteUtc +
"|sha256=" + RuntimeAssemblySha256;
}
catch (Exception ex)
{
RuntimeBuildStamp = PluginMetadata.Version + "|build-metadata-error";
Log?.LogWarning("Failed to initialize runtime build metadata: " + ex.Message);
}
}
private void OnDestroy()
{
Logger.LogInfo("Main.OnDestroy invoked");
if (!_applicationQuitting)
{
Logger.LogWarning("Ignoring OnDestroy because the application is still running");
return;
}
Cleanup();
}
private void OnApplicationQuitting()
{
_applicationQuitting = true;
IsShuttingDown = true;
Logger.LogInfo("Application quitting");
Cleanup();
}
private void Cleanup()
{
if (_cleanupCompleted)
return;
_cleanupCompleted = true;
Application.quitting -= OnApplicationQuitting;
StopHotkeyThread();
_harmony?.UnpatchSelf();
_harmony = null;
ScreenReader.Stop();
ScreenReader.Shutdown();
}
private void StartHotkeyThread()
{
if (_hotkeyThread != null)
return;
_hotkeyThreadRunning = true;
_hotkeyThread = new Thread(HotkeyThreadLoop)
{
IsBackground = true,
Name = "DateEverythingAccessHotkeys"
};
_hotkeyThread.Start();
Logger.LogInfo("Background hotkey thread started");
}
private void StopHotkeyThread()
{
if (_hotkeyThread == null)
return;
_hotkeyThreadRunning = false;
if (_hotkeyThreadId != 0)
{
PostThreadMessage(_hotkeyThreadId, WmQuit, UIntPtr.Zero, IntPtr.Zero);
}
if (!_hotkeyThread.Join(500))
{
Logger.LogWarning("Background hotkey thread did not stop within 500ms");
}
_hotkeyThread = null;
_hotkeyThreadId = 0;
}
private void HotkeyThreadLoop()
{
_hotkeyThreadId = GetCurrentThreadId();
try
{
int registered = 0;
registered += TryRegisterHotkey(HelpHotkeyId, VkF1, "F1") ? 1 : 0;
registered += TryRegisterHotkey(DebugHotkeyId, VkF9, "F9") ? 1 : 0;
registered += TryRegisterHotkey(SettingsHotkeyId, ModControl | ModNoRepeat, VkF1, "Ctrl+F1") ? 1 : 0;
registered += TryRegisterHotkey(CoverageSweepHotkeyId, ModControl | ModAlt | ModNoRepeat, VkF8, "Ctrl+Alt+F8") ? 1 : 0;
Logger.LogInfo("Background hotkey message loop active (" + registered + " hotkey(s) registered)");
NativeMessage message;
while (_hotkeyThreadRunning)
{
sbyte result = GetMessage(out message, IntPtr.Zero, 0, 0);
if (result <= 0)
break;
if (message.message == WmHotkey)
{
ProcessRegisteredHotkey((int)message.wParam);
}
}
}
catch (Exception ex)
{
Logger.LogError("Background hotkey thread failed: " + ex);
}
finally
{
UnregisterHotKey(IntPtr.Zero, HelpHotkeyId);
UnregisterHotKey(IntPtr.Zero, DebugHotkeyId);
UnregisterHotKey(IntPtr.Zero, SettingsHotkeyId);
UnregisterHotKey(IntPtr.Zero, CoverageSweepHotkeyId);
Logger.LogInfo("Background hotkey thread exiting");
}
}
private bool TryRegisterHotkey(int id, uint virtualKey, string label)
{
return TryRegisterHotkey(id, ModNoRepeat, virtualKey, label);
}
private bool TryRegisterHotkey(int id, uint modifiers, uint virtualKey, string label)
{
if (RegisterHotKey(IntPtr.Zero, id, modifiers, virtualKey))
{
Logger.LogInfo("Registered hotkey: " + label);
return true;
}
int error = Marshal.GetLastWin32Error();
// Error 1409 (ERROR_HOTKEY_ALREADY_REGISTERED) means another app owns this
// combo. Skip just this binding and keep the thread + message loop alive so
// the remaining hotkeys still work, rather than tearing down all of them.
Logger.LogWarning("Could not register hotkey " + label + " (Win32 error " + error +
"); skipping it. Other hotkeys are unaffected.");
return false;
}
private void ProcessRegisteredHotkey(int hotkeyId)
{
if (hotkeyId == HelpHotkeyId)
{
if (IsModifierKeyDown(0x10) || IsModifierKeyDown(0x11) || IsModifierKeyDown(0x12))
return;
Logger.LogInfo("Help hotkey detected");
AnnounceHelp();
return;
}
if (hotkeyId == DebugHotkeyId)
{
if (IsModifierKeyDown(0x10) || IsModifierKeyDown(0x11) || IsModifierKeyDown(0x12))
return;
ToggleDebugMode();
return;
}
if (hotkeyId == SettingsHotkeyId)
{
if (!IsModifierKeyDown(0x11) || IsModifierKeyDown(0x10) || IsModifierKeyDown(0x12))
return;
ToggleSettingsMenu();
return;
}
if (hotkeyId == CoverageSweepHotkeyId)
{
// Ctrl+Alt, no Shift: Left Shift is the game's crouch toggle.
if (!IsModifierKeyDown(0x11) || !IsModifierKeyDown(0x12) || IsModifierKeyDown(0x10))
return;
Logger.LogInfo("Coverage sweep hotkey detected");
AccessibilityWatcher.RequestToggleCoverageSweep();
}
}
private static bool IsModifierKeyDown(int virtualKey)
{
return (GetAsyncKeyState(virtualKey) & 0x8000) != 0;
}
private void AnnounceHelp()
{
Loc.RefreshLanguage();
ScreenReader.Say(Loc.Get("help_text"));
}
private void ToggleDebugMode()
{
DebugMode = !DebugMode;
string status = DebugMode ? "enabled" : "disabled";
Logger.LogInfo("Debug mode " + status);
Loc.RefreshLanguage();
if (DebugMode)
{
bool dumpedMappings = InputMappingReporter.TryDumpCurrentMappings(out int dumpedControllerCount);
string messageKey = dumpedMappings ? "debug_mode_enabled_with_mapping_dump" : "debug_mode_enabled";
ScreenReader.Say(Loc.Get(messageKey, dumpedControllerCount));
return;
}
ScreenReader.Say(Loc.Get("debug_mode_disabled"));
}
private void ToggleSettingsMenu()
{
Logger.LogInfo("Accessibility settings hotkey detected");
ModConfig.ToggleMenu();
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct NativeMessage
{
public IntPtr hWnd;
public uint message;
public UIntPtr wParam;
public IntPtr lParam;
public uint time;
public int ptX;
public int ptY;
}
}