Esempio n. 1
0
        /// <summary>
        ///     Modifys the console window propertys
        /// </summary>
        private static void ModifyConsoleWindow()
        {
            //TODO: Linux support
#if !__MonoCS__ // Setting screen or primary screen
            // Fullscreen
            if (Settings.Default.ConsoleFullscreenMode)
            {
                Screen screen = Screen.AllScreens.ElementAt(Settings.Default.ConsoleFullscreenDisplay);

                // Fullscreen screen connected -> restore fullscreen on screen
                if (screen != null)
                {
                    // Move to wanted display
                    ConsoleUtils.SetWindowPos(ConsoleUtils.GetConsoleWindow(), 0, screen.WorkingArea.Left, screen.WorkingArea.Top, Console.LargestWindowWidth, Console.LargestWindowHeight, 1);
                    ConsoleUtils.ToggleConsoleFullscreenMode();
                }
                // else -> write message after server startup
                else
                {
                    SharedEvents.OnAfterCoreStartupCompleted += () => ConsoleOutput.WriteLine(ConsoleType.Warn,
                                                                                              "Can't restore fullscreen mode in this session. Console use default settings instead.");
                }
            }
            // Normal console window
            else
            {
                Point savedPosition = Settings.Default.ConsoleLocation;
                Size  ConsoleSize   = Settings.Default.ConsoleSize;

                // Console position saved -> check if valid after screen changes || set position
                if (savedPosition.X != -1 && savedPosition.Y != -1)
                {
                    // Saved on not connected screen -> message after server startup
                    if (!Screen.AllScreens.Any(screen => screen.Bounds.Contains(savedPosition)))
                    {
                        ConsoleUtils.SetWindowPos(ConsoleUtils.GetConsoleWindow(), 0, 0, 0,
                                                  ConsoleSize.Width, ConsoleSize.Height, 1);
                        SharedEvents.OnAfterCoreStartupCompleted += () => ConsoleOutput.WriteLine(ConsoleType.Warn,
                                                                                                  "Can't restore saved console location. Saved location was on disconnected screen. Console use default location instead.");
                    }
                    // Valid saved position -> restore
                    else
                    {
                        ConsoleUtils.SetWindowPos(ConsoleUtils.GetConsoleWindow(), 0, Settings.Default.ConsoleLocation.X, Settings.Default.ConsoleLocation.Y,
                                                  ConsoleSize.Width, ConsoleSize.Height, 1);
                    }
                }
            }
#endif

            // Prepare submodules
            ConsoleOutput.PrepareConsoleOutput();
            ConsoleError.PrepareConsoleError();
            ConsoleCommandHandler.PrepareConsoleCommands();
        }
Esempio n. 2
0
        public static void SaveConsolePos()
        {
            //TODO: Linux support
#if __MonoCS__
            ConsoleOutput.WriteLine(ConsoleType.Debug, "Currently only supported on Windows. See #23");
#else
            Point hWndLocation = Settings.Default.ConsoleLocation;
            ConsoleUtils.GetWindowRect(ConsoleUtils.GetConsoleWindow(), ref hWndLocation);
            Settings.Default.ConsoleLocation = hWndLocation;
            Settings.Default.Save();
            ConsoleOutput.WriteLine(ConsoleType.Config,
                                    $"Saved the current console positon at {Settings.Default.ConsoleLocation}");
#endif
        }
Esempio n. 3
0
        /// <summary>
        ///     Prepares the console comand routine.
        ///     Binding events.. etc.
        /// </summary>
        public static void PrepareConsoleCommands()
        {
            SharedEvents.OnModuleLoaded += InspectModule;

            // Output for CIN | DATETIME | INPUT
            ConsoleInput.OnConsoleString += (consoleString, args) =>
            {
                if (!args.Cancel)
                {
                    ConsoleOutput.WriteLine(ConsoleType.ConsoleInput, consoleString);
                }
            };

            // Parse input for commands
            ConsoleInput.OnConsoleString += ParseConsoleString;
        }
