-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFeatureManager.cs
More file actions
76 lines (72 loc) · 2.71 KB
/
Copy pathFeatureManager.cs
File metadata and controls
76 lines (72 loc) · 2.71 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
namespace CWAPI
{
public class FeatureManager
{
private readonly List<IFeature> Features = [];
private readonly ManualLogSource Logger;
private readonly ConfigFile Config;
public FeatureManager(BepInEx.Logging.ManualLogSource logger, ConfigFile configs)
{
Logger = new(logger, nameof(FeatureManager));
Config = configs;
RegisterFeaturesFromAssembly(Assembly.GetCallingAssembly());
}
public void RegisterFeaturesFromAssembly(Assembly assembly)
{
Logger.LogDebug("Scanning for features...");
Type baseType = typeof(Feature<>);
assembly.GetTypes()
.Where(t =>
{
if (!t.IsClass || t.IsAbstract || t.GetCustomAttribute<FeatureAttribute>() == null) return false;
Type? current = t.BaseType;
while (current != null)
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == baseType)
return true;
current = current.BaseType;
}
return false;
}).ToList()
.ForEach(t =>
{
if (Activator.CreateInstance(t) is IFeature feature)
{
Features.Add(feature);
Logger.LogDebug($"Discovered and registered feature: {feature.FeatureName}");
}
});
}
public bool InitializeFeatures(bool handleExceptions = false) => Features.All(f =>
{
try
{
ConfigSection Section = new(Config, f.FeatureName);
f.CreateRequiredConfig(Section);
f.CreateConfig(Section);
if (f.Enabled)
{
if (f.Required)
Logger.LogInfo($"Feature '{f.FeatureName}' is required. Initializing...");
else
Logger.LogInfo($"Feature '{f.FeatureName}' is enabled. Initializing...");
f.Initialize();
}
else
Logger.LogInfo($"Feature '{f.FeatureName}' is disabled.");
return true;
}
catch (Exception ex)
{
Logger.LogError($"There was an error loading feature '{f.FeatureName}'. Exception: {ex}");
if (!handleExceptions) throw;
return false;
}
});
}
}