ConsoleComponent.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ETModel
  5. {
  6. [ObjectSystem]
  7. public class ConsoleComponentAwakeSystem : StartSystem<ConsoleComponent>
  8. {
  9. public override void Start(ConsoleComponent self)
  10. {
  11. self.Start().NoAwait();
  12. }
  13. }
  14. public static class ConsoleMode
  15. {
  16. public const string None = "";
  17. public const string Repl = "repl";
  18. }
  19. public class ConsoleComponent: Entity
  20. {
  21. public CancellationTokenSource CancellationTokenSource;
  22. public string Mode = "";
  23. public async ETVoid Start()
  24. {
  25. this.CancellationTokenSource = new CancellationTokenSource();
  26. while (true)
  27. {
  28. try
  29. {
  30. string line = await Task.Factory.StartNew(() =>
  31. {
  32. Console.Write($"{this.Mode}> ");
  33. return Console.In.ReadLine();
  34. }, this.CancellationTokenSource.Token);
  35. line = line.Trim();
  36. if (this.Mode != "")
  37. {
  38. bool isExited = true;
  39. switch (this.Mode)
  40. {
  41. case ConsoleMode.Repl:
  42. {
  43. ReplComponent replComponent = this.GetComponent<ReplComponent>();
  44. if (replComponent == null)
  45. {
  46. Console.WriteLine($"no command: {line}!");
  47. break;
  48. }
  49. try
  50. {
  51. isExited = await replComponent.Run(line, this.CancellationTokenSource.Token);
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e);
  56. }
  57. break;
  58. }
  59. }
  60. if (isExited)
  61. {
  62. this.Mode = "";
  63. }
  64. continue;
  65. }
  66. switch (line)
  67. {
  68. case "reload":
  69. try
  70. {
  71. Game.EventSystem.Add(DLLType.Hotfix, DllHelper.GetHotfixAssembly());
  72. }
  73. catch (Exception e)
  74. {
  75. Console.WriteLine(e);
  76. }
  77. break;
  78. case "repl":
  79. try
  80. {
  81. this.Mode = ConsoleMode.Repl;
  82. this.AddComponent<ReplComponent>();
  83. }
  84. catch (Exception e)
  85. {
  86. Console.WriteLine(e);
  87. }
  88. break;
  89. default:
  90. Console.WriteLine($"no such command: {line}");
  91. break;
  92. }
  93. }
  94. catch (Exception e)
  95. {
  96. Console.WriteLine(e);
  97. }
  98. }
  99. }
  100. }
  101. }