-
Notifications
You must be signed in to change notification settings - Fork 1
/
EntryPoint.cs
360 lines (314 loc) · 14 KB
/
EntryPoint.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Andraste.Payload.ModManagement;
using Andraste.Payload.Native;
using Andraste.Shared.Lifecycle;
using Andraste.Shared.ModManagement.Features;
using Andraste.Shared.ModManagement.Json.Features;
using Andraste.Shared.ModManagement.Json.Features.Plugin;
using EasyHook;
using NLog;
using NLog.Config;
using NLog.Targets;
using Semver;
namespace Andraste.Payload
{
// TODO: Proper Shutdown detection using WM_ or something.
public abstract class EntryPoint : IEntryPoint
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
// TODO: Make non-static once we have a reasonable way to access EntryPoint non-static.
// TODO: Move into dedicated class
public static string GameFolder;
public static string GameExecutable;
/// <summary>
/// The folder where the resulting assembly dll is stored.
/// This can be different from the Working Directory, which is the
/// folder where the Launcher/Host Application resides.
/// </summary>
public static string FrameworkFolder;
public static string ProfileFolder;
public abstract string FrameworkName { get; }
public abstract string Version { get; }
public bool IsRunning { get; protected set; } = true;
/// <summary>
/// Determines when the application is ready.
/// This is set, as soon as the Process has it's MainWindowHandle
/// </summary>
public bool IsReady => Process.GetCurrentProcess().MainWindowHandle != IntPtr.Zero;
private bool _ready;
protected readonly Dictionary<string, IFeatureParser> FeatureParser = new Dictionary<string, IFeatureParser>();
protected readonly Dictionary<string, SemVersion> BuiltInDependencies = new Dictionary<string, SemVersion>();
public readonly ManagerContainer Container;
protected readonly ModLoader ModLoader;
protected EntryPoint(RemoteHooking.IContext context, string profileFolder)
{
GameFolder = Directory.GetCurrentDirectory();
GameExecutable = Process.GetCurrentProcess().MainModule!.FileName;
FrameworkFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ProfileFolder = profileFolder;
Container = new ManagerContainer();
ModLoader = new ModLoader(this);
}
public virtual void Run(RemoteHooking.IContext context, string profileFolder)
{
try
{
Run(profileFolder);
}
catch (Exception ex)
{
Logger.Fatal(ex, "Unhandled Exception in the Andraste Bootstrapping process.");
ShowExceptionDialog(ex);
IsRunning = false;
Shutdown();
}
}
private void Run(string profileFolder) {
if (ShouldSetupExceptionHandlers)
{
RegisterExceptionHandlers();
}
if (ShouldSetupLogging)
{
SetupLogging();
}
Thread.CurrentThread.Name = "Andraste Main-Thread";
Logger.Info($"Game Executable: {GameExecutable}");
Logger.Info($"Game Directory: {GameFolder}");
Logger.Info($"Profile Directory: {ProfileFolder}");
Logger.Info($"Framework Directory: {FrameworkFolder}");
Logger.Info($".NET Plattform: {RuntimeInformation.FrameworkDescription}"); // .net 4.7.1+
Logger.Trace("Loading Mods");
LoadMods();
Logger.Trace("Internal Initialization done, calling Pre-Wakeup");
PreWakeup();
ModLoader.EmitGenericEvent(EGenericEvent.EPreWakeup);
Logger.Trace("Loading the Managers");
Container.Load();
Logger.Trace("Implementing Mods");
ImplementMods();
Logger.Trace("Waking up the Application");
RemoteHooking.WakeUpProcess();
Logger.Trace("Calling Post-Wakeup");
PostWakeup();
ModLoader.EmitGenericEvent(EGenericEvent.EPostWakeup);
while (IsRunning)
{
if (!_ready && IsReady)
{
// A small wait, since some contexts might still not be ready at window creation time.
Thread.Sleep(100);
Logger.Trace("Calling ApplicationReady");
_ready = true;
try
{
ApplicationReady();
}
catch (Exception ex)
{
Logger.Error(ex, "Exception in ApplicationReady");
}
ModLoader.EmitGenericEvent(EGenericEvent.EApplicationReady);
}
Thread.Sleep(100);
}
Shutdown();
}
protected virtual void Shutdown()
{
Logger.Info("Shutting down and exiting CLR");
ModLoader?.UnloadPlugins();
Container.Unload();
UnregisterExceptionHandlers();
LogManager.Flush();
Thread.Sleep(1000); // Give the actual flushing some time.
Environment.Exit(1);
}
#region Mods
/// <summary>
/// The mods have been parsed into <see cref="ModLoader.EnabledMods"/>, including their feature statements, and the
/// framework had a chance in changing this in <see cref="PreWakeup"/>.
/// Now the mods are "implemented", that means, the parsed features are used to dispatch hooks and others.
/// </summary>
protected virtual void ImplementMods()
{
ModLoader.ImplementVfs();
ModLoader.ImplementPlugins();
ModLoader.LoadPlugins();
}
/// <summary>
/// Scans for a launcher-defined mods.json and examines it's contents.
/// It will then proceed to load and register the mods, so they are available for the framework impl in
/// PreWakeup, but they will be only activated after PreWakeup returns (but before actually waking up)
/// </summary>
protected virtual void LoadMods()
{
DiscoverMods();
ValidateDependencies();
LoadFeatureParsers();
ParseModFeatures();
}
protected virtual void ParseModFeatures()
{
foreach (var mods in ModLoader.EnabledMods)
{
Logger.Info($"Enabled Mod {mods.ModInformation.Slug}");
var conf = mods.ModInformation.Configurations[mods.ModSetting.ActiveConfiguration];
foreach (var feature in conf.Features.Keys)
{
try
{
if (FeatureParser.TryGetValue(feature, out var parser))
{
var parsed = parser.Parse(conf.Features[feature]);
conf._parsedFeatures.Add(feature, parsed);
}
else
{
Logger.Warn($"Unknown Feature {feature}. Skipping");
}
}
catch (Exception exception)
{
Logger.Warn(exception, $"Exception when parsing {feature} for {mods.ModInformation.Slug}. " +
"Syntax error in mod.json? Missing dependant mod?");
}
}
}
}
protected virtual void DiscoverMods()
{
ModLoader.EnabledMods = ModLoader.DiscoverMods(ProfileFolder);
}
protected virtual void ValidateDependencies()
{
ModLoader.ValidateDependencies(BuiltInDependencies);
}
protected virtual void LoadFeatureParsers()
{
FeatureParser.Add("andraste.builtin.vfs", new VFSFeatureParser());
FeatureParser.Add("andraste.builtin.plugin", new PluginFeatureParser());
}
#endregion
#region Lifecycle
/// <summary>
/// This is called when Andraste has been loaded so far and the user
/// framework is ready for action (registering hooks).
/// This happens before the Application is launched, so regular
/// method calls should not be called at this stage.
/// Use <see cref="PostWakeup"/> instead.
/// </summary>
protected abstract void PreWakeup();
/// <summary>
/// This is called when Andraste has been loaded and the application
/// has become active.
/// This is the perfect time for a full initialization of non-critical
/// hooks and all other elements, as this stage does NOT delay the
/// application start-up (as opposed to <see cref="PreWakeup"/>).
/// </summary>
protected abstract void PostWakeup();
/// <summary>
/// This is called when the Application has been loaded and created
/// its Main Window.
///
/// This happens after Pre/PostWakeup and is intended to initialize
/// custom UI or accessing game functions (add your own, more specific
/// checks, if possible).
/// </summary>
protected abstract void ApplicationReady();
#endregion
#region Logging
protected bool ShouldSetupLogging { get; set; } = true;
/// <summary>
/// Sets a default NLog logging up. Stub this method if you plan on providing your own backend.
/// Using a different logging framework is not supported, because Andraste will use NLog internally.
/// </summary>
protected virtual void SetupLogging()
{
// Workaround: For some reason, NLog is only flushing/deleting the file, once you log something to it,
// so we're going to force-delete the files for now.
var outputLog = Path.Combine(ProfileFolder, "output.log");
var errorLog = Path.Combine(ProfileFolder, "error.log");
if (File.Exists(outputLog))
{
File.Delete(outputLog);
}
if (File.Exists(errorLog))
{
File.Delete(errorLog);
}
var cfg = new LoggingConfiguration();
var fileStdout = new FileTarget("fileStdout")
{
FileName = outputLog, AutoFlush = true, DeleteOldFileOnStartup = true,
Layout = "${longdate}|${threadname}(${threadid})|${level:uppercase=true}|${logger}|${message}${exception:format=ToString}"
};
// TODO: Proper \r\n before exception, but only if there is an exception...
var fileErr = new FileTarget("fileErr")
{
FileName = errorLog, AutoFlush = false, DeleteOldFileOnStartup = true,
// Default from https://github.com/NLog/NLog/wiki/File-target#layout-options
Layout = "${longdate}|${threadname}(${threadid})|${level:uppercase=true}|${logger}|${message}${exception:format=ToString}"
};
cfg.AddRule(LogLevel.Trace, LogLevel.Warn, fileStdout);
cfg.AddRule(LogLevel.Error, LogLevel.Fatal, fileErr);
LogManager.Configuration = cfg;
}
#endregion
#region Exception Handlers
/// <summary>
/// Whether this should setup the exception handlers to display a
/// message dialog for uncaught exceptions, that could terminate
/// the game otherwise.
///
/// Set to false before <see cref="Run"/> is called or use
/// <see cref="RegisterExceptionHandlers"/> and
/// <see cref="UnregisterExceptionHandlers"/>.
/// </summary>
protected bool ShouldSetupExceptionHandlers { get; set; } = true;
protected void RegisterExceptionHandlers()
{
// TODO: refactor ProcessExit, so that it's always hooked and can properly do the destruction
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
protected void UnregisterExceptionHandlers()
{
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
}
protected virtual void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Logger.Fatal(e.ExceptionObject as Exception, $"Got uncaught Exception{Environment.NewLine}");
ShowExceptionDialog(e.ExceptionObject as Exception);
if (e.IsTerminating)
{
IsRunning = false;
Shutdown(); // Run() won't be running anymore if it has caused the exception
// @TODO: We should maybe just unload all hooks so the game can continue running
}
}
private void ShowExceptionDialog(Exception e)
{
var text = "An Uncaught Exception has happened and the game will now crash!\n" +
$"This is definitely caused by Andraste / {FrameworkName}!\n\n" +
$"---------------------\n{e}";
var mwh = Process.GetCurrentProcess().MainWindowHandle;
const uint MB_OK = 0;
const uint MB_ICONERROR = 0x00000010U;
User32.MessageBox(mwh != IntPtr.Zero ? mwh : IntPtr.Zero, text, "Uncaught Exception", MB_OK | MB_ICONERROR);
}
protected virtual void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Logger.Info("Got ProcessExit: Shutting down!");
IsRunning = false;
}
#endregion
}
}