ReplComponentSystem.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using ETModel;
  5. using Microsoft.CodeAnalysis.Scripting;
  6. using Microsoft.CodeAnalysis.CSharp.Scripting;
  7. namespace ETHotfix
  8. {
  9. [ObjectSystem]
  10. public class ReplComponentStartSystem : StartSystem<ReplComponent>
  11. {
  12. public override void Start(ReplComponent self)
  13. {
  14. self.ScriptOptions = ScriptOptions.Default.WithFilePath(Environment.CurrentDirectory)
  15. .AddReferences(typeof (ReplComponent).Assembly);
  16. self.Run().NoAwait();
  17. }
  18. }
  19. [ObjectSystem]
  20. public class ReplComponentLoadSystem : LoadSystem<ReplComponent>
  21. {
  22. public override void Load(ReplComponent self)
  23. {
  24. self.CancellationTokenSource?.Cancel();
  25. self.ScriptState = null;
  26. self.Run().NoAwait();
  27. }
  28. }
  29. public static class ReplComponentHelper
  30. {
  31. public static async ETVoid Run(this ReplComponent self)
  32. {
  33. self.CancellationTokenSource = new CancellationTokenSource();
  34. while (true)
  35. {
  36. try
  37. {
  38. string line = await Task.Factory.StartNew(() =>
  39. {
  40. Console.Out.Write("> ");
  41. return Console.In.ReadLine();
  42. }, self.CancellationTokenSource.Token);
  43. line = line.Trim();
  44. if (line == "quit")
  45. {
  46. self.ScriptState = null;
  47. continue;
  48. }
  49. if (self.ScriptState == null)
  50. {
  51. self.ScriptState = await CSharpScript.RunAsync(line, self.ScriptOptions, cancellationToken: self.CancellationTokenSource.Token);
  52. }
  53. else
  54. {
  55. self.ScriptState = await self.ScriptState.ContinueWithAsync(line, cancellationToken: self.CancellationTokenSource.Token);
  56. }
  57. }
  58. catch (Exception e)
  59. {
  60. Console.WriteLine(e);
  61. }
  62. }
  63. }
  64. }
  65. }