// ClassicalSharp copyright 2014-2016 UnknownShadow200 | Licensed under MIT using System; using System.Collections.Generic; using System.Text; namespace ClassicalSharp.Commands { public class CommandManager : IGameComponent { public static bool IsCommandPrefix( string input ) { return Utils.CaselessStarts( input, "/client " ) || Utils.CaselessEquals( input, "/client" ); } protected Game game; public List RegisteredCommands = new List(); public void Init( Game game ) { this.game = game; Register( new CommandsCommand() ); Register( new GpuInfoCommand() ); Register( new HelpCommand() ); Register( new InfoCommand() ); Register( new RenderTypeCommand() ); if( game.Network.IsSinglePlayer ) { Register( new ModelCommand() ); Register( new CuboidCommand() ); } } public void Ready( Game game ) { } public void Reset( Game game ) { } public void OnNewMap( Game game ) { } public void OnNewMapLoaded( Game game ) { } public void Register( Command command ) { command.game = game; for( int i = 0; i < RegisteredCommands.Count; i++ ) { Command cmd = RegisteredCommands[i]; if( Utils.CaselessEquals( cmd.Name, command.Name ) ) throw new InvalidOperationException( "Another command already has name : " + command.Name ); } RegisteredCommands.Add( command ); } public Command GetMatch( string commandName ) { Command match = null; for( int i = 0; i < RegisteredCommands.Count; i++ ) { Command cmd = RegisteredCommands[i]; if( !Utils.CaselessStarts( cmd.Name, commandName ) ) continue; if( match != null ) { game.Chat.Add( "&e/client: Multiple commands found that start with: \"&f" + commandName + "&e\"." ); return null; } match = cmd; } if( match == null ) game.Chat.Add( "&e/client: Unrecognised command: \"&f" + commandName + "&e\"." ); return match; } public void Execute( string text ) { CommandReader reader = new CommandReader( text ); if( reader.TotalArgs == 0 ) { game.Chat.Add( "&eList of client commands:" ); PrintDefinedCommands( game ); game.Chat.Add( "&eTo see a particular command's help, type /client help [cmd name]" ); return; } string commandName = reader.Next(); Command cmd = GetMatch( commandName ); if( cmd != null ) { cmd.Execute( reader ); } } public void PrintDefinedCommands( Game game ) { List lines = new List(); StringBuilder buffer = new StringBuilder( 64 ); for( int i = 0; i < RegisteredCommands.Count; i++ ) { Command cmd = RegisteredCommands[i]; string name = cmd.Name; if( buffer.Length + name.Length > 64 ) { lines.Add( buffer.ToString() ); buffer.Length = 0; } buffer.Append( name ); buffer.Append( ", " ); } if( buffer.Length > 0 ) lines.Add( buffer.ToString() ); for( int i = 0; i < lines.Count; i++ ) game.Chat.Add( lines[i] ); } public void Dispose() { RegisteredCommands.Clear(); } } }