ReplComponentSystem.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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
  15. .WithMetadataResolver(ScriptMetadataResolver.Default.WithBaseDirectory(Environment.CurrentDirectory))
  16. .AddReferences(typeof (ReplComponent).Assembly)
  17. .AddImports("System");
  18. self.Run().NoAwait();
  19. }
  20. }
  21. [ObjectSystem]
  22. public class ReplComponentLoadSystem : LoadSystem<ReplComponent>
  23. {
  24. public override void Load(ReplComponent self)
  25. {
  26. self.CancellationTokenSource?.Cancel();
  27. self.ScriptState = null;
  28. self.Run().NoAwait();
  29. }
  30. }
  31. public static class ReplComponentHelper
  32. {
  33. public static async ETVoid Run(this ReplComponent self)
  34. {
  35. self.CancellationTokenSource = new CancellationTokenSource();
  36. while (true)
  37. {
  38. try
  39. {
  40. string line = await Task.Factory.StartNew(() =>
  41. {
  42. Console.Out.Write("> ");
  43. return Console.In.ReadLine();
  44. }, self.CancellationTokenSource.Token);
  45. line = line.Trim();
  46. if (line == "exit")
  47. {
  48. self.ScriptState = null;
  49. continue;
  50. }
  51. if (self.ScriptState == null)
  52. {
  53. self.ScriptState = await CSharpScript.RunAsync(line, self.ScriptOptions, cancellationToken: self.CancellationTokenSource.Token);
  54. }
  55. else
  56. {
  57. self.ScriptState = await self.ScriptState.ContinueWithAsync(line, cancellationToken: self.CancellationTokenSource.Token);
  58. }
  59. }
  60. catch (Exception e)
  61. {
  62. Console.WriteLine(e);
  63. }
  64. }
  65. }
  66. }
  67. }