ConsoleComponent.cs 3.6 KB

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