SixelSupportDetector.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. using System.Text.RegularExpressions;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Uses Ansi escape sequences to detect whether sixel is supported
  5. /// by the terminal.
  6. /// </summary>
  7. public class SixelSupportDetector
  8. {
  9. /// <summary>
  10. /// Sends Ansi escape sequences to the console to determine whether
  11. /// sixel is supported (and <see cref="SixelSupportResult.Resolution"/>
  12. /// etc).
  13. /// </summary>
  14. /// <returns>Description of sixel support, may include assumptions where
  15. /// expected response codes are not returned by console.</returns>
  16. public void Detect (Action<SixelSupportResult> resultCallback)
  17. {
  18. var result = new SixelSupportResult ();
  19. result.SupportsTransparency = IsWindowsTerminal () || IsXtermWithTransparency ();
  20. IsSixelSupportedByDar (result, resultCallback);
  21. }
  22. private void TryGetResolutionDirectly (SixelSupportResult result, Action<SixelSupportResult> resultCallback)
  23. {
  24. // Expect something like:
  25. //<esc>[6;20;10t
  26. QueueRequest (EscSeqUtils.CSI_RequestSixelResolution,
  27. (r) =>
  28. {
  29. // Terminal supports directly responding with resolution
  30. var match = Regex.Match (r, @"\[\d+;(\d+);(\d+)t$");
  31. if (match.Success)
  32. {
  33. if (int.TryParse (match.Groups [1].Value, out var ry) &&
  34. int.TryParse (match.Groups [2].Value, out var rx))
  35. {
  36. result.Resolution = new Size (rx, ry);
  37. }
  38. }
  39. // Finished
  40. resultCallback.Invoke (result);
  41. },
  42. // Request failed, so try to compute instead
  43. ()=>TryComputeResolution (result,resultCallback));
  44. }
  45. private void TryComputeResolution (SixelSupportResult result, Action<SixelSupportResult> resultCallback)
  46. {
  47. string windowSize;
  48. string sizeInChars;
  49. QueueRequest (EscSeqUtils.CSI_RequestWindowSizeInPixels,
  50. (r1)=>
  51. {
  52. windowSize = r1;
  53. QueueRequest (EscSeqUtils.CSI_ReportTerminalSizeInChars,
  54. (r2) =>
  55. {
  56. sizeInChars = r2;
  57. ComputeResolution (result,windowSize,sizeInChars);
  58. resultCallback (result);
  59. }, abandoned: () => resultCallback (result));
  60. },abandoned: ()=>resultCallback(result));
  61. }
  62. private void ComputeResolution (SixelSupportResult result, string windowSize, string sizeInChars)
  63. {
  64. // Fallback to window size in pixels and characters
  65. // Example [4;600;1200t
  66. var pixelMatch = Regex.Match (windowSize, @"\[\d+;(\d+);(\d+)t$");
  67. // Example [8;30;120t
  68. var charMatch = Regex.Match (sizeInChars, @"\[\d+;(\d+);(\d+)t$");
  69. if (pixelMatch.Success && charMatch.Success)
  70. {
  71. // Extract pixel dimensions
  72. if (int.TryParse (pixelMatch.Groups [1].Value, out var pixelHeight)
  73. && int.TryParse (pixelMatch.Groups [2].Value, out var pixelWidth)
  74. &&
  75. // Extract character dimensions
  76. int.TryParse (charMatch.Groups [1].Value, out var charHeight)
  77. && int.TryParse (charMatch.Groups [2].Value, out var charWidth)
  78. && charWidth != 0
  79. && charHeight != 0) // Avoid divide by zero
  80. {
  81. // Calculate the character cell size in pixels
  82. var cellWidth = (int)Math.Round ((double)pixelWidth / charWidth);
  83. var cellHeight = (int)Math.Round ((double)pixelHeight / charHeight);
  84. // Set the resolution based on the character cell size
  85. result.Resolution = new Size (cellWidth, cellHeight);
  86. }
  87. }
  88. }
  89. private void IsSixelSupportedByDar (SixelSupportResult result,Action<SixelSupportResult> resultCallback)
  90. {
  91. QueueRequest (
  92. EscSeqUtils.CSI_SendDeviceAttributes,
  93. (r) =>
  94. {
  95. result.IsSupported = ResponseIndicatesSupport (r);
  96. if (result.IsSupported)
  97. {
  98. TryGetResolutionDirectly (result, resultCallback);
  99. }
  100. else
  101. {
  102. resultCallback (result);
  103. }
  104. },abandoned: () => resultCallback(result));
  105. }
  106. private void QueueRequest (AnsiEscapeSequenceRequest req, Action<string> responseCallback, Action abandoned)
  107. {
  108. var newRequest = new AnsiEscapeSequenceRequest
  109. {
  110. Request = req.Request,
  111. Terminator = req.Terminator,
  112. ResponseReceived = responseCallback,
  113. Abandoned = abandoned
  114. };
  115. Application.Driver.QueueAnsiRequest (newRequest);
  116. }
  117. private bool ResponseIndicatesSupport (string response)
  118. {
  119. return response.Split (';').Contains ("4");
  120. }
  121. private bool IsWindowsTerminal ()
  122. {
  123. return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable ("WT_SESSION"));;
  124. }
  125. private bool IsXtermWithTransparency ()
  126. {
  127. // Check if running in real xterm (XTERM_VERSION is more reliable than TERM)
  128. var xtermVersionStr = Environment.GetEnvironmentVariable ("XTERM_VERSION");
  129. // If XTERM_VERSION exists, we are in a real xterm
  130. if (!string.IsNullOrWhiteSpace (xtermVersionStr) && int.TryParse (xtermVersionStr, out var xtermVersion) && xtermVersion >= 370)
  131. {
  132. return true;
  133. }
  134. return false;
  135. }
  136. }