1 #region Copyright & License Information
2 /*
3  * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
4  * This file is part of OpenRA, which is free software. It is made
5  * available to you under the terms of the GNU General Public License
6  * as published by the Free Software Foundation, either version 3 of
7  * the License, or (at your option) any later version. For more
8  * information, see COPYING.
9  */
10 #endregion
11 
12 using System.Collections.Generic;
13 using System.Linq;
14 using OpenRA.Mods.Common.Traits;
15 using OpenRA.Traits;
16 
17 namespace OpenRA.Mods.Common.Commands
18 {
19 	[Desc("Enables commands triggered by typing them into the chatbox. Attach this to the world actor.")]
20 	public class ChatCommandsInfo : TraitInfo<ChatCommands> { }
21 
22 	public class ChatCommands : INotifyChat
23 	{
24 		public Dictionary<string, IChatCommand> Commands { get; private set; }
25 
ChatCommands()26 		public ChatCommands()
27 		{
28 			Commands = new Dictionary<string, IChatCommand>();
29 		}
30 
OnChat(string playername, string message)31 		public bool OnChat(string playername, string message)
32 		{
33 			if (message.StartsWith("/"))
34 			{
35 				var name = message.Substring(1).Split(' ')[0].ToLowerInvariant();
36 				var command = Commands.FirstOrDefault(x => x.Key == name);
37 
38 				if (command.Value != null)
39 					command.Value.InvokeCommand(name.ToLowerInvariant(), message.Substring(1 + name.Length).Trim());
40 				else
41 					Game.Debug("{0} is not a valid command.", name);
42 
43 				return false;
44 			}
45 
46 			return true;
47 		}
48 
RegisterCommand(string name, IChatCommand command)49 		public void RegisterCommand(string name, IChatCommand command)
50 		{
51 			// Override possible duplicates instead of crashing.
52 			Commands[name.ToLowerInvariant()] = command;
53 		}
54 	}
55 
56 	public interface IChatCommand
57 	{
InvokeCommand(string command, string arg)58 		void InvokeCommand(string command, string arg);
59 	}
60 }
61