-
Notifications
You must be signed in to change notification settings - Fork 0
/
MoreCommands.cs
337 lines (289 loc) · 15.3 KB
/
MoreCommands.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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using Brigadier.NET;
using Brigadier.NET.Context;
using Brigadier.NET.Suggestion;
using Brigadier.NET.Tree;
using log4net;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MonoMod.RuntimeDetour;
using MoreCommands.ArgumentTypes.Entities;
using MoreCommands.Extensions;
using MoreCommands.Hooks;
using MoreCommands.IL;
using MoreCommands.IL.Detours;
using MoreCommands.Misc;
using MoreCommands.Misc.TagHandlers;
using MoreCommands.UI;
using MoreCommands.Utils;
using Newtonsoft.Json;
using ReLogic.Content;
using Terraria;
using Terraria.Chat;
using Terraria.Chat.Commands;
using Terraria.GameContent.NetModules;
using Terraria.Graphics.Effects;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;
using Terraria.UI.Chat;
namespace MoreCommands;
public class MoreCommands : Mod
{
public static MoreCommands Instance { get; private set; }
public static ILog Log => Instance?.Logger;
public static CommandDispatcher<CommandSource> Dispatcher { get; private set; } = new();
public static Color DefColour { get; set; } = Color.Orange;
public static Color SecColour { get; set; } = Color.Yellow;
public static bool IsClientOp { get; private set; }
public static (uint requestId, Suggestions suggestions) RequestedSuggestions { get; private set; } = (0, null);
public static IEnumerable<Command> Commands => CommandsBackend.ToImmutableList();
public static bool Rainbow
{
get => _rainbow;
set
{
_rainbow = value;
Filters.Scene["MCRainbow"].GetShader().UseProgress(value ? 1 : 0); // Deactivating isn't instant, setting a variable is.
if (value) Filters.Scene.Activate("MCRainbow");
else Filters.Scene.Deactivate("MCRainbow");
}
}
public static IEnumerable<string> LegacyCommands => LegacyCommandsBackend.ToImmutableList();
private static bool _rainbow;
private static readonly Func<ChatCommandProcessor, Dictionary<LocalizedText, ChatCommandId>> GetLocalizedCommands =
Dynamics.CreateGetter<ChatCommandProcessor, Dictionary<LocalizedText, ChatCommandId>>("_localizedCommands");
private static readonly Func<ChatCommandProcessor, Dictionary<ChatCommandId, IChatCommand>> GetVanillaCommands =
Dynamics.CreateGetter<ChatCommandProcessor, Dictionary<ChatCommandId, IChatCommand>>("_commands");
private static readonly List<string> LegacyCommandsBackend = new();
internal static ModKeybind CommandKeybind { get; private set; }
internal static UserInterface CommandTileInterface;
internal static CommandTileUI CommandTileUI;
internal static UserInterface SuggestionsInterface;
internal static UserInterface DisposalInterface;
internal static DisposalUI DisposalUI;
internal static UserInterface TitleInterface;
internal static TitleUI TitleUI;
private static (uint requestId, Suggestions suggestions) _clientSuggestions = (0, null);
private static readonly IList<Command> CommandsBackend = new List<Command>();
private static readonly IList<Detour> Detours = new List<Detour>();
private static readonly IDictionary<CommandNode<CommandSource>, Command> CommandOrigins = new Dictionary<CommandNode<CommandSource>, Command>();
private static readonly IDictionary<CommandNode<CommandSource>, CommandNode<CommandSource>> AbsoluteParents = new Dictionary<CommandNode<CommandSource>, CommandNode<CommandSource>>();
public override void Load()
{
Instance = this;
MonoModHooks.RequestNativeAccess();
CreateDetour(typeof(CommandLoader).GetMethod("HandleCommand", BindingFlags.NonPublic | BindingFlags.Static), typeof(CommandLoaderDetours).GetMethod("HandleCommand",
BindingFlags.Public | BindingFlags.Static, new []{typeof(string), typeof(CommandCaller)}));
CreateDetour(typeof(CommandLoader).GetMethod("GetCommand", BindingFlags.NonPublic | BindingFlags.Static), typeof(CommandLoaderDetours).GetMethod("GetCommand"));
CreateDetour(typeof(NetTextModule).GetMethod("DeserializeAsServer", BindingFlags.NonPublic | BindingFlags.Instance), typeof(NetTextModuleDetours).GetMethod("DeserializeAsServer"));
ILManipulator.RegisterManipulations();
LangHelper.LoadEnglishLanguage();
EntitySelectorOptions.Register();
RegisterCommands();
if (!Main.dedServ)
{
CommandTileInterface = new UserInterface();
CommandTileUI = new CommandTileUI();
CommandTileUI.Initialize();
SuggestionsInterface = new UserInterface();
DisposalInterface = new UserInterface();
DisposalUI = new DisposalUI();
DisposalUI.Initialize();
TitleInterface = new UserInterface();
TitleUI = new TitleUI();
TitleUI.Initialize();
ChatManager.Register<ClickTagHandler>("click");
ChatManager.Register<HoverTagHandler>("hover");
ChatManager.Register<StyledTagHandler>("styled");
ScreenShaderData rainbowScreenData = new(new Ref<Effect>(Assets.Request<Effect>("Assets/Shaders/RainbowShader",
AssetRequestMode.ImmediateLoad).Value), "RainbowScreen");
rainbowScreenData.SwapProgram("RainbowScreen");
Filters.Scene["MCRainbow"] = new Filter(rainbowScreenData, EffectPriority.Medium);
}
Logging.IgnoreExceptionSource("MoreCommands");
Logging.IgnoreExceptionSource("Brigadier.NET");
Logging.IgnoreExceptionContents("Brigadier.NET");
CommandKeybind = KeybindLoader.RegisterKeybind(this, "Chat Command", Keys.OemQuestion);
}
public override void PostAddRecipes()
{
IdHelper.Init();
EntitySelectorOptions.RegisterTagGroups();
Dictionary<LocalizedText, ChatCommandId> localizedCommands = GetLocalizedCommands(ChatManager.Commands);
foreach (LocalizedText name in from KeyValuePair<ChatCommandId, IChatCommand> pair in GetVanillaCommands(ChatManager.Commands)
select localizedCommands.Select(pair0 => (KeyValuePair<LocalizedText, ChatCommandId>?) pair0)
.FirstOrDefault(pair0 => pair0.Value.Value.Equals(pair.Key))?.Key into name where name is not null select name)
LegacyCommandsBackend.Add(name.Value[1..]); // Name starts with a slash
foreach ((string name, List<ModCommand> commands) in Util.GetCommands())
if (!commands.Any(cmd => cmd is ModCommandWrapper))
LegacyCommandsBackend.Add(name);
Log.Debug("Legacy commands: " + Command.JoinNicely(LegacyCommandsBackend));
Dispatcher.FindAmbiguities((parent, child, sibling, inputs) =>
{
if (AbsoluteParents.TryGetValue(parent, out CommandNode<CommandSource> absParent) && CommandOrigins[absParent].IgnoreAmbiguities) return;
Log.Debug($"Found ambiguity on command {Dispatcher.GetPath(parent).First()} between children {child.Name} and {sibling.Name} with inputs {Command.JoinNicely(inputs)}.");
});
}
public override void Unload()
{
Instance = null;
Dispatcher = null;
DefColour = default;
CommandKeybind = null;
RequestedSuggestions = (0, null);
foreach (Detour detour in Detours)
detour.Dispose();
Detours.Clear();
ILManipulator.UnregisterEdits();
}
public override void HandlePacket(BinaryReader reader, int whoAmI)
{
byte id;
try
{
id = reader.ReadByte();
}
catch (Exception)
{
Log.Warn($"Player {whoAmI} ({Main.player[whoAmI].name}) sent a packet without id.");
return;
}
if (Main.netMode == NetmodeID.Server) switch (id)
{
// C2S PACKETS
case (byte) MCPacketID.C2S.SuggestionsRequest: // Suggestions request packet
uint requestId = reader.ReadUInt32();
string text = reader.ReadString();
CommandSource source = new(new ServerPlayerCommandCaller(Main.player[whoAmI]));
Dispatcher.GetCompletionSuggestions(Dispatcher.Parse(text, source))
.ContinueWith(task =>
{
Suggestions suggestions = task.Result;
ModPacket packet = GetPacket();
packet.Write((byte) MCPacketID.S2C.SuggestionsSend);
packet.Write(requestId);
packet.Write(suggestions.Range.Start);
packet.Write(suggestions.Range.End);
packet.Write(suggestions.List.Count);
foreach (Suggestion suggestion in suggestions.List)
{
packet.Write(suggestion.Text);
packet.Write(suggestion.Tooltip is null ? "" : suggestion.Tooltip.String);
}
packet.Send(whoAmI);
});
break;
}
else switch (id)
{
// S2C PACKETS
case (byte) MCPacketID.S2C.OperatorPacket: // Operator packet, only received when we're op(ped) or deopped.
IsClientOp = reader.ReadBoolean();
break;
case (byte) MCPacketID.S2C.SuggestionsSend: // Suggestions receive packet
uint requestId = reader.ReadUInt32();
StringRange range = StringRange.Between(reader.ReadInt32(), reader.ReadInt32());
int count = reader.ReadInt32();
List<Suggestion> list = new();
for (int i = 0; i < count; i++)
{
string text = reader.ReadString();
string tooltip = reader.ReadString();
list.Add(new Suggestion(range, text, string.IsNullOrEmpty(tooltip) ? null : new LiteralMessage(tooltip)));
}
if (_clientSuggestions.requestId == requestId) list = _clientSuggestions.suggestions.List.Where(suggestion => !list.Contains(suggestion)).Concat(list).ToList();
RequestedSuggestions = (requestId, new Suggestions(_clientSuggestions.requestId == requestId && _clientSuggestions.suggestions.Range.Start > range.Start ?
_clientSuggestions.suggestions.Range : range, list));
break;
case (byte) MCPacketID.S2C.Title:
string title = reader.ReadString();
string subtitle = reader.ReadString();
uint duration = reader.ReadUInt32();
uint fadeIn = reader.ReadUInt32();
uint fadeOut = reader.ReadUInt32();
TitleUI.ShowTitle(title, subtitle, duration, fadeIn, fadeOut);
break;
}
}
private static void RegisterCommands()
{
IDictionary<string, List<ModCommand>> commands = Util.GetCommands();
IEnumerable<Command> commandsToRegister = Assembly.GetAssembly(typeof(MoreCommands))?.GetTypes()
.Where(t => !t.IsAbstract && typeof(Command).IsAssignableFrom(t))
.Select(type =>
{
try
{
return (Command) Activator.CreateInstance(type);
}
catch (Exception e)
{
Log.Error($"Could not load command of type {type.Name}.", e);
return null;
}
})
.Where(cmd => cmd is not null)
.ToList();
foreach (Command command in commandsToRegister!)
{
if (command.ServerOnly && !Main.dedServ || command.Type == CommandType.Chat && Main.dedServ) continue;
command.Init();
IList<CommandNode<CommandSource>> before = new List<CommandNode<CommandSource>>(Dispatcher.GetRoot().Children);
command.Register(Dispatcher);
CommandsBackend.Add(command);
// Command might have registered multiple commands/aliases.
Dispatcher.GetRoot().Children
.Where(node => node is LiteralCommandNode<CommandSource> && !before.Contains(node))
.ToList()
.ForEach(node =>
{
CommandOrigins[node] = command;
RegisterAbsoluteParents(node, node);
commands.ComputeIfAbsent(node.Name, _ => new List<ModCommand>())
.Add(new ModCommandWrapper(Dispatcher, node.Name, command));
});
}
Log.Info($"Registered {commandsToRegister.Count()} commands.");
}
private static void RegisterAbsoluteParents(CommandNode<CommandSource> node, CommandNode<CommandSource> absoluteParent)
{
AbsoluteParents[node] = absoluteParent;
foreach (CommandNode<CommandSource> child in node.Children)
RegisterAbsoluteParents(child, absoluteParent);
}
private static void CreateDetour(MethodBase from, MethodBase to) => Detours.Add(new Detour(@from, to));
public static bool IsOp(int playerId) => ModContent.GetInstance<SystemHooks>().Operators.Contains(Util.GetAddress(playerId).GetIdentifier());
public static void RequestSuggestions(uint requestId)
{
Dispatcher.GetCompletionSuggestions(Dispatcher.Parse(Main.chatText[1..], new CommandSource(new ClientPlayerCommandCaller())))
.ContinueWith(task =>
{
_clientSuggestions = (requestId, task.Result);
if (Main.netMode == NetmodeID.MultiplayerClient)
{
ModPacket packet = Instance.GetPacket();
packet.Write((byte) MCPacketID.C2S.SuggestionsRequest); // Suggestions request packet.
packet.Write(requestId);
packet.Write(Main.chatText[1..]);
packet.Send();
}
else Dispatcher.GetCompletionSuggestions(Dispatcher.Parse(Main.chatText[1..], new CommandSource(new ServerPlayerCommandCaller(Main.LocalPlayer))))
.ContinueWith(task0 => RequestedSuggestions = (requestId, new Suggestions(task0.Result.Range.Start > _clientSuggestions.suggestions.Range.Start ?
task0.Result.Range : _clientSuggestions.suggestions.Range, _clientSuggestions.suggestions.List
.Where(suggestion => !task0.Result.List.Contains(suggestion)).Concat(task0.Result.List).ToList())));
});
}
private static string GetConfigPath(string name) => Path.Combine(Util.ConfigDirPath, $"MoreCommands_{name}.json");
public static bool ConfigExists(string name) => File.Exists(GetConfigPath(name));
public static T ReadJson<T>(string name) where T : new() => !File.Exists(GetConfigPath(name)) ? new T() : JsonConvert.DeserializeObject<T>(File.ReadAllText(GetConfigPath(name)));
public static void SaveJson(string name, object data) => File.WriteAllText(GetConfigPath(name), JsonConvert.SerializeObject(data, Formatting.Indented));
}