Esempio n. 4
0
        public static void Fullscreen(bool fullscreen, int display = -1)
        {
            // Fullscreen disabled -> Save, message & return;
            if (!fullscreen)
            {
                // Save settings
                Settings.Default.ConsoleFullscreenDisplay = -1;
                Settings.Default.ConsoleFullscreenMode    = false;
                Settings.Default.Save();

                ConsoleOutput.WriteLine(ConsoleType.Config,
                                        "Disabled fullscreen mode. ~b~Changes take effect on next Start.");
                return;
            }

#if !__MonoCS__
            // No display given -> Use current & message
            if (display == -1)
            {
                Point p = new Point();
                ConsoleUtils.GetWindowRect(ConsoleUtils.GetConsoleWindow(), ref p);
                display = Screen.AllScreens.ToList()
                          .FindIndex(screen => Equals(screen, Screen.FromPoint(new Point(p.X, p.Y))));
                ConsoleOutput.WriteLine(ConsoleType.Info,
                                        $"No display given for fullscreen. Using the current display ~b~{display}~;~.");
            }
#endif

            // invalid display given -> Warning & return;
            if (Screen.AllScreens.Length - 1 < display)
            {
                ConsoleOutput.WriteLine(ConsoleType.Warn,
                                        $"Invalid display ~o~{display}~;~. Available displays: 0 - {Screen.AllScreens.Length - 1}");
                return;
            }

            // Save settings message
            Settings.Default.ConsoleFullscreenDisplay = display;
            Settings.Default.ConsoleFullscreenMode    = true;
            Settings.Default.Save();
            ConsoleOutput.WriteLine(ConsoleType.Config,
                                    $"Enabled fullscreen mode for display ~b~{display}~;~.  " +
                                    $"~b~Changes take effect on next Start.");
        }
Esempio n. 5
0
        /// <summary>
        ///     Parsing a file line by line to a new string.
        ///     Adds ~n~ after each line.
        /// </summary>
        /// <param name="path">Path to the textfile</param>
        /// <param name="marginTopLines">Extra empty lines in top of the text file</param>
        /// <param name="marginBottomLines">Extra empty lines after the text file</param>
        /// <returns></returns>
        public static string ParseTextFileForConsole(string path, int marginTopLines = 0, int marginBottomLines = 0)
        {
            // File does not exist -> message & return;
            if (!File.Exists(path))
            {
                ConsoleOutput.WriteLine(ConsoleType.Warn,
                                        $"Can't load the text file ~r~\"{path}\"~w~. File ignored.");
                return(string.Empty);
            }

            string returnString      = string.Empty;
            int    longestLineLength = 0;

            // Read file line by line
            string       currentLine;
            StreamReader streamReader = new StreamReader(path);

            while ((currentLine = streamReader.ReadLine()) != null)
            {
                returnString += currentLine + "~n~";
                if (currentLine.Length > longestLineLength)
                {
                    longestLineLength = currentLine.Length;
                }
            }

            // MarginTop
            for (var i = 0; i < marginTopLines; i++)
            {
                returnString = string.Empty.PadRight(longestLineLength) + "~n~" + returnString;
            }

            // MarginTop
            for (var i = 0; i < marginBottomLines; i++)
            {
                returnString += string.Empty.PadRight(longestLineLength) + "~n~";
            }

            streamReader.Close();

            return(returnString);
        }
Esempio n. 6
0
        private void WriteHandler(string message)
        {
            bool gtMpMessage = ConsoleUtils.IsGtmpConsoleMessage(message);

            // Startup not completed -> return;
            if (!SharedEvents.StartUpCompleted)
            {
                return;
            }

            // Print Text as invalid console use.
            if (!gtMpMessage)
            {
                if (!_lastWasInvalid)
                {
                    ConsoleOutput.WriteLine(ConsoleType.Warn, $"Use ConsoleOutput.* for writing to console!");
                }
                _lastWasInvalid = true;
            }

            // Remove GtMp console tags
            if (gtMpMessage)
            {
                message = message.Substring(message.LastIndexOf(" | ", StringComparison.Ordinal) + 3);
            }

            if (!ConsoleUtils.OriginalWriterInUse)
            {
                // Write console line
                string[] newLines = message.Split('\n');
                foreach (string line in newLines)
                {
                    ConsoleOutput.WriteLine(gtMpMessage ? ConsoleType.GtMp : ConsoleType.ConsoleOutput, line);
                }
            }

            // Clear string Writer
            StringBuilder stringBuilder = GetStringBuilder();

            stringBuilder.Remove(0, stringBuilder.Length);
        }
