Minecraft-Console-Client/MinecraftClient/Settings.cs

2383 lines
95 KiB
C#
Raw Normal View History

TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
using System;
using System.Collections.Generic;
2022-10-05 15:02:30 +08:00
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MinecraftClient.Protocol;
2022-10-05 15:02:30 +08:00
using MinecraftClient.Proxy;
using Tomlet;
using Tomlet.Attributes;
using Tomlet.Models;
using static MinecraftClient.Settings.AppVarConfigHelper;
using static MinecraftClient.Settings.ChatBotConfigHealper;
using static MinecraftClient.Settings.ChatFormatConfigHelper;
2022-12-11 13:00:19 +08:00
using static MinecraftClient.Settings.ConsoleConfigHealper;
2022-10-06 14:53:05 +08:00
using static MinecraftClient.Settings.HeadCommentHealper;
2022-10-05 15:02:30 +08:00
using static MinecraftClient.Settings.LoggingConfigHealper;
2024-04-16 21:21:08 +03:00
using static MinecraftClient.Settings.MainConfigHelper;
using static MinecraftClient.Settings.MainConfigHelper.MainConfig;
using static MinecraftClient.Settings.MainConfigHelper.MainConfig.AdvancedConfig;
2022-10-05 15:02:30 +08:00
using static MinecraftClient.Settings.MCSettingsConfigHealper;
using static MinecraftClient.Settings.SignatureConfigHelper;
namespace MinecraftClient
{
public static class Settings
{
2022-10-05 19:39:21 +08:00
private const int CommentsAlignPosition = 45;
2022-10-06 14:53:05 +08:00
private readonly static Regex CommentRegex = new(@"^(.*)\s?#\s\$([\w\.]+)\$\s*$$", RegexOptions.Compiled);
2022-12-11 13:00:19 +08:00
// Other Settings
public const string TranslationsFile_Version = "1.19.3";
public const string TranslationsFile_Website_Index = "https://piston-meta.mojang.com/v1/packages/c492375ded5da34b646b8c5c0842a0028bc69cec/2.json";
public const string TranslationsFile_Website_Download = "https://resources.download.minecraft.net";
Add Mailer bot (#1108) * Update for the mail script. As requested, I added the synchronization between the config debugmessage bool and the one in the script. Furthermore, I added a way to send anonymous mails by writing "tellonym". The messages are saved as normal mails, which lets them count to the mail cap, due to the fact that the host knows the sender. I added the script to the chat bots because of the problems, that the scripts have with serialization. Instead of rewriting the whole serialization part, my idea was to add the script to the other chat bots, to avoid the compiling issues. Then the serialization would work perfectly fine. Then you could remove the option class at some point and move all the settings to the config file with the addition to activate the whole script. * Correction of debug message loading. The object was missing and the change would be overridden a few lines later. * Update McClient.cs * Add Mail to config file * Correcting the safe file. * Small correction of Settings.c * Update Mailscript Added a failsafe version of the path changing commands. If a path could not be found, an error will be created and the path will be reseted to standart, to avoid endless chains of errors. * Fix for the mail script Removed a wrong option call. Removed the debug_msg condition around the path functions. => Users are aware of what happened (if they see the error) although they turned off debug_msg. * Added some features. Added a try statement to all number changing commands. Added a command to list all moderators to the console. * Serialization Fix There was a chance, that if two bots work on one file, and two users send messages in a short time period, that one bot deserializes the message and then the other bot deserialize the same file, before the other one could save its changes. This would lead to one message disappearing, because one bot never deserialized this message. For this I changed the whole serialization process. All changes are now committed after the interval and not after an incoming mail command directly. All mails are safed temporarily in cache and get serialized after the interval. Due to this changes, you can determit when the individual bot changes the file (there are no more direct interactions with the file after a command, which lead to a certain randomness). Furthermore you can now set an interval of e.g. 2 mins and reset the interval of one bot with "resettimer" after one minute so that the bots won't disturb eachother and no files get lost. * My idea of a manual. This is my idea of a manual for the bot. Improvements of my language / further ideas are welcome! :D * addIgnored [NAME] and removeIgnored[NAME] Added an ignored list. Moderators can add players to the list. The bot won't react to them and just log to the console that they are ignored, everytime they are sending a message, to ensure that they are not accidently ignored. (Just if debug_msg is active.) Especially useful if there are other chat bots on the server, which spam many messages that aren't useful for the mail system. Or block spammers etc. * Add the three commands to the manual. Added addignored, removeignored and getignored to the manual. * Remove moderators. Implement Console Control. Due to security concerns, I converted all moderator commands to console internal commands. Thereby only the host can change crucial settings. Special thanks to ORelio for the hint! * Added empty statement check Added if to all commands, where the syntax is not already protected by a try, so that an incorrect syntax (Empty args[] due to missing statement) won't crash the script. * Changed the serialization fail If the programm can't safe the file, because of some strange character for instance, it first tries to change the path back to normal and if this not helps, it creates a new, file. * toggle mail sending/receiving Add an option to turn mailsending and the listening to commands in chat on/off. * Updated manual. - Removed moderator commands. - Removed moderator part in the network manual + added the two new commands + added a waring for nick plugins and minecraft renames + added a small syntax example * Updated the Settings.cs file. * Smaller fixes and additions + improved command reading of 'mail' & 'tellonym' + sorted internal commands alphabetically + host can set a maximum message length + host can accept commands from public chat + host can decide if 'self mailing' (mailing yourself) is accepted + new order makes 'getsettings' easier to read + new internal commands to toggle 'publiccommands' and 'selfmailing' as well as the maximum mail size - removed the old command interpreter * Small improvements and additions Added a few commands and settings * Completing getsettings + added 'publiccomands' * Completed getsettings + Added 'publiccommand' to 'getsettings' * Removed single bolean, added Dictionary - removed all boleans in the option class - removed all functions relating them + added Dictionary for the booleans + added a single function to set/toggle all booleans * Removed Commands, added interpreter - Removed all Register commands - removed all integer methods + added a single mail command + added integer dictionary + added integer handling similar like bool handling * Small fix + Changed the numbers in several methods to adjust them to the new syntax. - removed parameters in several methods, because they got unneccesary * Even smaller fix + Sorted 'getsettings' alphabetically + corrected a typo * New Serialization method. Now serializing through the .INI format! Thanks to ORelio, who helped me a lot! :) * Added different time Added the option to switch between utc and the time of the local machine for timestamps. * Made timeinutc serializable Added the bool to the serialization method. * Adding the INIFile.cs For Dictionary serialization. * Reworked ignore feature Ignored players are now serialized in a file and reloaded, after the bot enters a server. * Mailer bot refactoring Rename Mail to Mailer Move options to MinecraftClient.ini Make the bot much simpler by removing some settings Create specific MailDatabase and IgnoreList classes However the core functionality for users is the same Settings removed: - allow_sendmail: Cannot use Mailer if it's disabled - allow_receivemail: Cannot use Mailer if it's disabled - path_setting: Settings moved to MinecraftClient.ini - debug_msg: MCC already has a setting for that with LogDebugToConsole() - auto_respawn: MCC already has a built-in auto-respawn feature - allow_selfmail: Is it really necessary to block self mails? ;) - maxcharsinmsg: Automatically calculated based on max chat message length - timeinutc: DateTime is not show to the recipient so I think it's not absolutely necessary - interval_sendmail: Set to 10 seconds for now Internal Commands removed: - changemailpath: Now a static setting in config - changesettingspath: Now a static setting in config - updatemails: Already updated every 10 seconds - getsettings: Shown on startup with debugmessages=true - resettimer: Seems only useful for debugging - setbool: Settings are static in config file - setinteger: Settings are static in config file All user commands are retained: - mail - tellonym * Reload database for mailer network feature * Merge Mail documentation to Readme.md Co-authored-by: ORelio <oreliogitantispam.l0gin@spamgourmet.com>
2020-08-03 21:44:39 +02:00
public const string TranslationProjectUrl = "https://crowdin.com/project/minecraft-console-client";
2026-03-23 14:29:04 +01:00
public const int ClientTicksPerSecond = 20;
public const int ClientTickIntervalMilliseconds = 1000 / ClientTicksPerSecond;
2022-10-06 14:53:05 +08:00
2022-10-05 15:02:30 +08:00
public static GlobalConfig Config = new();
public static class InternalConfig
{
2022-10-05 15:02:30 +08:00
public static string ServerIP = String.Empty;
public static ushort ServerPort = 25565;
public static AccountInfoConfig Account = new();
2022-10-16 20:37:07 +08:00
2022-10-05 15:02:30 +08:00
public static string Username = string.Empty;
public static string MinecraftVersion = string.Empty;
public static bool InteractiveMode = true;
public static bool GravityEnabled = true;
public static bool KeepAccountSettings = false;
public static bool KeepServerSettings = false;
}
2022-10-05 15:02:30 +08:00
public class GlobalConfig
{
[TomlPrecedingComment("$Head$")]
2022-10-06 14:53:05 +08:00
public HeadComment Head
{
get { return HeadCommentHealper.Config; }
set { HeadCommentHealper.Config = value; HeadCommentHealper.Config.OnSettingUpdate(); }
}
2022-10-05 15:02:30 +08:00
public MainConfig Main
{
2024-04-16 21:21:08 +03:00
get { return MainConfigHelper.Config; }
set { MainConfigHelper.Config = value; MainConfigHelper.Config.OnSettingUpdate(); }
2022-10-05 15:02:30 +08:00
}
[TomlPrecedingComment("$Signature$")]
2022-10-05 15:02:30 +08:00
public SignatureConfig Signature
{
get { return SignatureConfigHelper.Config; }
set { SignatureConfigHelper.Config = value; SignatureConfigHelper.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$Logging$")]
2022-10-05 15:02:30 +08:00
public LoggingConfig Logging
{
get { return LoggingConfigHealper.Config; }
set { LoggingConfigHealper.Config = value; LoggingConfigHealper.Config.OnSettingUpdate(); }
}
2022-12-11 13:00:19 +08:00
public ConsoleConfig Console
{
get { return ConsoleConfigHealper.Config; }
set { ConsoleConfigHealper.Config = value; ConsoleConfigHealper.Config.OnSettingUpdate(); }
}
2022-10-05 15:02:30 +08:00
public AppVarConfig AppVar
{
get { return AppVarConfigHelper.Config; }
set { AppVarConfigHelper.Config = value; AppVarConfigHelper.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$Proxy$")]
2022-10-05 15:02:30 +08:00
public ProxyHandler.Configs Proxy
{
get { return ProxyHandler.Config; }
set { ProxyHandler.Config = value; ProxyHandler.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$MCSettings$")]
2022-10-05 15:02:30 +08:00
public MCSettingsConfig MCSettings
{
get { return MCSettingsConfigHealper.Config; }
set { MCSettingsConfigHealper.Config = value; MCSettingsConfigHealper.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatFormat$")]
2022-10-05 15:02:30 +08:00
public ChatFormatConfig ChatFormat
{
get { return ChatFormatConfigHelper.Config; }
set { ChatFormatConfigHelper.Config = value; ChatFormatConfigHelper.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot$")]
2022-10-05 15:02:30 +08:00
public ChatBotConfig ChatBot
{
get { return ChatBotConfigHealper.Config; }
set { ChatBotConfigHealper.Config = value; }
}
}
/// <summary>
/// Structured result returned by <see cref="LoadFromFile(string, bool)"/>.
/// </summary>
public readonly struct ConfigLoadResult
{
public bool Success { get; init; }
public bool NeedWriteDefault { get; init; }
/// <summary>True when a pre-TOML legacy config was detected, backed up, and a fresh default is needed.</summary>
public bool IsLegacyUpgrade { get; init; }
/// <summary>Non-null when the load failed due to a parse/IO error (not a legacy upgrade).</summary>
public string? ErrorMessage { get; init; }
/// <summary>Path where the old config was backed up (legacy upgrade case).</summary>
public string? LegacyBackupPath { get; init; }
}
public static ConfigLoadResult LoadFromFile(string filepath, bool keepAccountAndServerSettings = false)
2022-10-05 15:02:30 +08:00
{
bool keepAccountSettings = InternalConfig.KeepAccountSettings;
bool keepServerSettings = InternalConfig.KeepServerSettings;
if (keepAccountAndServerSettings)
InternalConfig.KeepAccountSettings = InternalConfig.KeepServerSettings = true;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
2022-10-05 15:02:30 +08:00
TomlDocument document;
try
{
document = TomlParser.ParseFile(filepath);
Thread.CurrentThread.CurrentCulture = Program.ActualCulture;
2022-10-05 19:16:33 +08:00
Config = TomletMain.To<GlobalConfig>(document);
2022-10-05 15:02:30 +08:00
}
catch (Exception ex)
{
Thread.CurrentThread.CurrentCulture = Program.ActualCulture;
try
{
2022-10-05 15:02:30 +08:00
string configString = File.ReadAllText(filepath);
if (configString.Contains("Some settings missing here after an upgrade?"))
{
2022-11-07 11:15:19 +08:00
string newFilePath = Path.ChangeExtension(filepath, ".old.ini");
2022-10-05 15:02:30 +08:00
File.Copy(filepath, newFilePath, true);
return new ConfigLoadResult
{
Success = false,
NeedWriteDefault = true,
IsLegacyUpgrade = true,
LegacyBackupPath = newFilePath
};
}
}
2022-10-05 15:02:30 +08:00
catch { }
return new ConfigLoadResult
{
Success = false,
NeedWriteDefault = false,
ErrorMessage = ex.GetFullMessage()
};
2022-10-05 15:02:30 +08:00
}
finally
{
if (!keepAccountSettings)
InternalConfig.KeepAccountSettings = false;
if (!keepServerSettings)
InternalConfig.KeepServerSettings = false;
}
return new ConfigLoadResult { Success = true, NeedWriteDefault = false };
2022-10-05 15:02:30 +08:00
}
public static void WriteToFile(string filepath, bool backupOldFile)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
2022-10-05 15:02:30 +08:00
string tomlString = TomletMain.TomlStringFrom(Config);
Thread.CurrentThread.CurrentCulture = Program.ActualCulture;
2022-10-05 15:02:30 +08:00
string[] tomlList = tomlString.Split('\n');
StringBuilder newConfig = new();
foreach (string line in tomlList)
{
2022-10-06 14:53:05 +08:00
Match matchComment = CommentRegex.Match(line);
if (matchComment.Success && matchComment.Groups.Count == 3)
2022-10-05 15:02:30 +08:00
{
2022-10-06 14:53:05 +08:00
string config = matchComment.Groups[1].Value, comment = matchComment.Groups[2].Value;
2022-10-05 15:02:30 +08:00
if (config.Length > 0)
2022-10-05 19:39:21 +08:00
newConfig.Append(config).Append(' ', Math.Max(1, CommentsAlignPosition - config.Length) - 1);
string? comment_trans = ConfigComments.ResourceManager.GetString(comment);
if (string.IsNullOrEmpty(comment_trans))
newConfig.Append("# ").AppendLine(comment.ReplaceLineEndings());
else
newConfig.Append("# ").AppendLine(comment_trans.Replace("\n", "\n# ").ReplaceLineEndings());
2022-10-05 15:02:30 +08:00
}
else
{
newConfig.AppendLine(line);
}
}
bool needUpdate = true;
2022-10-06 18:12:32 +08:00
byte[] newConfigByte = Encoding.UTF8.GetBytes(newConfig.ToString());
2022-10-05 15:02:30 +08:00
if (File.Exists(filepath))
{
try
{
2022-10-06 18:12:32 +08:00
if (new FileInfo(filepath).Length == newConfigByte.Length)
if (File.ReadAllBytes(filepath).SequenceEqual(newConfigByte))
needUpdate = false;
2022-10-05 15:02:30 +08:00
}
catch { }
}
if (needUpdate)
{
2022-10-06 14:53:05 +08:00
bool backupSuccessed = true;
2022-10-05 15:02:30 +08:00
if (backupOldFile && File.Exists(filepath))
2022-10-06 14:53:05 +08:00
{
string backupFilePath = Path.ChangeExtension(filepath, ".backup.ini");
try { File.Copy(filepath, backupFilePath, true); }
catch (Exception ex)
{
backupSuccessed = false;
ConsoleIO.WriteLineFormatted("§c" + string.Format(Translations.config_backup_fail, backupFilePath));
2022-10-06 14:53:05 +08:00
ConsoleIO.WriteLine(ex.Message);
}
}
if (backupSuccessed)
{
2022-10-06 18:12:32 +08:00
try { File.WriteAllBytes(filepath, newConfigByte); }
2022-10-06 14:53:05 +08:00
catch (Exception ex)
{
ConsoleIO.WriteLineFormatted("§c" + string.Format(Translations.config_write_fail, filepath));
2022-10-06 14:53:05 +08:00
ConsoleIO.WriteLine(ex.Message);
}
}
}
}
/// <summary>
/// Load settings from the command line
/// </summary>
/// <param name="args">Command-line arguments</param>
/// <exception cref="System.ArgumentException">Thrown on invalid arguments</exception>
public static void LoadArguments(string[] args)
{
int positionalIndex = 0;
bool skipPassword = false;
foreach (string argument in args)
{
if (argument.StartsWith("--"))
{
//Load settings as --setting=value and --section.setting=value
if (!argument.Contains('='))
throw new ArgumentException(string.Format(Translations.error_setting_argument_syntax, argument));
string argumentBody = argument[2..];
int separatorIndex = argumentBody.IndexOf('=');
if (separatorIndex < 1)
throw new ArgumentException(string.Format(Translations.error_setting_argument_syntax, argument));
string settingName = argumentBody[..separatorIndex].Trim();
string settingValue = argumentBody[(separatorIndex + 1)..].Trim();
if (!TryApplyArgumentSetting(settingName, settingValue))
throw new ArgumentException(string.Format(Translations.error_setting_argument_syntax, argument));
}
else if (argument.StartsWith("-") && argument.Length > 1)
{
//Keep single dash arguments as unsupported for now (future use)
throw new ArgumentException(string.Format(Translations.error_setting_argument_syntax, argument));
}
else
{
switch (positionalIndex)
{
2022-10-11 22:47:06 +02:00
case 0:
if (Config.Main.Advanced.AccountList.TryGetValue(argument, out AccountInfoConfig accountInfo))
{
InternalConfig.Account = accountInfo;
skipPassword = true;
}
else
{
InternalConfig.Account.Login = argument;
}
InternalConfig.KeepAccountSettings = true;
2022-10-05 15:02:30 +08:00
break;
2022-10-11 22:47:06 +02:00
case 1:
if (!skipPassword)
InternalConfig.Account.Password = argument;
2022-10-05 15:02:30 +08:00
break;
2022-10-11 22:47:06 +02:00
case 2:
Config.Main.SetServerIP(new MainConfig.ServerInfoConfig(argument), true);
InternalConfig.KeepServerSettings = true;
2022-10-05 15:02:30 +08:00
break;
2022-10-11 22:47:06 +02:00
case 3:
2022-10-05 15:02:30 +08:00
// SingleCommand = argument;
break;
}
positionalIndex++;
}
}
}
private static readonly string[][] s_argumentSettingSearchPrefixes =
[
[],
["Main", "Advanced"],
["Main", "General"],
["Main"],
["Logging"],
["Console", "General"],
["Console", "CommandSuggestion"],
["Console"],
["MCSettings"],
["ChatFormat"],
["ChatBot"],
["Signature"],
["Proxy"],
["AppVar"]
];
private static bool TryApplyArgumentSetting(string settingPath, string settingValue)
{
if (string.IsNullOrWhiteSpace(settingPath))
return false;
string[] settingParts = settingPath
.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (settingParts.Length == 0)
return false;
HashSet<string> triedPaths = new(StringComparer.Ordinal);
foreach (string[] prefix in s_argumentSettingSearchPrefixes)
{
string[] fullPath = [.. prefix, .. settingParts];
string pathKey = string.Join('.', fullPath.Select(NormalizeArgumentToken));
if (!triedPaths.Add(pathKey))
continue;
if (!TryResolveArgumentSettingPath(fullPath, out object owner, out MemberInfo member, out List<object> objectPath))
continue;
if (!TryConvertArgumentValue(settingValue, GetMemberType(member), out object? convertedValue))
return false;
if (!TrySetMemberValue(owner, member, convertedValue))
return false;
ApplyOnSettingUpdate(objectPath);
return true;
}
return false;
}
private static bool TryResolveArgumentSettingPath(string[] fullPath, out object owner, out MemberInfo member, out List<object> objectPath)
{
owner = Config;
objectPath = [owner];
member = null!;
for (int i = 0; i < fullPath.Length; i++)
{
if (!TryGetArgumentMember(owner.GetType(), fullPath[i], out MemberInfo currentMember))
return false;
if (i == fullPath.Length - 1)
{
member = currentMember;
return true;
}
object? nextObject = GetMemberValue(owner, currentMember);
if (nextObject is null)
return false;
owner = nextObject;
objectPath.Add(owner);
}
return false;
}
private static bool TryGetArgumentMember(Type ownerType, string token, out MemberInfo member)
{
ArgumentNullException.ThrowIfNull(ownerType);
string normalizedToken = NormalizeArgumentToken(token);
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
foreach (PropertyInfo property in ownerType.GetProperties(flags))
{
if (!property.CanRead || !property.CanWrite || property.GetIndexParameters().Length > 0)
continue;
if (NormalizeArgumentToken(property.Name) == normalizedToken)
{
member = property;
return true;
}
}
foreach (FieldInfo field in ownerType.GetFields(flags))
{
if (NormalizeArgumentToken(field.Name) == normalizedToken)
{
member = field;
return true;
}
}
member = null!;
return false;
}
private static string NormalizeArgumentToken(string token)
{
return ToLowerIfNeed(token.Replace("_", string.Empty, StringComparison.Ordinal)
.Replace("-", string.Empty, StringComparison.Ordinal));
}
private static Type GetMemberType(MemberInfo member)
{
return member switch
{
PropertyInfo property => property.PropertyType,
FieldInfo field => field.FieldType,
_ => throw new ArgumentException($"Unsupported member type: {member.MemberType}", nameof(member))
};
}
private static object? GetMemberValue(object owner, MemberInfo member)
{
return member switch
{
PropertyInfo property => property.GetValue(owner),
FieldInfo field => field.GetValue(owner),
_ => null
};
}
private static bool TrySetMemberValue(object owner, MemberInfo member, object? value)
{
switch (member)
{
case PropertyInfo property:
property.SetValue(owner, value);
return true;
case FieldInfo field:
field.SetValue(owner, value);
return true;
default:
return false;
}
}
private static bool TryConvertArgumentValue(string input, Type targetType, out object? converted)
{
Type effectiveType = Nullable.GetUnderlyingType(targetType) ?? targetType;
if (effectiveType == typeof(string))
{
converted = input;
return true;
}
if (effectiveType == typeof(bool))
{
bool success = bool.TryParse(input, out bool value);
converted = value;
return success;
}
if (effectiveType.IsEnum)
{
bool success = Enum.TryParse(effectiveType, input, true, out object? value);
converted = value;
return success;
}
try
{
converted = Convert.ChangeType(input, effectiveType, CultureInfo.InvariantCulture);
return true;
}
catch (InvalidCastException)
{
converted = null;
return false;
}
catch (FormatException)
{
converted = null;
return false;
}
catch (OverflowException)
{
converted = null;
return false;
}
}
private static void ApplyOnSettingUpdate(List<object> objectPath)
{
HashSet<object> calledObjects = new(ReferenceEqualityComparer.Instance);
for (int i = objectPath.Count - 1; i >= 0; i--)
{
object target = objectPath[i];
if (!calledObjects.Add(target))
continue;
MethodInfo? onSettingUpdate = target.GetType().GetMethod(nameof(MainConfig.OnSettingUpdate), BindingFlags.Instance | BindingFlags.Public, []);
onSettingUpdate?.Invoke(target, null);
}
}
2022-10-06 14:53:05 +08:00
public static class HeadCommentHealper
{
public static HeadComment Config = new();
[TomlDoNotInlineObject]
public class HeadComment
{
[TomlProperty("Current Version")]
2022-10-06 18:12:32 +08:00
public string CurrentVersion { get; set; } = Program.BuildInfo ?? "Development Build";
2022-10-11 22:47:06 +02:00
2022-10-06 14:53:05 +08:00
[TomlProperty("Latest Version")]
public string LatestVersion { get; set; } = "Unknown";
public void OnSettingUpdate()
{
2022-10-06 18:12:32 +08:00
CurrentVersion = Program.BuildInfo ?? "Development Build";
2022-10-06 14:53:05 +08:00
LatestVersion ??= "Unknown";
}
}
}
2024-04-16 21:21:08 +03:00
public static class MainConfigHelper
{
2022-10-05 15:02:30 +08:00
public static MainConfig Config = new();
[TomlDoNotInlineObject]
public class MainConfig
{
2022-10-05 15:02:30 +08:00
public GeneralConfig General = new();
[TomlPrecedingComment("$Main.Advanced$")]
2022-10-05 15:02:30 +08:00
public AdvancedConfig Advanced = new();
2022-10-05 15:02:30 +08:00
[NonSerialized]
public static readonly string[] AvailableLang =
{
"af_za", "ar_sa", "ast_es", "az_az", "ba_ru", "bar", "be_by", "bg_bg",
"br_fr", "brb", "bs_ba", "ca_es", "cs_cz", "cy_gb", "da_dk", "de_at",
"de_ch", "de_de", "el_gr", "en_au", "en_ca", "en_gb", "en_nz", "en_pt",
"en_ud", "en_us", "enp", "enws", "eo_uy", "es_ar", "es_cl", "es_ec",
"es_es", "es_mx", "es_uy", "es_ve", "esan", "et_ee", "eu_es", "fa_ir",
"fi_fi", "fil_ph", "fo_fo", "fr_ca", "fr_fr", "fra_de", "fur_it", "fy_nl",
"ga_ie", "gd_gb", "gl_es", "haw_us", "he_il", "hi_in", "hr_hr", "hu_hu",
"hy_am", "id_id", "ig_ng", "io_en", "is_is", "isv", "it_it", "ja_jp",
"jbo_en", "ka_ge", "kk_kz", "kn_in", "ko_kr", "ksh", "kw_gb", "la_la",
"lb_lu", "li_li", "lmo", "lol_us", "lt_lt", "lv_lv", "lzh", "mk_mk",
2022-12-11 13:00:19 +08:00
"mn_mn", "ms_my", "mt_mt", "nah", "nds_de", "nl_be", "nl_nl", "nn_no",
"no_no", "oc_fr", "ovd", "pl_pl", "pt_br", "pt_pt", "qya_aa", "ro_ro",
"rpr", "ru_ru", "ry_ua", "se_no", "sk_sk", "sl_si", "so_so", "sq_al",
"sr_sp", "sv_se", "sxu", "szl", "ta_in", "th_th", "tl_ph", "tlh_aa",
"tok", "tr_tr", "tt_ru", "uk_ua", "val_es", "vec_it", "vi_vn", "yi_de",
"yo_ng", "zh_cn", "zh_hk", "zh_tw", "zlm_arab"
2022-10-05 15:02:30 +08:00
};
/// <summary>
/// Load server information in ServerIP and ServerPort variables from a "serverip:port" couple or server alias
/// </summary>
/// <returns>True if the server IP was valid and loaded, false otherwise</returns>
public bool SetServerIP(ServerInfoConfig serverInfo, bool checkAlias)
{
2022-11-05 21:15:16 +08:00
string[] sip = serverInfo.Host.Split(new[] { ":", "" }, StringSplitOptions.None);
string host = ToLowerIfNeed(sip[0]);
2022-10-05 15:02:30 +08:00
ushort port = 25565;
2022-11-05 21:15:16 +08:00
if (serverInfo.Port.HasValue)
2022-10-05 15:02:30 +08:00
{
2022-11-05 21:15:16 +08:00
port = serverInfo.Port.Value;
}
else if (sip.Length > 1)
{
try { port = Convert.ToUInt16(sip[1]); }
catch (FormatException) { return false; }
2022-10-05 15:02:30 +08:00
}
2022-10-05 15:02:30 +08:00
if (host == "localhost" || host.Contains('.'))
{
//Server IP (IP or domain names contains at least a dot)
2022-11-05 21:15:16 +08:00
if (sip.Length == 1 && !serverInfo.Port.HasValue && host.Contains('.') && host.Any(c => char.IsLetter(c)) &&
Settings.Config.Main.Advanced.ResolveSrvRecords != ResolveSrvRecordType.no)
2022-10-05 15:02:30 +08:00
//Domain name without port may need Minecraft SRV Record lookup
ProtocolHandler.MinecraftServiceLookup(ref host, ref port);
InternalConfig.ServerIP = host;
InternalConfig.ServerPort = port;
return true;
}
2022-11-05 21:15:16 +08:00
else if (checkAlias && Advanced.ServerList.TryGetValue(sip[0], out ServerInfoConfig serverStr2))
2022-10-05 15:02:30 +08:00
{
return SetServerIP(serverStr2, false);
}
2022-10-05 15:02:30 +08:00
return false;
}
2022-10-05 15:02:30 +08:00
public void OnSettingUpdate()
{
ConsoleIO.EnableTimestamps = Advanced.Timestamps;
2022-10-05 15:02:30 +08:00
InternalConfig.InteractiveMode = !Advanced.ExitOnFailure;
2022-10-05 15:02:30 +08:00
General.Account.Login ??= string.Empty;
General.Account.Password ??= string.Empty;
if (!InternalConfig.KeepAccountSettings)
{
if (Advanced.AccountList.TryGetValue(General.Account.Login, out AccountInfoConfig account))
InternalConfig.Account = account;
else
InternalConfig.Account = General.Account;
}
2022-10-05 15:02:30 +08:00
General.Server.Host ??= string.Empty;
2022-10-05 15:02:30 +08:00
if (Advanced.MessageCooldown < 0)
Advanced.MessageCooldown = 0;
if (Advanced.MaxChatMessageLength < 0)
Advanced.MaxChatMessageLength = 0;
else if (Advanced.MaxChatMessageLength > 32767)
Advanced.MaxChatMessageLength = 32767;
if (Advanced.MaxChatMessageLength > 0)
ConsoleIO.WriteLineFormatted("§e[Settings] MaxChatMessageLength is set to " + Advanced.MaxChatMessageLength + ". Setting this incorrectly may cause you to be kicked from the server.");
2022-10-05 15:02:30 +08:00
if (Advanced.TcpTimeout < 1)
Advanced.TcpTimeout = 1;
2022-10-05 15:02:30 +08:00
if (Advanced.MovementSpeed < 1)
Advanced.MovementSpeed = 1;
if (!Advanced.LoadMccTranslation)
{
2022-12-11 13:00:19 +08:00
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Program.ActualCulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
2022-10-05 15:02:30 +08:00
Advanced.Language = Regex.Replace(Advanced.Language, @"[^-^_^\w^*\d]", string.Empty).Replace('-', '_');
2022-10-06 18:12:32 +08:00
Advanced.Language = ToLowerIfNeed(Advanced.Language);
2022-10-05 15:02:30 +08:00
if (!AvailableLang.Contains(Advanced.Language))
{
Advanced.Language = GetDefaultGameLanguage();
ConsoleIO.WriteLogLine("[Settings] " + Translations.config_Main_Advanced_language_invaild);
}
if (!InternalConfig.KeepServerSettings)
{
if (!string.IsNullOrWhiteSpace(General.Server.Host))
2022-10-05 15:02:30 +08:00
{
string[] sip = General.Server.Host.Split(new[] { ":", "" }, StringSplitOptions.None);
2022-11-05 21:30:15 +08:00
General.Server.Host = sip[0];
InternalConfig.ServerIP = General.Server.Host;
if (sip.Length > 1)
{
try { General.Server.Port = Convert.ToUInt16(sip[1]); }
catch (FormatException) { }
}
2022-10-05 15:02:30 +08:00
}
if (General.Server.Port.HasValue)
InternalConfig.ServerPort = General.Server.Port.Value;
else
SetServerIP(General.Server, true);
}
2022-10-09 07:57:28 +08:00
for (int i = 0; i < Advanced.BotOwners.Count; ++i)
Advanced.BotOwners[i] = ToLowerIfNeed(Advanced.BotOwners[i]);
2022-10-13 19:34:49 +08:00
if (Advanced.MinTerminalWidth < 1)
Advanced.MinTerminalWidth = 1;
if (Advanced.MinTerminalHeight < 1)
Advanced.MinTerminalHeight = 1;
2023-01-13 16:12:10 +08:00
if (Advanced.TemporaryFixBadpacket && !Advanced.TerrainAndMovements)
{
Advanced.TerrainAndMovements = true;
ConsoleIO.WriteLineFormatted("§c[Settings]You need to enable TerrainAndMovements before enabling TemporaryFixBadpacket.");
}
2022-10-05 15:02:30 +08:00
}
[TomlDoNotInlineObject]
public class GeneralConfig
{
[TomlInlineComment("$Main.General.account$")]
2022-10-05 15:02:30 +08:00
public AccountInfoConfig Account = new(string.Empty, string.Empty);
[TomlInlineComment("$Main.General.login$")]
2022-10-05 15:02:30 +08:00
public ServerInfoConfig Server = new(string.Empty);
[TomlInlineComment("$Main.General.server_info$")]
2022-10-05 15:02:30 +08:00
public LoginType AccountType = LoginType.microsoft;
[TomlInlineComment("$Main.General.method$")]
2022-10-05 15:02:30 +08:00
public LoginMethod Method = LoginMethod.mcc;
2023-11-12 21:04:20 +08:00
[TomlInlineComment("$Main.General.AuthlibServer$")]
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
public AuthlibServer AuthServer = new();
[TomlInlineComment("$Main.General.AuthlibUser$")]
public string AuthUser = "";
2023-11-12 21:04:20 +08:00
2022-10-05 15:02:30 +08:00
2023-11-16 00:04:56 +08:00
public enum LoginType { mojang, microsoft,yggdrasil };
2022-10-05 15:02:30 +08:00
public enum LoginMethod { mcc, browser };
}
[TomlDoNotInlineObject]
public class AdvancedConfig
{
[TomlInlineComment("$Main.Advanced.enable_sentry$")]
public bool EnableSentry = true;
[TomlInlineComment("$Main.Advanced.language$")]
2022-12-11 13:00:19 +08:00
public string Language = "en_us";
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Main.Advanced.LoadMccTrans$")]
public bool LoadMccTranslation = true;
[TomlInlineComment("$Main.Advanced.load_resourcepack_translations$")]
public bool LoadResourcePackTranslations = true;
[TomlInlineComment("$Main.Advanced.load_forge_mod_translations$")]
public bool LoadForgeModTranslations = true;
// [TomlInlineComment("$Main.Advanced.console_title$")]
2022-10-05 15:02:30 +08:00
public string ConsoleTitle = "%username%@%serverip% - Minecraft Console Client";
[TomlInlineComment("$Main.Advanced.internal_cmd_char$")]
2022-10-05 15:02:30 +08:00
public InternalCmdCharType InternalCmdChar = InternalCmdCharType.slash;
[TomlInlineComment("$Main.Advanced.message_cooldown$")]
2022-10-06 18:12:32 +08:00
public double MessageCooldown = 1.0;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Main.Advanced.max_chat_message_length$")]
public int MaxChatMessageLength = 0;
[TomlInlineComment("$Main.Advanced.bot_owners$")]
2022-10-05 15:02:30 +08:00
public List<string> BotOwners = new() { "Player1", "Player2" };
[TomlInlineComment("$Main.Advanced.mc_version$")]
2022-10-05 15:02:30 +08:00
public string MinecraftVersion = "auto";
[TomlInlineComment("$Main.Advanced.mc_forge$")]
2023-01-16 14:47:17 +08:00
public ForgeConfigType EnableForge = ForgeConfigType.no;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Main.Advanced.brand_info$")]
2022-10-05 15:02:30 +08:00
public BrandInfoType BrandInfo = BrandInfoType.mcc;
[TomlInlineComment("$Main.Advanced.chatbot_log_file$")]
2022-10-05 15:02:30 +08:00
public string ChatbotLogFile = "";
[TomlInlineComment("$Main.Advanced.private_msgs_cmd_name$")]
2022-10-05 15:02:30 +08:00
public string PrivateMsgsCmdName = "tell";
[TomlInlineComment("$Main.Advanced.show_system_messages$")]
2022-10-05 15:02:30 +08:00
public bool ShowSystemMessages = true;
[TomlInlineComment("$Main.Advanced.show_xpbar_messages$")]
2022-10-05 15:02:30 +08:00
public bool ShowXPBarMessages = true;
[TomlInlineComment("$Main.Advanced.show_chat_links$")]
2022-10-05 15:02:30 +08:00
public bool ShowChatLinks = true;
[TomlInlineComment("$Main.Advanced.show_inventory_layout$")]
2022-10-05 15:02:30 +08:00
public bool ShowInventoryLayout = true;
[TomlInlineComment("$Main.Advanced.show_effect_messages$")]
public bool ShowEffectMessages = true;
[TomlInlineComment("$Main.Advanced.show_effect_names_in_tui$")]
public bool ShowEffectNamesInTUI = false;
2026-04-03 21:15:02 +02:00
[TomlInlineComment("$Main.Advanced.show_github_star_reminder$")]
public bool ShowGithubStarReminder = true;
[TomlInlineComment("$Main.Advanced.terrain_and_movements$")]
2022-10-05 15:02:30 +08:00
public bool TerrainAndMovements = false;
[TomlInlineComment("$Main.Advanced.move_head_while_walking$")]
2022-10-13 19:34:49 +08:00
public bool MoveHeadWhileWalking = true;
[TomlInlineComment("$Main.Advanced.movement_speed$")]
2022-10-13 19:34:49 +08:00
public int MovementSpeed = 2;
[TomlInlineComment("$Main.Advanced.temporary_fix_badpacket$")]
2022-11-01 16:37:50 +08:00
public bool TemporaryFixBadpacket = false;
[TomlInlineComment("$Main.Advanced.inventory_handling$")]
2022-10-05 15:02:30 +08:00
public bool InventoryHandling = false;
[TomlInlineComment("$Main.Advanced.entity_handling$")]
2022-10-05 15:02:30 +08:00
public bool EntityHandling = false;
[TomlInlineComment("$Main.Advanced.session_cache$")]
2022-10-05 15:02:30 +08:00
public CacheType SessionCache = CacheType.disk;
[TomlInlineComment("$Main.Advanced.profilekey_cache$")]
2022-10-05 15:02:30 +08:00
public CacheType ProfileKeyCache = CacheType.disk;
[TomlInlineComment("$Main.Advanced.resolve_srv_records$")]
2022-10-05 15:02:30 +08:00
public ResolveSrvRecordType ResolveSrvRecords = ResolveSrvRecordType.fast;
[TomlPrecedingComment("$Main.Advanced.account_list$")]
2022-10-05 15:02:30 +08:00
public Dictionary<string, AccountInfoConfig> AccountList = new() {
2022-10-05 20:41:37 +08:00
{ "AccountNikename1", new AccountInfoConfig("playerone@email.com", "thepassword") },
{ "AccountNikename2", new AccountInfoConfig("TestBot", "-") },
2022-10-05 15:02:30 +08:00
};
[TomlPrecedingComment("$Main.Advanced.server_list$")]
2022-10-05 15:02:30 +08:00
public Dictionary<string, ServerInfoConfig> ServerList = new() {
2022-10-05 20:41:37 +08:00
{ "ServerAlias1", new ServerInfoConfig("mc.awesomeserver.com") },
{ "ServerAlias2", new ServerInfoConfig("192.168.1.27", 12345) },
2022-10-05 15:02:30 +08:00
};
[TomlInlineComment("$Main.Advanced.player_head_icon$")]
2022-10-05 15:02:30 +08:00
public bool PlayerHeadAsIcon = true;
[TomlInlineComment("$Main.Advanced.exit_on_failure$")]
2022-10-05 15:02:30 +08:00
public bool ExitOnFailure = false;
[TomlInlineComment("$Main.Advanced.script_cache$")]
2022-10-05 15:02:30 +08:00
public bool CacheScript = true;
[TomlInlineComment("$Main.Advanced.timestamps$")]
2022-10-05 15:02:30 +08:00
public bool Timestamps = false;
[TomlInlineComment("$Main.Advanced.auto_respawn$")]
2022-10-05 15:02:30 +08:00
public bool AutoRespawn = false;
[TomlInlineComment("$Main.Advanced.minecraft_realms$")]
2022-10-05 15:02:30 +08:00
public bool MinecraftRealms = false;
[TomlInlineComment("$Main.Advanced.timeout$")]
2022-10-05 15:02:30 +08:00
public int TcpTimeout = 30;
[TomlInlineComment("$Main.Advanced.enable_emoji$")]
2022-10-05 15:02:30 +08:00
public bool EnableEmoji = true;
[TomlInlineComment("$Main.Advanced.MinTerminalWidth$")]
2022-10-13 19:34:49 +08:00
public int MinTerminalWidth = 16;
[TomlInlineComment("$Main.Advanced.MinTerminalHeight$")]
2022-10-13 19:34:49 +08:00
public int MinTerminalHeight = 10;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Main.Advanced.ignore_invalid_playername$")]
public bool IgnoreInvalidPlayerName = true;
2022-10-05 15:02:30 +08:00
/// <summary>
/// Load login/password using an account alias
/// </summary>
/// <returns>True if the account was found and loaded</returns>
public bool SetAccount(string accountAlias)
{
2022-10-05 15:02:30 +08:00
if (AccountList.TryGetValue(accountAlias, out AccountInfoConfig accountInfo))
{
InternalConfig.Account = accountInfo;
return true;
2022-10-05 15:02:30 +08:00
}
else
{
return false;
}
}
2022-10-05 15:02:30 +08:00
public enum InternalCmdCharType { none, slash, backslash };
2022-10-05 15:02:30 +08:00
public enum BrandInfoType { mcc, vanilla, empty };
public enum CacheType { none, memory, disk };
public enum ResolveSrvRecordType { no, fast, yes };
public enum ForgeConfigType { no, auto, force };
}
2022-10-05 15:02:30 +08:00
public struct AccountInfoConfig
{
public string Login = string.Empty, Password = string.Empty;
public AccountInfoConfig()
{
Login = string.Empty;
Password = string.Empty;
}
2022-10-05 15:02:30 +08:00
public AccountInfoConfig(string Login)
{
2022-10-05 15:02:30 +08:00
this.Login = Login;
this.Password = "-";
}
2022-10-05 15:02:30 +08:00
public AccountInfoConfig(string Login, string Password)
{
2022-10-05 15:02:30 +08:00
this.Login = Login;
this.Password = Password;
}
2022-10-05 15:02:30 +08:00
}
public struct ServerInfoConfig
{
public string Host = string.Empty;
public ushort? Port = null;
public ServerInfoConfig()
{
Host = string.Empty;
Port = null;
}
2022-10-05 15:02:30 +08:00
public ServerInfoConfig(string Host)
{
2022-10-05 15:02:30 +08:00
string[] sip = Host.Split(new[] { ":", "" }, StringSplitOptions.None);
this.Host = sip[0];
if (sip.Length > 1)
{
try { this.Port = Convert.ToUInt16(sip[1]); }
catch (FormatException) { }
}
}
2022-10-05 15:02:30 +08:00
public ServerInfoConfig(string Host, ushort Port)
{
2022-10-05 15:02:30 +08:00
this.Host = Host.Split(new[] { ":", "" }, StringSplitOptions.None)[0];
this.Port = Port;
}
2022-10-05 15:02:30 +08:00
}
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
[TomlDoNotInlineObject]
public class AuthlibServer
2023-11-12 21:04:20 +08:00
{
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
[NonSerialized]
private string _host = string.Empty;
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
[TomlInlineComment("$AuthlibServer.Host$")]
public string Host
2023-11-12 21:04:20 +08:00
{
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
get => _host;
set
2023-11-12 21:04:20 +08:00
{
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
string[] split = value.Split(new[] { ":", "" }, StringSplitOptions.None);
if (split.Length >= 1)
_host = split[0];
if (split.Length >= 2)
{
try { Port = Convert.ToUInt16(split[1]); }
catch (FormatException) { }
}
2023-11-12 21:04:20 +08:00
}
}
Add configurable authlib-injector API path and HTTP support for Yggdrasil auth Re-implements the changes from PR #2890, adapted for the current codebase which uses System.Text.Json.Nodes and HttpClient instead of the legacy Json.JSONData and hand-rolled SslStream HTTP client. Changes: - Settings.cs: Convert AuthlibServer from struct to class with [TomlDoNotInlineObject]; convert Host to a property that parses 'host:port' syntax; add AuthlibInjectorAPIPath (default '/api/yggdrasil') for servers that use a different prefix (e.g. Drasl uses '/authlib-injector'); add UseHttps (default true) so local/dev auth servers without TLS work. - ConfigComments.resx: Add descriptive inline comments for the new AuthlibServer fields (Host, Port, AuthlibInjectorAPIPath, UseHttps). - ProtocolHandler.cs: Replace three hardcoded '/api/yggdrasil/...' paths with AuthlibInjectorAPIPath-based paths (authenticate, refresh, join). Replace hand-rolled TcpClient+SslStream HTTP in DoHTTPSRequest with HttpClient+SocketsHttpHandler (ConnectCallback routes through ProxyHandler). Add useHttps parameter so HTTP-only auth servers are supported. - KeyUtils.cs: Add AuthServerSupportsProfileKeys() that fetches the authlib-injector metadata endpoint and checks feature.enable_profile_key. Update GetNewProfileKeys() to skip key fetch when the auth server does not support profile keys; build the cert URL dynamically using AuthlibInjectorAPIPath for Yggdrasil; always fetch real certs instead of returning a dummy response. Remove MakeDummyResponse() which is no longer needed. Tested against a local Drasl instance with authlib-injector 1.2.7 on a 1.21.11 Minecraft server — full auth flow (login, profile key fetch, session join) confirmed working end-to-end. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-22 23:43:24 +01:00
[TomlInlineComment("$AuthlibServer.Port$")]
public int Port = 443;
[TomlInlineComment("$AuthlibServer.AuthlibInjectorAPIPath$")]
public string AuthlibInjectorAPIPath = "/api/yggdrasil";
[TomlInlineComment("$AuthlibServer.UseHttps$")]
public bool UseHttps = true;
2023-11-12 21:04:20 +08:00
}
2022-10-05 15:02:30 +08:00
}
}
2022-10-05 15:02:30 +08:00
public static class SignatureConfigHelper
{
public static SignatureConfig Config = new();
2022-10-05 15:02:30 +08:00
[TomlDoNotInlineObject]
public class SignatureConfig
{
[TomlInlineComment("$Signature.LoginWithSecureProfile$")]
2022-10-05 15:02:30 +08:00
public bool LoginWithSecureProfile = true;
[TomlInlineComment("$Signature.SignChat$")]
2022-10-05 15:02:30 +08:00
public bool SignChat = true;
[TomlInlineComment("$Signature.SignMessageInCommand$")]
2022-10-05 15:02:30 +08:00
public bool SignMessageInCommand = true;
[TomlInlineComment("$Signature.MarkLegallySignedMsg$")]
2023-01-29 22:39:11 +08:00
public bool MarkLegallySignedMsg = true;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Signature.MarkModifiedMsg$")]
2022-10-05 15:02:30 +08:00
public bool MarkModifiedMsg = true;
[TomlInlineComment("$Signature.MarkIllegallySignedMsg$")]
2022-10-05 15:02:30 +08:00
public bool MarkIllegallySignedMsg = true;
[TomlInlineComment("$Signature.MarkSystemMessage$")]
2023-01-29 22:39:11 +08:00
public bool MarkSystemMessage = true;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Signature.ShowModifiedChat$")]
2022-10-05 15:02:30 +08:00
public bool ShowModifiedChat = true;
[TomlInlineComment("$Signature.ShowIllegalSignedChat$")]
2022-10-05 15:02:30 +08:00
public bool ShowIllegalSignedChat = true;
public void OnSettingUpdate() { }
}
}
2022-10-05 15:02:30 +08:00
public static class LoggingConfigHealper
{
public static LoggingConfig Config = new();
[TomlDoNotInlineObject]
public class LoggingConfig
{
[TomlInlineComment("$Logging.DebugMessages$")]
2022-10-05 15:02:30 +08:00
public bool DebugMessages = false;
[TomlInlineComment("$Logging.ChatMessages$")]
2022-10-05 15:02:30 +08:00
public bool ChatMessages = true;
[TomlInlineComment("$Logging.InfoMessages$")]
2022-10-05 15:02:30 +08:00
public bool InfoMessages = true;
[TomlInlineComment("$Logging.WarningMessages$")]
2022-10-05 15:02:30 +08:00
public bool WarningMessages = true;
[TomlInlineComment("$Logging.ErrorMessages$")]
2022-10-05 15:02:30 +08:00
public bool ErrorMessages = true;
[TomlInlineComment("$Logging.ChatFilter$")]
2022-10-05 15:02:30 +08:00
public string ChatFilterRegex = @".*";
[TomlInlineComment("$Logging.DebugFilter$")]
2022-10-05 15:02:30 +08:00
public string DebugFilterRegex = @".*";
[TomlInlineComment("$Logging.FilterMode$")]
2022-10-06 18:12:32 +08:00
public FilterModeEnum FilterMode = FilterModeEnum.disable;
2022-10-05 15:02:30 +08:00
[TomlInlineComment("$Logging.LogToFile$")]
2022-10-05 15:02:30 +08:00
public bool LogToFile = false;
[TomlInlineComment("$Logging.LogFile$")]
2022-10-05 15:02:30 +08:00
public string LogFile = @"console-log.txt";
[TomlInlineComment("$Logging.PrependTimestamp$")]
2022-10-05 15:02:30 +08:00
public bool PrependTimestamp = false;
[TomlInlineComment("$Logging.SaveColorCodes$")]
2022-10-05 15:02:30 +08:00
public bool SaveColorCodes = false;
public void OnSettingUpdate() { }
2022-10-06 18:12:32 +08:00
public enum FilterModeEnum { disable, blacklist, whitelist }
2022-10-05 15:02:30 +08:00
}
}
2022-12-11 13:00:19 +08:00
public static class ConsoleConfigHealper
{
public static ConsoleConfig Config = new();
[TomlDoNotInlineObject]
public class ConsoleConfig
{
public MainConfig General = new();
[TomlPrecedingComment("$Console.CommandSuggestion$")]
public CommandSuggestionConfig CommandSuggestion = new();
2026-03-29 18:47:40 +08:00
[TomlPrecedingComment("$Console.Minimap$")]
public MinimapConfig Minimap = new();
2026-04-04 16:17:49 +02:00
[TomlPrecedingComment("$Console.TabList$")]
public TabListConfig TabList = new();
2022-12-11 13:00:19 +08:00
public void OnSettingUpdate()
{
ConsoleIO.ChatVisible = General.Display_Chat;
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
var backend = ConsoleIO.Backend;
if (backend == null) return;
2022-12-14 14:45:51 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
backend.DisplayUserInput = General.Display_Input;
backend.SetBackreadBufferLimit(General.History_Input_Records);
2022-12-14 14:45:51 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
if (backend is ClassicConsoleBackend classic)
{
classic.EnableWriterColor = General.ConsoleColorMode != ConsoleColorModeType.disable;
classic.UseVT100ColorCode = General.ConsoleColorMode != ConsoleColorModeType.legacy_4bit;
2022-12-14 14:45:51 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
if (General.ConsoleColorMode == ConsoleColorModeType.disable)
CommandSuggestion.Enable_Color = false;
2022-12-11 16:30:45 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
classic.EnableSuggestionColor = CommandSuggestion.Enable_Color;
classic.Enable24bitColor = General.ConsoleColorMode == ConsoleColorModeType.vt100_24bit;
classic.UseBasicArrow = CommandSuggestion.Use_Basic_Arrow;
2022-12-11 13:00:19 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
CommandSuggestion.Max_Suggestion_Width =
classic.SetMaxSuggestionLength(CommandSuggestion.Max_Suggestion_Width);
CommandSuggestion.Max_Displayed_Suggestions =
classic.SetMaxSuggestionCount(CommandSuggestion.Max_Displayed_Suggestions);
2022-12-11 13:00:19 +08:00
if (!CheckColorCode(CommandSuggestion.Text_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.TextColor", CommandSuggestion.Text_Color));
CommandSuggestion.Text_Color = "#f8fafc";
}
if (!CheckColorCode(CommandSuggestion.Text_Background_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.TextBackgroundColor", CommandSuggestion.Text_Background_Color));
CommandSuggestion.Text_Background_Color = "#64748b";
}
if (!CheckColorCode(CommandSuggestion.Highlight_Text_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.HighlightTextColor", CommandSuggestion.Highlight_Text_Color));
CommandSuggestion.Highlight_Text_Color = "#334155";
}
if (!CheckColorCode(CommandSuggestion.Highlight_Text_Background_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.HighlightTextBackgroundColor", CommandSuggestion.Highlight_Text_Background_Color));
CommandSuggestion.Highlight_Text_Background_Color = "#fde047";
}
if (!CheckColorCode(CommandSuggestion.Tooltip_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.TooltipColor", CommandSuggestion.Tooltip_Color));
CommandSuggestion.Tooltip_Color = "#7dd3fc";
}
if (!CheckColorCode(CommandSuggestion.Highlight_Tooltip_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.HighlightTooltipColor", CommandSuggestion.Highlight_Tooltip_Color));
CommandSuggestion.Highlight_Tooltip_Color = "#3b82f6";
}
if (!CheckColorCode(CommandSuggestion.Arrow_Symbol_Color))
{
ConsoleIO.WriteLine(string.Format(Translations.config_commandsuggestion_illegal_color, "CommandSuggestion.ArrowSymbolColor", CommandSuggestion.Arrow_Symbol_Color));
CommandSuggestion.Arrow_Symbol_Color = "#d1d5db";
}
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
classic.SetSuggestionColors(
2022-12-11 13:00:19 +08:00
CommandSuggestion.Text_Color, CommandSuggestion.Text_Background_Color,
CommandSuggestion.Highlight_Text_Color, CommandSuggestion.Highlight_Text_Background_Color,
CommandSuggestion.Tooltip_Color, CommandSuggestion.Highlight_Tooltip_Color,
CommandSuggestion.Arrow_Symbol_Color);
}
}
private static bool CheckColorCode(string? input)
{
if (string.IsNullOrWhiteSpace(input))
return false;
if (input.Length < 6 || input.Length > 7)
return false;
if (input.Length == 6 && input[0] == '#')
return false;
if (input.Length == 7 && input[0] != '#')
return false;
try
{
Convert.ToInt32(input.Length == 7 ? input[1..] : input, 16);
return true;
}
catch
{
return false;
}
}
[TomlDoNotInlineObject]
public class MainConfig
{
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
[TomlInlineComment("$Console.General.ConsoleMode$")]
public ConsoleModeType ConsoleMode = ConsoleModeType.classic;
2022-12-14 14:45:51 +08:00
[TomlInlineComment("$Console.General.ConsoleColorMode$")]
public ConsoleColorModeType ConsoleColorMode = ConsoleColorModeType.vt100_24bit;
2022-12-11 13:00:19 +08:00
[TomlInlineComment("$Console.General.Display_Icon_Banner$")]
public bool Display_Icon_Banner = true;
2022-12-14 14:45:51 +08:00
[TomlInlineComment("$Console.General.Display_Input$")]
public bool Display_Input = true;
[TomlInlineComment("$Console.General.Display_Chat$")]
public bool Display_Chat = true;
2022-12-14 14:45:51 +08:00
[TomlInlineComment("$Console.General.History_Input_Records$")]
public int History_Input_Records = 32;
[TomlInlineComment("$Console.General.TUI_Log_Scrollback$")]
public int TUI_Log_Scrollback = 0;
2022-12-11 13:00:19 +08:00
}
[TomlDoNotInlineObject]
public class CommandSuggestionConfig
{
[TomlInlineComment("$Console.CommandSuggestion.Enable$")]
public bool Enable = true;
public bool Enable_Color = true;
2022-12-11 16:30:45 +08:00
[TomlInlineComment("$Console.CommandSuggestion.Use_Basic_Arrow$")]
public bool Use_Basic_Arrow = false;
2022-12-11 13:00:19 +08:00
public int Max_Suggestion_Width = 30;
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
public int Max_Displayed_Suggestions = 10;
2022-12-11 13:00:19 +08:00
public string Text_Color = "#f8fafc";
public string Text_Background_Color = "#64748b";
public string Highlight_Text_Color = "#334155";
public string Highlight_Text_Background_Color = "#fde047";
public string Tooltip_Color = "#7dd3fc";
public string Highlight_Tooltip_Color = "#3b82f6";
public string Arrow_Symbol_Color = "#d1d5db";
}
2022-12-14 14:45:51 +08:00
TUI for MCC (#2976) * feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
2026-03-26 02:08:18 +08:00
public enum ConsoleModeType { classic, tui };
2022-12-14 14:45:51 +08:00
public enum ConsoleColorModeType { disable, legacy_4bit, vt100_4bit, vt100_8bit, vt100_24bit };
2026-03-29 18:47:40 +08:00
[TomlDoNotInlineObject]
public class MinimapConfig
{
[TomlInlineComment("$Console.Minimap.Enabled$")]
public bool Enabled = false;
[TomlInlineComment("$Console.Minimap.Zoom$")]
public int Zoom = Tui.MinimapControl.DefaultZoom;
[TomlInlineComment("$Console.Minimap.Width$")]
public int Width = Tui.MinimapControl.DefaultWidth;
[TomlInlineComment("$Console.Minimap.Height$")]
public int Height = Tui.MinimapControl.DefaultHeight;
[TomlInlineComment("$Console.Minimap.Position$")]
public Tui.MinimapPosition Position = Tui.MinimapPosition.top_right;
[TomlInlineComment("$Console.Minimap.ShowPlayerNames$")]
public bool ShowPlayerNames = false;
[TomlInlineComment("$Console.Minimap.ShowHostileNames$")]
public bool ShowHostileNames = false;
[TomlInlineComment("$Console.Minimap.ShowNeutralNames$")]
public bool ShowNeutralNames = false;
[TomlInlineComment("$Console.Minimap.ShowPassiveNames$")]
public bool ShowPassiveNames = false;
[TomlInlineComment("$Console.Minimap.RefreshInterval$")]
public int RefreshInterval = Tui.MinimapControl.DefaultRefreshMs;
2026-03-31 00:40:26 +08:00
[TomlInlineComment("$Console.Minimap.CaveMode$")]
public Tui.CaveModeOption CaveMode = Tui.CaveModeOption.auto;
2026-03-29 18:47:40 +08:00
public void OnSettingUpdate()
{
Zoom = Math.Clamp(Zoom, Tui.MinimapControl.MinZoom, Tui.MinimapControl.MaxZoom);
Width = Math.Clamp(Width, 10, 120);
Height = Math.Clamp(Height, 4, 80);
if (Height % 2 != 0) Height++;
RefreshInterval = Math.Clamp(RefreshInterval,
Tui.MinimapControl.MinRefreshMs, Tui.MinimapControl.MaxRefreshMs);
}
}
2026-04-04 16:17:49 +02:00
[TomlDoNotInlineObject]
public class TabListConfig
{
[TomlInlineComment("$Console.TabList.ShowTeams$")]
public bool ShowTeams = false;
}
2022-12-11 13:00:19 +08:00
}
}
2022-10-05 15:02:30 +08:00
public static class AppVarConfigHelper
{
public static AppVarConfig Config = new();
[TomlDoNotInlineObject]
public class AppVarConfig
{
[TomlPrecedingComment("$AppVars.Variables$")]
2022-10-05 15:02:30 +08:00
private readonly Dictionary<string, string> VarStirng = new() {
{ "your_var", "your_value" },
{ "your var 2", "your value 2" },
};
public void OnSettingUpdate() { }
[NonSerialized]
private readonly Dictionary<string, object> VarObject = new();
[NonSerialized]
readonly Lock varLock = new();
2022-10-05 15:02:30 +08:00
private static bool TryGetReadOnlyVar(string varName, [NotNullWhen(true)] out object? varData)
{
switch (Settings.ToLowerIfNeed(varName))
{
case "username":
varData = InternalConfig.Username;
return true;
case "login":
varData = InternalConfig.Account.Login;
return true;
case "serverip":
varData = InternalConfig.ServerIP;
return true;
case "serverport":
varData = InternalConfig.ServerPort;
return true;
case "datetime":
varData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
return true;
case "date":
varData = DateTime.Now.ToString("yyyy-MM-dd");
return true;
case "players":
varData = string.Join(", ", McClient.Instance?.GetOnlinePlayers() ?? []);
return true;
default:
varData = null;
return false;
}
}
2022-10-05 15:02:30 +08:00
/// <summary>
/// Set a custom %variable% which will be available through expandVars()
/// </summary>
/// <param name="varName">Name of the variable</param>
/// <param name="varData">Value of the variable</param>
/// <returns>True if the parameters were valid</returns>
public bool SetVar(string varName, object varData)
{
varName = Settings.ToLowerIfNeed(new string(varName.TakeWhile(char.IsLetterOrDigit).ToArray()));
if (varName.Length > 0)
{
2022-10-05 15:02:30 +08:00
bool isString = varData.GetType() == typeof(string);
lock (varLock)
{
if (isString)
{
2022-10-05 15:02:30 +08:00
if (VarObject.ContainsKey(varName))
VarObject.Remove(varName);
VarStirng[varName] = (string)varData;
}
else
{
2022-10-05 15:02:30 +08:00
if (VarStirng.ContainsKey(varName))
VarStirng.Remove(varName);
VarObject[varName] = varData;
}
2022-10-05 15:02:30 +08:00
}
return true;
}
2022-10-05 15:02:30 +08:00
else
{
2022-10-11 22:47:06 +02:00
return false;
2022-09-13 19:25:00 +08:00
}
2022-10-05 15:02:30 +08:00
}
/// <summary>
/// Get a custom %variable% or null if the variable does not exist
/// </summary>
/// <param name="varName">Variable name</param>
/// <returns>The value or null if the variable does not exists</returns>
public object? GetVar(string varName)
{
if (TryGetReadOnlyVar(varName, out object? readOnlyVar))
return readOnlyVar;
2022-10-05 15:02:30 +08:00
if (VarStirng.TryGetValue(varName, out string? valueString))
return valueString;
else if (VarObject.TryGetValue(varName, out object? valueObject))
return valueObject;
else
return null;
}
2022-10-05 15:02:30 +08:00
/// <summary>
/// Get a custom %variable% or null if the variable does not exist
/// </summary>
/// <param name="varName">Variable name</param>
/// <returns>The value or null if the variable does not exists</returns>
public bool TryGetVar(string varName, [NotNullWhen(true)] out object? varData)
{
if (TryGetReadOnlyVar(varName, out varData))
return true;
2022-10-05 15:02:30 +08:00
if (VarStirng.TryGetValue(varName, out string? valueString))
{
2022-10-05 15:02:30 +08:00
varData = valueString;
return true;
}
2022-10-05 15:02:30 +08:00
else if (VarObject.TryGetValue(varName, out object? valueObject))
{
2022-10-05 15:02:30 +08:00
varData = valueObject;
return true;
}
2022-10-05 15:02:30 +08:00
else
{
2022-10-05 15:02:30 +08:00
varData = null;
return false;
}
2022-10-05 15:02:30 +08:00
}
/// <summary>
/// Get a dictionary containing variables (names and value)
/// </summary>
/// <returns>A IDictionary<string, object> containing a name and a vlaue key pairs of variables</returns>
public Dictionary<string, object> GetVariables()
{
2022-10-11 22:47:06 +02:00
Dictionary<string, object> res = new(VarObject);
2022-10-05 15:02:30 +08:00
foreach ((string varName, string varData) in VarStirng)
res.Add(varName, varData);
return res;
}
2022-10-05 15:02:30 +08:00
/// <summary>
/// Replace %variables% with their value from global AppVars
/// </summary>
/// <param name="str">String to parse</param>
/// <param name="localContext">Optional local variables overriding global variables</param>
/// <returns>Modifier string</returns>
public string ExpandVars(string str, Dictionary<string, object>? localVars = null)
{
StringBuilder result = new();
for (int i = 0; i < str.Length; i++)
{
2022-10-05 15:02:30 +08:00
if (str[i] == '%')
{
bool varname_ok = false;
StringBuilder var_name = new();
for (int j = i + 1; j < str.Length; j++)
{
2022-10-05 15:02:30 +08:00
if (!char.IsLetterOrDigit(str[j]) && str[j] != '_')
{
2022-10-05 15:02:30 +08:00
if (str[j] == '%')
varname_ok = var_name.Length > 0;
break;
}
2022-10-05 15:02:30 +08:00
else var_name.Append(str[j]);
}
2022-10-05 15:02:30 +08:00
if (varname_ok)
{
2022-10-05 15:02:30 +08:00
string varname = var_name.ToString();
string varname_lower = Settings.ToLowerIfNeed(varname);
i = i + varname.Length + 1;
if (TryGetReadOnlyVar(varname_lower, out object? readOnlyVar))
{
result.Append(readOnlyVar.ToString());
}
else if (localVars is not null && localVars.ContainsKey(varname_lower))
{
result.Append(localVars[varname_lower].ToString());
}
else if (TryGetVar(varname_lower, out object? var_value))
{
result.Append(var_value.ToString());
}
else
2022-10-05 15:02:30 +08:00
{
result.Append("%" + varname + '%');
2022-10-05 15:02:30 +08:00
}
}
2022-10-05 15:02:30 +08:00
else result.Append(str[i]);
}
else result.Append(str[i]);
}
2022-10-05 15:02:30 +08:00
return result.ToString();
}
}
}
2022-10-05 15:02:30 +08:00
public static class MCSettingsConfigHealper
{
public static MCSettingsConfig Config = new();
2022-10-05 15:02:30 +08:00
[TomlDoNotInlineObject]
public class MCSettingsConfig
{
[TomlInlineComment("$MCSettings.Enabled$")]
2022-10-05 15:02:30 +08:00
public bool Enabled = true;
[TomlInlineComment("$MCSettings.Locale$")]
2022-10-05 15:02:30 +08:00
public string Locale = "en_US";
[TomlInlineComment("$MCSettings.RenderDistance$")]
2022-10-05 15:02:30 +08:00
public byte RenderDistance = 8;
[TomlInlineComment("$MCSettings.Difficulty$")]
2022-10-05 15:02:30 +08:00
public DifficultyType Difficulty = DifficultyType.peaceful;
[TomlInlineComment("$MCSettings.ChatMode$")]
2022-10-05 15:02:30 +08:00
public ChatModeType ChatMode = ChatModeType.enabled;
[TomlInlineComment("$MCSettings.ChatColors$")]
2022-10-05 15:02:30 +08:00
public bool ChatColors = true;
[TomlInlineComment("$MCSettings.MainHand$")]
2022-10-05 15:02:30 +08:00
public MainHandType MainHand = MainHandType.left;
public SkinInfo Skin = new();
public void OnSettingUpdate() { }
public enum DifficultyType { peaceful, easy, normal, difficult };
public enum ChatModeType { enabled, commands, disabled };
public enum MainHandType { left, right };
public struct SkinInfo
{
public bool Cape = true, Hat = true, Jacket = false;
public bool Sleeve_Left = false, Sleeve_Right = false;
public bool Pants_Left = false, Pants_Right = false;
public SkinInfo() { }
public SkinInfo(bool Cape, bool Hat, bool Jacket, bool Sleeve_Left, bool Sleeve_Right, bool Pants_Left, bool Pants_Right)
{
2022-10-05 15:02:30 +08:00
this.Cape = Cape;
this.Hat = Hat;
this.Jacket = Jacket;
this.Sleeve_Left = Sleeve_Left;
this.Sleeve_Right = Sleeve_Right;
this.Pants_Left = Pants_Left;
this.Pants_Right = Pants_Right;
}
2022-10-05 15:02:30 +08:00
public byte GetByte()
{
2022-10-05 15:02:30 +08:00
return (byte)(
((Cape ? 1 : 0) << 0)
| ((Jacket ? 1 : 0) << 1)
| ((Sleeve_Left ? 1 : 0) << 2)
| ((Sleeve_Right ? 1 : 0) << 3)
| ((Pants_Left ? 1 : 0) << 4)
| ((Pants_Right ? 1 : 0) << 5)
| ((Hat ? 1 : 0) << 6)
);
}
2022-10-05 15:02:30 +08:00
}
}
}
2022-10-05 15:02:30 +08:00
public static class ChatFormatConfigHelper
{
2022-10-05 15:02:30 +08:00
public static ChatFormatConfig Config = new();
2022-10-05 15:02:30 +08:00
[TomlDoNotInlineObject]
public class ChatFormatConfig
{
[TomlInlineComment("$ChatFormat.Builtins$")]
2022-10-05 15:02:30 +08:00
public bool Builtins = true;
[TomlInlineComment("$ChatFormat.UserDefined$")]
2022-10-06 18:12:32 +08:00
public bool UserDefined = false;
2022-10-05 15:02:30 +08:00
public string Public = @"^<([a-zA-Z0-9_]+)> (.+)$";
2022-09-12 02:10:18 +08:00
2022-10-05 15:02:30 +08:00
public string Private = @"^([a-zA-Z0-9_]+) whispers to you: (.+)$";
public string TeleportRequest = @"^([a-zA-Z0-9_]+) has requested (?:to|that you) teleport to (?:you|them)\.$";
2022-10-17 10:03:01 +08:00
public void OnSettingUpdate()
{
if (UserDefined)
{
bool checkResult = true;
try { _ = new Regex(Public); }
catch (ArgumentException)
{
checkResult = false;
2023-01-13 16:12:10 +08:00
ConsoleIO.WriteLineFormatted("§c[Settings]Illegal regular expression: ChatFormat.Public = " + Public);
2022-10-17 10:03:01 +08:00
}
try { _ = new Regex(Private); }
catch (ArgumentException)
{
checkResult = false;
2023-01-13 16:12:10 +08:00
ConsoleIO.WriteLineFormatted("§c[Settings]Illegal regular expression: ChatFormat.Private = " + Private);
2022-10-17 10:03:01 +08:00
}
try { _ = new Regex(TeleportRequest); }
catch (ArgumentException)
{
checkResult = false;
2023-01-13 16:12:10 +08:00
ConsoleIO.WriteLineFormatted("§c[Settings]Illegal regular expression: ChatFormat.TeleportRequest = " + TeleportRequest);
2022-10-17 10:03:01 +08:00
}
if (!checkResult)
{
UserDefined = false;
2023-01-13 16:12:10 +08:00
ConsoleIO.WriteLineFormatted("§c[Settings]ChatFormat: User-defined regular expressions are disabled.");
2022-10-17 10:03:01 +08:00
}
}
}
}
}
2022-10-05 15:02:30 +08:00
public static class ChatBotConfigHealper
{
2022-10-05 15:02:30 +08:00
public static ChatBotConfig Config = new();
2022-10-05 15:02:30 +08:00
[TomlDoNotInlineObject]
public class ChatBotConfig
{
[TomlPrecedingComment("$ChatBot.Alerts$")]
2022-10-05 15:02:30 +08:00
public ChatBots.Alerts.Configs Alerts
{
2022-10-05 15:02:30 +08:00
get { return ChatBots.Alerts.Config; }
set { ChatBots.Alerts.Config = value; ChatBots.Alerts.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AntiAfk$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AntiAFK.Configs AntiAFK
{
get { return ChatBots.AntiAFK.Config; }
set { ChatBots.AntiAFK.Config = value; ChatBots.AntiAFK.Config.OnSettingUpdate(); }
}
2022-10-05 15:02:30 +08:00
[TomlPrecedingComment("$ChatBot.AutoAttack$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoAttack.Configs AutoAttack
{
get { return ChatBots.AutoAttack.Config; }
set { ChatBots.AutoAttack.Config = value; ChatBots.AutoAttack.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoCraft$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoCraft.Configs AutoCraft
{
get { return ChatBots.AutoCraft.Config; }
set { ChatBots.AutoCraft.Config = value; ChatBots.AutoCraft.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoDig$")]
2022-10-08 17:56:32 +08:00
public ChatBots.AutoDig.Configs AutoDig
{
get { return ChatBots.AutoDig.Config; }
set { ChatBots.AutoDig.Config = value; ChatBots.AutoDig.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoDrop$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoDrop.Configs AutoDrop
{
get { return ChatBots.AutoDrop.Config; }
set { ChatBots.AutoDrop.Config = value; ChatBots.AutoDrop.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoEat$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoEat.Configs AutoEat
{
get { return ChatBots.AutoEat.Config; }
set { ChatBots.AutoEat.Config = value; ChatBots.AutoEat.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoFishing$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoFishing.Configs AutoFishing
{
get { return ChatBots.AutoFishing.Config; }
set { ChatBots.AutoFishing.Config = value; ChatBots.AutoFishing.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoRelog$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoRelog.Configs AutoRelog
{
2022-10-05 15:02:30 +08:00
get { return ChatBots.AutoRelog.Config; }
set { ChatBots.AutoRelog.Config = value; ChatBots.AutoRelog.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.AutoRespond$")]
2022-10-05 15:02:30 +08:00
public ChatBots.AutoRespond.Configs AutoRespond
{
get { return ChatBots.AutoRespond.Config; }
set { ChatBots.AutoRespond.Config = value; ChatBots.AutoRespond.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.ChatLog$")]
2022-10-05 15:02:30 +08:00
public ChatBots.ChatLog.Configs ChatLog
{
get { return ChatBots.ChatLog.Config; }
set { ChatBots.ChatLog.Config = value; ChatBots.ChatLog.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.DiscordBridge$")]
public ChatBots.DiscordBridge.Configs DiscordBridge
{
get { return ChatBots.DiscordBridge.Config; }
2022-10-21 19:05:49 +08:00
set { ChatBots.DiscordBridge.Config = value; ChatBots.DiscordBridge.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.Farmer$")]
2022-10-11 22:47:06 +02:00
public ChatBots.Farmer.Configs Farmer
{
get { return ChatBots.Farmer.Config; }
set { ChatBots.Farmer.Config = value; ChatBots.Farmer.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.FollowPlayer$")]
2022-10-05 15:02:30 +08:00
public ChatBots.FollowPlayer.Configs FollowPlayer
{
get { return ChatBots.FollowPlayer.Config; }
set { ChatBots.FollowPlayer.Config = value; ChatBots.FollowPlayer.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.HangmanGame$")]
2022-10-05 15:02:30 +08:00
public ChatBots.HangmanGame.Configs HangmanGame
{
get { return ChatBots.HangmanGame.Config; }
set { ChatBots.HangmanGame.Config = value; ChatBots.HangmanGame.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.Mailer$")]
2022-10-05 15:02:30 +08:00
public ChatBots.Mailer.Configs Mailer
{
get { return ChatBots.Mailer.Config; }
set { ChatBots.Mailer.Config = value; ChatBots.Mailer.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.Map$")]
2022-10-05 15:02:30 +08:00
public ChatBots.Map.Configs Map
{
get { return ChatBots.Map.Config; }
set { ChatBots.Map.Config = value; ChatBots.Map.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.PlayerListLogger$")]
2022-10-05 15:02:30 +08:00
public ChatBots.PlayerListLogger.Configs PlayerListLogger
{
get { return ChatBots.PlayerListLogger.Config; }
set { ChatBots.PlayerListLogger.Config = value; ChatBots.PlayerListLogger.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.RemoteControl$")]
2022-10-05 15:02:30 +08:00
public ChatBots.RemoteControl.Configs RemoteControl
{
get { return ChatBots.RemoteControl.Config; }
set { ChatBots.RemoteControl.Config = value; ChatBots.RemoteControl.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.ReplayCapture$")]
2022-10-05 15:02:30 +08:00
public ChatBots.ReplayCapture.Configs ReplayCapture
{
get { return ChatBots.ReplayCapture.Config; }
set { ChatBots.ReplayCapture.Config = value; ChatBots.ReplayCapture.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.ScriptScheduler$")]
2022-10-05 15:02:30 +08:00
public ChatBots.ScriptScheduler.Configs ScriptScheduler
{
get { return ChatBots.ScriptScheduler.Config; }
set { ChatBots.ScriptScheduler.Config = value; ChatBots.ScriptScheduler.Config.OnSettingUpdate(); }
}
2022-10-20 19:29:35 +02:00
[TomlPrecedingComment("$ChatBot.TelegramBridge$")]
2022-10-24 15:35:24 +02:00
public ChatBots.TelegramBridge.Configs TelegramBridge
{
get { return ChatBots.TelegramBridge.Config; }
set { ChatBots.TelegramBridge.Config = value; ChatBots.TelegramBridge.Config.OnSettingUpdate(); }
}
2023-05-20 21:44:18 +02:00
[TomlPrecedingComment("$ChatBot.ItemsCollector$")]
public ChatBots.ItemsCollector.Configs ItemsCollector
{
get { return ChatBots.ItemsCollector.Config; }
set
{
ChatBots.ItemsCollector.Config = value;
ChatBots.ItemsCollector.Config.OnSettingUpdate();
}
}
[TomlPrecedingComment("$ChatBot.DiscordRpc$")]
public ChatBots.DiscordRpc.Configs DiscordRpc
{
get { return ChatBots.DiscordRpc.Config; }
set { ChatBots.DiscordRpc.Config = value; ChatBots.DiscordRpc.Config.OnSettingUpdate(); }
}
[TomlPrecedingComment("$ChatBot.McpServer$")]
public ChatBots.McpServer.Configs McpServer
{
get { return ChatBots.McpServer.Config; }
set
{
ChatBots.McpServer.Config = value ?? new ChatBots.McpServer.Configs();
ChatBots.McpServer.Config.OnSettingUpdate();
}
}
}
}
/// <summary>
/// Map the system CultureInfo name to a Minecraft game language code.
/// </summary>
/// <remarks>
/// Culture name reference (language-COUNTRY):
/// https://learn.microsoft.com/en-us/previous-versions/commerce-server/ee797784(v=cs.20)
/// Full LCID / language-tag spec (MS-LCID, includes fil-PH, nb-NO, etc.):
/// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/70feba9f-294e-491e-b6eb-56532684c37f
/// </remarks>
public static string GetDefaultGameLanguage()
{
2022-12-11 13:00:19 +08:00
string gameLanguage = "en_us";
string systemLanguage = string.IsNullOrWhiteSpace(Program.ActualCulture.Name)
? Program.ActualCulture.Parent.Name
: Program.ActualCulture.Name;
switch (systemLanguage)
{
case "af":
case "af-ZA":
gameLanguage = "af_za";
break;
case "ar":
case "ar-AE":
case "ar-BH":
case "ar-DZ":
case "ar-EG":
case "ar-IQ":
case "ar-JO":
case "ar-KW":
case "ar-LB":
case "ar-LY":
case "ar-MA":
case "ar-OM":
case "ar-QA":
case "ar-SA":
case "ar-SY":
case "ar-TN":
case "ar-YE":
gameLanguage = "ar_sa";
break;
case "az":
case "az-Cyrl-AZ":
case "az-Latn-AZ":
gameLanguage = "az_az";
break;
case "be":
case "be-BY":
gameLanguage = "be_by";
break;
case "bg":
case "bg-BG":
gameLanguage = "bg_bg";
break;
case "bs-Latn-BA":
gameLanguage = "bs_ba";
break;
case "ca":
case "ca-ES":
gameLanguage = "ca_es";
break;
case "cs":
case "cs-CZ":
gameLanguage = "cs_cz";
break;
case "cy-GB":
gameLanguage = "cy_gb";
break;
case "da":
case "da-DK":
gameLanguage = "da_dk";
break;
case "de":
case "de-DE":
case "de-LI":
case "de-LU":
gameLanguage = "de_de";
break;
case "de-AT":
gameLanguage = "de_at";
break;
case "de-CH":
gameLanguage = "de_ch";
break;
case "dv":
case "dv-MV":
break;
case "el":
case "el-GR":
gameLanguage = "el_gr";
break;
case "en":
case "en-029":
case "en-BZ":
case "en-IE":
case "en-JM":
case "en-PH":
case "en-TT":
case "en-ZA":
case "en-ZW":
2022-12-11 13:00:19 +08:00
case "en-US":
gameLanguage = "en_us";
break;
case "en-GB":
gameLanguage = "en_gb";
break;
case "en-AU":
gameLanguage = "en_au";
break;
case "en-CA":
gameLanguage = "en_ca";
break;
case "en-NZ":
gameLanguage = "en_nz";
break;
case "es":
case "es-BO":
case "es-CO":
case "es-CR":
case "es-DO":
case "es-ES":
case "es-GT":
case "es-HN":
case "es-NI":
case "es-PA":
case "es-PE":
case "es-PR":
case "es-PY":
case "es-SV":
gameLanguage = "es_es";
break;
case "es-AR":
gameLanguage = "es_ar";
break;
case "es-CL":
gameLanguage = "es_cl";
break;
case "es-EC":
gameLanguage = "es_ec";
break;
case "es-MX":
gameLanguage = "es_mx";
break;
case "es-UY":
gameLanguage = "es_uy";
break;
case "es-VE":
gameLanguage = "es_ve";
break;
case "et":
case "et-EE":
gameLanguage = "et_ee";
break;
case "eu":
case "eu-ES":
gameLanguage = "eu_es";
break;
case "fa":
case "fa-IR":
gameLanguage = "fa_ir";
break;
case "fi":
case "fi-FI":
gameLanguage = "fi_fi";
break;
case "fil":
case "fil-PH":
gameLanguage = "fil_ph";
break;
case "tl":
case "tl-PH":
gameLanguage = "tl_ph";
break;
case "fo":
case "fo-FO":
gameLanguage = "fo_fo";
break;
case "fr":
case "fr-BE":
case "fr-FR":
case "fr-CH":
case "fr-LU":
case "fr-MC":
gameLanguage = "fr_fr";
break;
case "fr-CA":
gameLanguage = "fr_ca";
break;
case "gl":
case "gl-ES":
gameLanguage = "gl_es";
break;
case "gu":
case "gu-IN":
break;
case "he":
case "he-IL":
gameLanguage = "he_il";
break;
case "hi":
case "hi-IN":
gameLanguage = "hi_in";
break;
case "hr":
case "hr-BA":
case "hr-HR":
gameLanguage = "hr_hr";
break;
case "hu":
case "hu-HU":
gameLanguage = "hu_hu";
break;
case "hy":
case "hy-AM":
gameLanguage = "hy_am";
break;
case "id":
case "id-ID":
gameLanguage = "id_id";
break;
case "is":
case "is-IS":
gameLanguage = "is_is";
break;
case "it":
case "it-CH":
case "it-IT":
gameLanguage = "it_it";
break;
case "ja":
case "ja-JP":
gameLanguage = "ja_jp";
break;
case "ka":
case "ka-GE":
gameLanguage = "ka_ge";
break;
case "kk":
case "kk-KZ":
gameLanguage = "kk_kz";
break;
case "kn":
case "kn-IN":
gameLanguage = "kn_in";
break;
case "kok":
case "kok-IN":
break;
case "ko":
case "ko-KR":
gameLanguage = "ko_kr";
break;
case "ky":
case "ky-KG":
break;
case "lt":
case "lt-LT":
gameLanguage = "lt_lt";
break;
case "lv":
case "lv-LV":
gameLanguage = "lv_lv";
break;
case "mi-NZ":
break;
case "mk":
case "mk-MK":
gameLanguage = "mk_mk";
break;
case "mn":
case "mn-MN":
gameLanguage = "mn_mn";
break;
case "mr":
case "mr-IN":
break;
case "ms":
case "ms-BN":
case "ms-MY":
gameLanguage = "ms_my";
break;
case "mt-MT":
gameLanguage = "mt_mt";
break;
case "nb-NO":
gameLanguage = "no_no";
break;
case "nl":
case "nl-NL":
gameLanguage = "nl_nl";
break;
case "nl-BE":
gameLanguage = "nl_be";
break;
case "nn-NO":
gameLanguage = "nn_no";
break;
case "no":
gameLanguage = "no_no";
break;
case "ns-ZA":
break;
case "pa":
case "pa-IN":
break;
case "pl":
case "pl-PL":
gameLanguage = "pl_pl";
break;
case "pt":
case "pt-PT":
gameLanguage = "pt_pt";
break;
case "pt-BR":
gameLanguage = "pt_br";
break;
case "quz-BO":
break;
case "quz-EC":
break;
case "quz-PE":
break;
case "ro":
case "ro-RO":
gameLanguage = "ro_ro";
break;
case "ru":
case "ru-RU":
gameLanguage = "ru_ru";
break;
case "sa":
case "sa-IN":
break;
case "se-FI":
case "se-NO":
case "se-SE":
gameLanguage = "se_no";
break;
case "sk":
case "sk-SK":
gameLanguage = "sk_sk";
break;
case "sl":
case "sl-SI":
gameLanguage = "sl_si";
break;
case "sma-NO":
break;
case "sma-SE":
break;
case "smj-NO":
break;
case "smj-SE":
break;
case "smn-FI":
break;
case "sms-FI":
break;
case "sq":
case "sq-AL":
gameLanguage = "sq_al";
break;
case "sr":
case "sr-Cyrl-BA":
case "sr-Cyrl-CS":
case "sr-Latn-BA":
case "sr-Latn-CS":
gameLanguage = "sr_sp";
break;
case "sv":
case "sv-FI":
case "sv-SE":
gameLanguage = "sv_se";
break;
case "sw":
case "sw-KE":
break;
case "syr":
case "syr-SY":
break;
case "ta":
case "ta-IN":
gameLanguage = "ta_in";
break;
case "te":
case "te-IN":
break;
case "th":
case "th-TH":
gameLanguage = "th_th";
break;
case "tn-ZA":
break;
case "tr":
case "tr-TR":
gameLanguage = "tr_tr";
break;
case "tt":
case "tt-RU":
gameLanguage = "tt_ru";
break;
case "uk":
case "uk-UA":
gameLanguage = "uk_ua";
break;
case "ur":
case "ur-PK":
break;
case "uz":
case "uz-Cyrl-UZ":
case "uz-Latn-UZ":
break;
case "vi":
case "vi-VN":
gameLanguage = "vi_vn";
break;
case "xh-ZA":
break;
case "zh-Hans": /* CurrentCulture.Parent.Name */
case "zh":
case "zh-CN":
case "zh-CHS":
case "zh-SG":
gameLanguage = "zh_cn";
break;
case "zh-Hant": /* CurrentCulture.Parent.Name */
case "zh-HK":
case "zh-CHT":
case "zh-MO":
gameLanguage = "zh_hk";
break;
case "zh-TW":
gameLanguage = "zh_tw";
break;
case "zu-ZA":
break;
}
return gameLanguage;
}
2022-10-05 15:02:30 +08:00
2022-09-06 16:08:51 +02:00
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static string ToLowerIfNeed(string str)
{
2022-10-05 15:02:30 +08:00
const string lookupStringL = "---------------------------------!-#$%&-()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[-]^_`abcdefghijklmnopqrstuvwxyz{|}~-";
2022-09-06 16:08:51 +02:00
bool needLower = false;
foreach (Char c in str)
{
if (Char.IsUpper(c))
{
needLower = true;
break;
}
}
if (needLower)
{
StringBuilder sb = new(str);
for (int i = 0; i < str.Length; ++i)
if (char.IsUpper(sb[i]))
sb[i] = lookupStringL[sb[i]];
return sb.ToString();
}
else
{
return str;
}
}
2022-10-06 14:53:05 +08:00
2022-10-08 17:56:32 +08:00
public static int DoubleToTick(double time)
{
2026-03-23 14:29:04 +01:00
time = Math.Min(int.MaxValue / (double)ClientTicksPerSecond, time);
return (int)Math.Round(time * ClientTicksPerSecond);
2022-10-08 17:56:32 +08:00
}
2022-10-05 15:02:30 +08:00
}
2022-09-06 16:08:51 +02:00
2022-10-05 15:02:30 +08:00
public static class InternalCmdCharTypeExtensions
{
public static char ToChar(this InternalCmdCharType type)
{
2022-10-05 15:02:30 +08:00
return type switch
{
2022-10-05 15:02:30 +08:00
InternalCmdCharType.none => ' ',
InternalCmdCharType.slash => '/',
InternalCmdCharType.backslash => '\\',
_ => '/',
};
}
2022-10-05 15:02:30 +08:00
public static string ToLogString(this InternalCmdCharType type)
{
2022-10-05 15:02:30 +08:00
return type switch
{
2022-10-05 15:02:30 +08:00
InternalCmdCharType.none => string.Empty,
InternalCmdCharType.slash => @"/",
InternalCmdCharType.backslash => @"\",
_ => @"/",
};
}
2022-10-05 15:02:30 +08:00
}
2022-10-11 22:47:06 +02:00
2022-10-05 15:02:30 +08:00
public static class BrandInfoTypeExtensions
{
public static string? ToBrandString(this BrandInfoType info)
{
2022-10-05 15:02:30 +08:00
return info switch
{
2022-10-05 19:39:21 +08:00
BrandInfoType.mcc => "Minecraft-Console-Client/" + Program.Version,
2022-10-05 15:02:30 +08:00
BrandInfoType.vanilla => "vanilla",
BrandInfoType.empty => null,
_ => null,
};
}
}
2022-10-08 10:06:11 +08:00
public static class ExceptionExtensions
{
public static string GetFullMessage(this Exception ex)
{
2022-10-13 19:34:49 +08:00
string msg = ex.Message.Replace("+", "->");
return ex.InnerException is null
2022-10-13 19:34:49 +08:00
? msg
: msg + "\n --> " + ex.InnerException.GetFullMessage();
2022-10-08 10:06:11 +08:00
}
}
}