ConsoleViewModel.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Avalonia.Collections;
  5. using Avalonia.Diagnostics.Models;
  6. using Microsoft.CodeAnalysis.CSharp.Scripting;
  7. using Microsoft.CodeAnalysis.Scripting;
  8. namespace Avalonia.Diagnostics.ViewModels
  9. {
  10. internal class ConsoleViewModel : ViewModelBase
  11. {
  12. private readonly ConsoleContext _context;
  13. private readonly Action<ConsoleContext> _updateContext;
  14. private int _historyIndex = -1;
  15. private string _input;
  16. private bool _isVisible;
  17. private ScriptState<object> _state;
  18. public ConsoleViewModel(Action<ConsoleContext> updateContext)
  19. {
  20. _context = new ConsoleContext(this);
  21. _updateContext = updateContext;
  22. }
  23. public string Input
  24. {
  25. get => _input;
  26. set => RaiseAndSetIfChanged(ref _input, value);
  27. }
  28. public bool IsVisible
  29. {
  30. get => _isVisible;
  31. set => RaiseAndSetIfChanged(ref _isVisible, value);
  32. }
  33. public AvaloniaList<ConsoleHistoryItem> History { get; } = new AvaloniaList<ConsoleHistoryItem>();
  34. public async Task Execute()
  35. {
  36. if (string.IsNullOrWhiteSpace(Input))
  37. {
  38. return;
  39. }
  40. try
  41. {
  42. var options = ScriptOptions.Default
  43. .AddReferences(Assembly.GetAssembly(typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo)));
  44. _updateContext(_context);
  45. if (_state == null)
  46. {
  47. _state = await CSharpScript.RunAsync(Input, options: options, globals: _context);
  48. }
  49. else
  50. {
  51. _state = await _state.ContinueWithAsync(Input);
  52. }
  53. if (_state.ReturnValue != ConsoleContext.NoOutput)
  54. {
  55. History.Add(new ConsoleHistoryItem(Input, _state.ReturnValue ?? "(null)"));
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. History.Add(new ConsoleHistoryItem(Input, ex));
  61. }
  62. Input = string.Empty;
  63. _historyIndex = -1;
  64. }
  65. public void HistoryUp()
  66. {
  67. if (History.Count > 0)
  68. {
  69. if (_historyIndex == -1)
  70. {
  71. _historyIndex = History.Count - 1;
  72. }
  73. else if (_historyIndex > 0)
  74. {
  75. --_historyIndex;
  76. }
  77. Input = History[_historyIndex].Input;
  78. }
  79. }
  80. public void HistoryDown()
  81. {
  82. if (History.Count > 0 && _historyIndex >= 0)
  83. {
  84. if (_historyIndex == History.Count - 1)
  85. {
  86. _historyIndex = -1;
  87. Input = string.Empty;
  88. }
  89. else
  90. {
  91. Input = History[++_historyIndex].Input;
  92. }
  93. }
  94. }
  95. public void ToggleVisibility() => IsVisible = !IsVisible;
  96. }
  97. }