AnsiEscapeSequenceRequest.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Describes an ongoing ANSI request sent to the console.
  5. /// Use <see cref="ResponseReceived"/> to handle the response
  6. /// when console answers the request.
  7. /// </summary>
  8. public class AnsiEscapeSequenceRequest
  9. {
  10. internal readonly object _responseLock = new (); // Per-instance lock
  11. /// <summary>
  12. /// Request to send e.g. see
  13. /// <see>
  14. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  15. /// </see>
  16. /// </summary>
  17. public required string Request { get; init; }
  18. /// <summary>
  19. /// Response received from the request.
  20. /// </summary>
  21. public string Response { get; internal set; } = string.Empty;
  22. /// <summary>
  23. /// Invoked when the console responds with an ANSI response code that matches the
  24. /// <see cref="Terminator"/>
  25. /// </summary>
  26. public event EventHandler<AnsiEscapeSequenceResponse>? ResponseReceived;
  27. /// <summary>
  28. /// <para>
  29. /// The terminator that uniquely identifies the type of response as responded
  30. /// by the console. e.g. for
  31. /// <see>
  32. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  33. /// </see>
  34. /// the terminator is
  35. /// <see>
  36. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Terminator</cref>
  37. /// </see>
  38. /// .
  39. /// </para>
  40. /// <para>
  41. /// After sending a request, the first response with matching terminator will be matched
  42. /// to the oldest outstanding request.
  43. /// </para>
  44. /// </summary>
  45. public required string Terminator { get; init; }
  46. /// <summary>
  47. /// Execute an ANSI escape sequence escape which may return a response or error.
  48. /// </summary>
  49. /// <param name="ansiRequest">The ANSI escape sequence to request.</param>
  50. /// <param name="result">
  51. /// When this method returns <see langword="true"/>, an object containing the response with an empty
  52. /// error.
  53. /// </param>
  54. /// <returns>A <see cref="AnsiEscapeSequenceResponse"/> with the response, error, terminator and value.</returns>
  55. public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result)
  56. {
  57. var error = new StringBuilder ();
  58. var values = new string? [] { null };
  59. try
  60. {
  61. ConsoleDriver? driver = Application.Driver;
  62. // Send the ANSI escape sequence
  63. ansiRequest.Response = driver?.WriteAnsiRequest (ansiRequest)!;
  64. if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (EscSeqUtils.KeyEsc))
  65. {
  66. throw new InvalidOperationException ("Invalid escape character!");
  67. }
  68. if (string.IsNullOrEmpty (ansiRequest.Terminator))
  69. {
  70. throw new InvalidOperationException ("Terminator request is empty.");
  71. }
  72. if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1]))
  73. {
  74. string resp = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response.Last ().ToString ();
  75. throw new InvalidOperationException ($"Terminator ends with '{resp}'\nand doesn't end with: '{ansiRequest.Terminator [^1]}'");
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. error.AppendLine ($"Error executing ANSI request:\n{ex.Message}");
  81. }
  82. finally
  83. {
  84. if (string.IsNullOrEmpty (error.ToString ()))
  85. {
  86. (string? _, string? _, values, string? _) = EscSeqUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ());
  87. }
  88. }
  89. AnsiEscapeSequenceResponse ansiResponse = new ()
  90. {
  91. Response = ansiRequest.Response, Error = error.ToString (),
  92. Terminator = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response [^1].ToString (), Value = values [0]
  93. };
  94. // Invoke the event if it's subscribed
  95. ansiRequest.ResponseReceived?.Invoke (ansiRequest, ansiResponse);
  96. result = ansiResponse;
  97. return string.IsNullOrWhiteSpace (result.Error) && !string.IsNullOrWhiteSpace (result.Response);
  98. }
  99. /// <summary>
  100. /// The value expected in the response e.g.
  101. /// <see>
  102. /// <cref>EscSeqUtils.CSI_ReportTerminalSizeInChars.Value</cref>
  103. /// </see>
  104. /// which will have a 't' as terminator but also other different request may return the same terminator with a
  105. /// different value.
  106. /// </summary>
  107. public string? Value { get; init; }
  108. internal void RaiseResponseFromInput (AnsiEscapeSequenceRequest ansiRequest, string response) { ResponseFromInput?.Invoke (ansiRequest, response); }
  109. internal event EventHandler<string>? ResponseFromInput;
  110. }