-
Notifications
You must be signed in to change notification settings - Fork 15
/
PluginCommandManager.cs
80 lines (68 loc) · 2.85 KB
/
PluginCommandManager.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
using Dalamud.Game.Command;
using DalamudPluginProjectTemplate.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using static Dalamud.Game.Command.CommandInfo;
namespace DalamudPluginProjectTemplate
{
public class PluginCommandManager<THost> : IDisposable
{
private readonly CommandManager commandManager;
private readonly (string, CommandInfo)[] pluginCommands;
private readonly THost host;
public PluginCommandManager(THost host, CommandManager commandManager)
{
this.commandManager = commandManager;
this.host = host;
this.pluginCommands = host.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(method => method.GetCustomAttribute<CommandAttribute>() != null)
.SelectMany(GetCommandInfoTuple)
.ToArray();
AddCommandHandlers();
}
private void AddCommandHandlers()
{
foreach (var (command, commandInfo) in this.pluginCommands)
{
this.commandManager.AddHandler(command, commandInfo);
}
}
private void RemoveCommandHandlers()
{
foreach (var (command, _) in this.pluginCommands)
{
this.commandManager.RemoveHandler(command);
}
}
private IEnumerable<(string, CommandInfo)> GetCommandInfoTuple(MethodInfo method)
{
var handlerDelegate = (HandlerDelegate)Delegate.CreateDelegate(typeof(HandlerDelegate), this.host, method);
var command = handlerDelegate.Method.GetCustomAttribute<CommandAttribute>();
var aliases = handlerDelegate.Method.GetCustomAttribute<AliasesAttribute>();
var helpMessage = handlerDelegate.Method.GetCustomAttribute<HelpMessageAttribute>();
var doNotShowInHelp = handlerDelegate.Method.GetCustomAttribute<DoNotShowInHelpAttribute>();
var commandInfo = new CommandInfo(handlerDelegate)
{
HelpMessage = helpMessage?.HelpMessage ?? string.Empty,
ShowInHelp = doNotShowInHelp == null,
};
// Create list of tuples that will be filled with one tuple per alias, in addition to the base command tuple.
var commandInfoTuples = new List<(string, CommandInfo)> { (command!.Command, commandInfo) };
if (aliases != null)
{
foreach (var alias in aliases.Aliases)
{
commandInfoTuples.Add((alias, commandInfo));
}
}
return commandInfoTuples;
}
public void Dispose()
{
RemoveCommandHandlers();
GC.SuppressFinalize(this);
}
}
}