Esempio n. 7
0
        public static void ViewHelpInformations(string commandName)
        {
            ConsoleCommand command = ConsoleCommandHandler.GetConsoleCommand(commandName);

            // Not command found -> message & return.
            if (command == null)
            {
                ConsoleOutput.WriteLine(ConsoleType.Help,
                                        $"No console command found for ~w~{commandName}~;~.");
                return;
            }

            // Show command help
            string commandParameter = string.Join(", ", command.MethodInfo.GetParameters()
                                                  .Select(info => $"~m~{info.ParameterType}~;~ {info.Name} " +
                                                          $"~l~{(info.IsOptional ? $" = [{info.DefaultValue}] " : "")}~;~"));

            ConsoleOutput.WriteLine(ConsoleType.Help,
                                    $"Command: ~w~{command.Command}~;~\n" +
                                    $"Aliase: ~w~{string.Join(", ", command.CommandAliases)}\n" +
                                    $"Usage: ~w~{command.Command} {commandParameter}");
        }
Esempio n. 8
0
        /// <summary>
        ///     Adding new command to the existings commands.
        ///     Checks all command attributes, and give warns on duplicates.
        /// </summary>
        /// <param name="newCommand">The new command</param>
        /// <returns>true if new command is unique, else false (with console message)</returns>
        internal static bool AddToCommands(ConsoleCommand newCommand)
        {
            bool   returnValue = true;
            string oldPrefix   = ConsoleOutput.GetPrefix();

            ConsoleOutput.SetPrefix(oldPrefix.Replace("> ", "\t"));
            try
            {
                // Already used command string -> message
                ConsoleCommand blockingCommand = Commands.FirstOrDefault(cmd =>
                                                                         cmd.Command.ToLower() == newCommand.Command.ToLower());

                if (blockingCommand != null)
                {
                    ConsoleOutput.WriteLine(ConsoleType.Warn,
                                            $"Command duplicate: ~c~{blockingCommand.FullName()}");
                    returnValue = false;
                }

                // Already used alias command string -> message
                blockingCommand = Commands.FirstOrDefault(cmd => cmd.CommandAliases.Contains(newCommand.Command) ||
                                                          cmd.CommandAliases.Any(sa => newCommand.CommandAliases
                                                                                 .Select(s => s.ToLower()).Contains(sa)));
                if (blockingCommand != null)
                {
                    ConsoleOutput.WriteLine(ConsoleType.Warn,
                                            $"Alias duplicate: ~c~{blockingCommand.FullName()}");
                    returnValue = false;
                }

                Commands.Add(newCommand);
                return(returnValue);
            }
            finally
            {
                ConsoleOutput.SetPrefix(oldPrefix);
            }
        }
Esempio n. 9
0
 private static void ApplicationOnThreadException(object sender,
                                                  ThreadExceptionEventArgs threadExceptionEventArgs)
 {
     ConsoleOutput.WriteLine(ConsoleType.Fatal, threadExceptionEventArgs.Exception.ToString());
     ConsoleUtils.SafeSystemConsoleUse(() => throw threadExceptionEventArgs.Exception);
 }
Esempio n. 10
0
 public static void CloseConsole()
 {
     ConsoleOutput.WriteLine(ConsoleType.Core, "Shutting down!");
     Thread.Sleep(1000);
     Environment.Exit(0);
 }
Esempio n. 11
0
 public static void ResetConsoleSettings()
 {
     Settings.Default.Reset();
     Settings.Default.Save();
     ConsoleOutput.WriteLine(ConsoleType.Config, "Console propertys reseted to default.");
 }
Esempio n. 12
0
        private static void ParseConsoleString(string consoleString, CancelEventArgs cancelEventArgs)
        {
            List <string> consoleStringParts = consoleString.Split(' ').ToList();

            foreach (ConsoleCommand command in Commands)
            {
                // console string not command -> continue;
                if (command.Command.ToLower() != consoleStringParts[0].ToLower() &&
                    !command.CommandAliases.Select(ca => ca.ToLower())
                    .Contains(consoleStringParts[0].ToLower()))
                {
                    continue;
                }

                // Cancle event
                cancelEventArgs.Cancel = true;

                // Remove command
                string enteredCommand = consoleStringParts[0];
                consoleStringParts.Remove(enteredCommand);

                // Check for parameters
                List <object>   parameterValues   = new List <object>();
                ParameterInfo[] commandParameters = command.MethodInfo.GetParameters();

                string currentParameterString = string.Empty;
                for (int i = 0; i < commandParameters.Length; i++)
                {
                    // No more string parameters -> break;
                    if (consoleStringParts.FirstOrDefault() == null)
                    {
                        break;
                    }

                    // append or set string parameters
                    currentParameterString += consoleStringParts.FirstOrDefault();
                    consoleStringParts.Remove(currentParameterString);

                    // String argument with quote -> wait for end quote.
                    if (currentParameterString.StartsWith("\""))
                    {
                        if (!currentParameterString.EndsWith("\""))
                        {
                            i--;
                            continue;
                        }

                        // Remove quotes
                        currentParameterString = currentParameterString
                                                 .Remove(currentParameterString.Length - 1, 1)
                                                 .Remove(0, 1);
                    }

                    // Try parse & reset string
                    try
                    {
                        // Barse boolean parameter for Convert functions
                        if (commandParameters[i].ParameterType == typeof(bool))
                        {
                            if (currentParameterString == "1")
                            {
                                currentParameterString = "true";
                            }
                            else if (currentParameterString == "0")
                            {
                                currentParameterString = "false";
                            }
                        }


                        object parameterValue =
                            Convert.ChangeType(currentParameterString, commandParameters[i].ParameterType);
                        currentParameterString = string.Empty;

                        if (parameterValue == null)
                        {
                            break;
                        }

                        parameterValues.Add(parameterValue);
                    }
                    catch (InvalidCastException)
                    {
                        ConsoleOutput.WriteLine(ConsoleType.Error,
                                                $"The type ~w~{commandParameters[i].ParameterType}~;~ can't be used as command parameter!");
                        return;
                    }
                    catch
                    {
                        ConsoleOutput.WriteLine(ConsoleType.Error,
                                                $"Invalid type given for parameter {commandParameters[i].Name}.");
                        return;
                    }
                }

                // Not enough parameter values -> message & next;
                if (commandParameters.Count(info => !info.IsOptional) > parameterValues.Count)
                {
                    ConsoleOutput.WriteLine(ConsoleType.ConsoleCommand,
                                            $"Incorrect parameter values for the command ~o~{enteredCommand}~;~. " +
                                            $"Type ~b~\"/help {enteredCommand}\"~;~ for more information.");
                    return;
                }

                // Add optional parameters if not given, to parametersValues
                if (commandParameters.Length != parameterValues.Count)
                {
                    for (int i = commandParameters.Length - parameterValues.Count; i < commandParameters.Length; i++)
                    {
                        parameterValues.Add(commandParameters[i].DefaultValue);
                    }
                }

                //TODO: check for optional parameters needed

                // Invoke command
                command.MethodInfo.Invoke(command.ClassInstance, parameterValues.ToArray());
                return;
            }

            ConsoleOutput.WriteLine(ConsoleType.Error, $"~w~No command found for ~r~\"{consoleStringParts[0]}\"~w~!");
        }
Esempio n. 13
0
        /// <summary>
        ///     Inspects a class for Commands.
        /// </summary>
        /// <param name="moduleInstance">The instance of the module wich should be inspected.</param>
        internal static void InspectModule(object moduleInstance)
        {
            List <ConsoleCommand> validCommands   = new List <ConsoleCommand>();
            List <ConsoleCommand> invalidCommands = new List <ConsoleCommand>();

            // Parse commands direct in module
            ParseCommands(moduleInstance);

            // Parse all field & Property infos
            foreach (FieldInfo fieldInfo in moduleInstance.GetType().GetFields())
            {
                ParseMemberInfo(null, fieldInfo, moduleInstance);
            }

            foreach (PropertyInfo propertyInfo in moduleInstance.GetType().GetProperties())
            {
                ParseMemberInfo(propertyInfo, null, moduleInstance);
            }

            // Parse static commands
            ParseStaticCommands();

            // Check for invalid commands & write message if given
            ParseInvalidCommands();
            if (invalidCommands.Any())
            {
                ConsoleOutput.SetPrefix(ConsoleOutput.GetPrefix().Replace(">", "~r~!"));

                foreach (ConsoleCommand invalidCommand in invalidCommands)
                {
                    ConsoleOutput.WriteLine(ConsoleType.ConsoleCommand,
                                            "~r~" + invalidCommand.Command + "~c~ " + invalidCommand.FullName());
                }

                ConsoleOutput.SetPrefix(ConsoleOutput.GetPrefix().Replace("~r~!", ">"));
            }

            // Register commands
            if (validCommands.Any())
            {
                foreach (ConsoleCommand command in validCommands)
                {
                    if (AddToCommands(command)) // On working command
                    {
                        ConsoleOutput.SetPrefix(ConsoleOutput.GetPrefix().Replace(">", "~g~+"));

                        // Highlight important commands
                        string commandColorCode = command.ImportantCommand ? "~#f66e00~" : "~g~";
                        // Command aliases
                        string aliasString =
                            $"{(command.CommandAliases.Any() ? $"~w~({commandColorCode}" : "")}{string.Join($"~w~, {commandColorCode}", command.CommandAliases)}{(command.CommandAliases.Any() ? "~w~)" : "")}";

                        ConsoleOutput.WriteLine(ConsoleType.ConsoleCommand,
                                                $"{commandColorCode}{command.Command} {aliasString} ~c~{command.FullName()}");

                        // Description
                        if (!string.IsNullOrEmpty(command.Description))
                        {
                            string currentPrefix = ConsoleOutput.GetPrefix();
                            ConsoleOutput.SetPrefix("\t\t~c~ > ~;~");
                            ConsoleOutput.WriteLine(ConsoleType.ConsoleCommand, command.Description);
                            ConsoleOutput.SetPrefix(currentPrefix);
                        }
                    }
                    else // on warnings
                    {
                        ConsoleOutput.SetPrefix(ConsoleOutput.GetPrefix().Replace(">", "~o~?"));
                        ConsoleOutput.WriteLine(ConsoleType.ConsoleCommand,
                                                "~o~" + command.Command + "~c~ " + command.FullName());
                    }

                    ConsoleOutput.SetPrefix(ConsoleOutput.GetPrefix().Replace("~g~+", ">").Replace("~o~?", ">"));
                }
            }

            void ParseInvalidCommands()
            {
                foreach (Type type in moduleInstance.GetType().Assembly.GetTypes())
                {
                    foreach (MethodInfo methodInfo in type.GetMethods())
                    {
                        object[] attributes = methodInfo.GetCustomAttributes(typeof(ConsoleCommand), true);

                        if (attributes.Length <= 0)
                        {
                            continue;
                        }

                        foreach (object commandObject in attributes)
                        {
                            // Method is registered as valid -> next.
                            if (validCommands.Any(cmd => cmd.MethodInfo == methodInfo))
                            {
                                continue;
                            }

                            ConsoleCommand command = (ConsoleCommand)commandObject;

                            // Save MethodInfo and Class instance
                            command.MethodInfo = methodInfo;
                            invalidCommands.Add(command);
                        }
                    }
                }
            }

            void ParseStaticCommands()
            {
                foreach (Type type in moduleInstance.GetType().Assembly.GetTypes())
                {
                    foreach (MethodInfo methodInfo in type.GetMethods()
                             .Where(info => info.IsStatic && info.IsPublic && !info.IsConstructor))
                    {
                        object[] attributes = methodInfo.GetCustomAttributes(typeof(ConsoleCommand), true);

                        if (attributes.Length <= 0)
                        {
                            continue;
                        }

                        foreach (object commandObject in attributes)
                        {
                            ConsoleCommand command = (ConsoleCommand)commandObject;

                            // Save MethodInfo and Class instance
                            command.MethodInfo    = methodInfo;
                            command.ClassInstance = null;
                            validCommands.Add(command);
                        }
                    }
                }
            }

            void ParseCommands(object instance)
            {
                foreach (MethodInfo methodInfo in instance.GetType().GetMethods()
                         .Where(info => !info.IsStatic && info.IsPublic && !info.IsConstructor))
                {
                    object[] attributes = methodInfo.GetCustomAttributes(typeof(ConsoleCommand), true);

                    if (attributes.Length <= 0)
                    {
                        continue;
                    }

                    foreach (object commandObject in attributes)
                    {
                        ConsoleCommand command = (ConsoleCommand)commandObject;

                        // Save MethodInfo and Class instance
                        command.MethodInfo    = methodInfo;
                        command.ClassInstance = instance;
                        validCommands.Add(command);
                    }
                }
            }

            void ParseMemberInfo(PropertyInfo propertyInfo, FieldInfo fieldInfo, object classInstance)
            {
                object instance = propertyInfo?.GetValue(classInstance) ?? fieldInfo?.GetValue(classInstance);

                if (instance == null ||
                    instance.GetType().Assembly != moduleInstance.GetType().Assembly || !instance.GetType().IsClass)
                {
                    return;
                }

                // Search for commands
                ParseCommands(instance);
                foreach (FieldInfo field in instance.GetType().GetFields())
                {
                    ParseMemberInfo(null, field, instance);
                }

                foreach (PropertyInfo property in instance.GetType().GetProperties())
                {
                    ParseMemberInfo(property, null, instance);
                }
            }
        }