DriverImpl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using System.Collections.Concurrent;
  2. using System.Runtime.InteropServices;
  3. namespace Terminal.Gui.Drivers;
  4. /// <summary>
  5. /// Provides the main implementation of the driver abstraction layer for Terminal.Gui.
  6. /// This implementation of <see cref="IDriver"/> coordinates the interaction between input processing, output
  7. /// rendering,
  8. /// screen size monitoring, and ANSI escape sequence handling.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>
  12. /// <see cref="DriverImpl"/> implements <see cref="IDriver"/>,
  13. /// serving as the central coordination point for console I/O operations. It delegates functionality
  14. /// to specialized components:
  15. /// </para>
  16. /// <list type="bullet">
  17. /// <item><see cref="IInputProcessor"/> - Processes keyboard and mouse input</item>
  18. /// <item><see cref="IOutputBuffer"/> - Manages the screen buffer state</item>
  19. /// <item><see cref="IOutput"/> - Handles actual console output rendering</item>
  20. /// <item><see cref="AnsiRequestScheduler"/> - Manages ANSI escape sequence requests</item>
  21. /// <item><see cref="ISizeMonitor"/> - Monitors terminal size changes</item>
  22. /// </list>
  23. /// <para>
  24. /// This class is internal and should not be used directly by application code.
  25. /// Applications interact with drivers through the <see cref="Application"/> class.
  26. /// </para>
  27. /// </remarks>
  28. internal class DriverImpl : IDriver
  29. {
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="DriverImpl"/> class.
  32. /// </summary>
  33. /// <param name="inputProcessor">The input processor for handling keyboard and mouse events.</param>
  34. /// <param name="outputBuffer">The output buffer for managing screen state.</param>
  35. /// <param name="output">The output interface for rendering to the console.</param>
  36. /// <param name="ansiRequestScheduler">The scheduler for managing ANSI escape sequence requests.</param>
  37. /// <param name="sizeMonitor">The monitor for tracking terminal size changes.</param>
  38. public DriverImpl (
  39. IInputProcessor inputProcessor,
  40. IOutputBuffer outputBuffer,
  41. IOutput output,
  42. AnsiRequestScheduler ansiRequestScheduler,
  43. ISizeMonitor sizeMonitor
  44. )
  45. {
  46. InputProcessor = inputProcessor;
  47. _output = output;
  48. OutputBuffer = outputBuffer;
  49. _ansiRequestScheduler = ansiRequestScheduler;
  50. InputProcessor.KeyDown += (s, e) => KeyDown?.Invoke (s, e);
  51. InputProcessor.KeyUp += (s, e) => KeyUp?.Invoke (s, e);
  52. InputProcessor.MouseEvent += (s, e) =>
  53. {
  54. //Logging.Logger.LogTrace ($"Mouse {e.Flags} at x={e.ScreenPosition.X} y={e.ScreenPosition.Y}");
  55. MouseEvent?.Invoke (s, e);
  56. };
  57. SizeMonitor = sizeMonitor;
  58. SizeMonitor.SizeChanged += OnSizeMonitorOnSizeChanged;
  59. CreateClipboard ();
  60. Driver.Force16ColorsChanged += OnDriverOnForce16ColorsChanged;
  61. }
  62. #region Driver Lifecycle
  63. /// <inheritdoc/>
  64. public void Init () { throw new NotSupportedException (); }
  65. /// <inheritdoc/>
  66. public void Refresh () { _output.Write (OutputBuffer); }
  67. /// <inheritdoc/>
  68. public string? GetName () => InputProcessor.DriverName?.ToLowerInvariant ();
  69. /// <inheritdoc/>
  70. public virtual string GetVersionInfo ()
  71. {
  72. string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName));
  73. return type;
  74. }
  75. /// <inheritdoc/>
  76. public void Suspend ()
  77. {
  78. // BUGBUG: This is all platform-specific and should not be implemented here.
  79. // BUGBUG: This needs to be in each platform's driver implementation.
  80. if (Environment.OSVersion.Platform != PlatformID.Unix)
  81. {
  82. return;
  83. }
  84. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  85. try
  86. {
  87. Console.ResetColor ();
  88. Console.Clear ();
  89. //Disable alternative screen buffer.
  90. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  91. //Set cursor key to cursor.
  92. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  93. Platform.Suspend ();
  94. //Enable alternative screen buffer.
  95. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  96. }
  97. catch (Exception ex)
  98. {
  99. Logging.Error ($"Error suspending terminal: {ex.Message}");
  100. }
  101. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  102. }
  103. /// <inheritdoc/>
  104. public bool IsLegacyConsole
  105. {
  106. get => _output.IsLegacyConsole;
  107. set => _output.IsLegacyConsole = value;
  108. }
  109. /// <inheritdoc/>
  110. public void Dispose ()
  111. {
  112. SizeMonitor.SizeChanged -= OnSizeMonitorOnSizeChanged;
  113. Driver.Force16ColorsChanged -= OnDriverOnForce16ColorsChanged;
  114. _output.Dispose ();
  115. }
  116. #endregion Driver Lifecycle
  117. #region Driver Components
  118. private readonly IOutput _output;
  119. /// <inheritdoc/>
  120. public IInputProcessor InputProcessor { get; }
  121. /// <inheritdoc/>
  122. public IOutputBuffer OutputBuffer { get; }
  123. /// <inheritdoc/>
  124. public ISizeMonitor SizeMonitor { get; }
  125. /// <inheritdoc/>
  126. public IClipboard? Clipboard { get; private set; } = new FakeClipboard ();
  127. private void CreateClipboard ()
  128. {
  129. if (InputProcessor.DriverName is { } && InputProcessor.DriverName.Contains ("fake"))
  130. {
  131. if (Clipboard is null)
  132. {
  133. Clipboard = new FakeClipboard ();
  134. }
  135. return;
  136. }
  137. PlatformID p = Environment.OSVersion.Platform;
  138. if (p is PlatformID.Win32NT or PlatformID.Win32S or PlatformID.Win32Windows)
  139. {
  140. Clipboard = new WindowsClipboard ();
  141. }
  142. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  143. {
  144. Clipboard = new MacOSXClipboard ();
  145. }
  146. else if (PlatformDetection.IsWSLPlatform ())
  147. {
  148. Clipboard = new WSLClipboard ();
  149. }
  150. // Clipboard is set to FakeClipboard at initialization
  151. }
  152. #endregion Driver Components
  153. #region Screen and Display
  154. /// <inheritdoc/>
  155. public Rectangle Screen => new (0, 0, OutputBuffer.Cols, OutputBuffer.Rows);
  156. /// <inheritdoc/>
  157. public virtual void SetScreenSize (int width, int height)
  158. {
  159. OutputBuffer.SetSize (width, height);
  160. _output.SetSize (width, height);
  161. SizeChanged?.Invoke (this, new (new (width, height)));
  162. }
  163. /// <inheritdoc/>
  164. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  165. private void OnSizeMonitorOnSizeChanged (object? _, SizeChangedEventArgs e) { SetScreenSize (e.Size!.Value.Width, e.Size.Value.Height); }
  166. /// <inheritdoc/>
  167. public int Cols
  168. {
  169. get => OutputBuffer.Cols;
  170. set => OutputBuffer.Cols = value;
  171. }
  172. /// <inheritdoc/>
  173. public int Rows
  174. {
  175. get => OutputBuffer.Rows;
  176. set => OutputBuffer.Rows = value;
  177. }
  178. /// <inheritdoc/>
  179. public int Left
  180. {
  181. get => OutputBuffer.Left;
  182. set => OutputBuffer.Left = value;
  183. }
  184. /// <inheritdoc/>
  185. public int Top
  186. {
  187. get => OutputBuffer.Top;
  188. set => OutputBuffer.Top = value;
  189. }
  190. #endregion Screen and Display
  191. #region Color Support
  192. /// <inheritdoc/>
  193. public bool SupportsTrueColor => !IsLegacyConsole;
  194. /// <inheritdoc/>
  195. public bool Force16Colors
  196. {
  197. get => _output.Force16Colors;
  198. set => _output.Force16Colors = value;
  199. }
  200. private void OnDriverOnForce16ColorsChanged (object? _, ValueChangedEventArgs<bool> e) { Force16Colors = e.NewValue; }
  201. #endregion Color Support
  202. #region Content Buffer
  203. /// <inheritdoc/>
  204. public Cell [,]? Contents
  205. {
  206. get => OutputBuffer.Contents;
  207. set => OutputBuffer.Contents = value;
  208. }
  209. /// <inheritdoc/>
  210. public Region? Clip
  211. {
  212. get => OutputBuffer.Clip;
  213. set => OutputBuffer.Clip = value;
  214. }
  215. /// <summary>Clears the <see cref="IDriver.Contents"/> of the driver.</summary>
  216. public void ClearContents ()
  217. {
  218. OutputBuffer.ClearContents ();
  219. ClearedContents?.Invoke (this, new MouseEventArgs ());
  220. }
  221. /// <inheritdoc/>
  222. public event EventHandler<EventArgs>? ClearedContents;
  223. #endregion Content Buffer
  224. #region Drawing and Rendering
  225. /// <inheritdoc/>
  226. public int Col => OutputBuffer.Col;
  227. /// <inheritdoc/>
  228. public int Row => OutputBuffer.Row;
  229. /// <inheritdoc/>
  230. public Attribute CurrentAttribute
  231. {
  232. get => OutputBuffer.CurrentAttribute;
  233. set => OutputBuffer.CurrentAttribute = value;
  234. }
  235. /// <inheritdoc/>
  236. public void Move (int col, int row) { OutputBuffer.Move (col, row); }
  237. /// <inheritdoc/>
  238. public bool IsRuneSupported (Rune rune) => Rune.IsValid (rune.Value);
  239. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  240. /// <param name="text">Used to determine if one or two columns are required.</param>
  241. /// <param name="col">The column.</param>
  242. /// <param name="row">The row.</param>
  243. /// <returns>
  244. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of
  245. /// <see cref="IDriver.Clip"/>.
  246. /// <see langword="true"/> otherwise.
  247. /// </returns>
  248. public bool IsValidLocation (string text, int col, int row) => OutputBuffer.IsValidLocation (text, col, row);
  249. /// <inheritdoc/>
  250. public void AddRune (Rune rune) { OutputBuffer.AddRune (rune); }
  251. /// <inheritdoc/>
  252. public void AddRune (char c) { OutputBuffer.AddRune (c); }
  253. /// <inheritdoc/>
  254. public void AddStr (string str) { OutputBuffer.AddStr (str); }
  255. /// <inheritdoc/>
  256. public void FillRect (Rectangle rect, Rune rune = default) { OutputBuffer.FillRect (rect, rune); }
  257. /// <inheritdoc/>
  258. public void FillRect (Rectangle rect, char c) { OutputBuffer.FillRect (rect, c); }
  259. /// <inheritdoc/>
  260. public Attribute SetAttribute (Attribute newAttribute)
  261. {
  262. Attribute currentAttribute = OutputBuffer.CurrentAttribute;
  263. OutputBuffer.CurrentAttribute = newAttribute;
  264. return currentAttribute;
  265. }
  266. /// <inheritdoc/>
  267. public Attribute GetAttribute () => OutputBuffer.CurrentAttribute;
  268. /// <inheritdoc/>
  269. public void WriteRaw (string ansi) { _output.Write (ansi); }
  270. /// <inheritdoc/>
  271. public ConcurrentQueue<SixelToRender> GetSixels () => _output.GetSixels ();
  272. /// <inheritdoc/>
  273. public new string ToString ()
  274. {
  275. StringBuilder sb = new ();
  276. Cell [,] contents = Contents!;
  277. for (var r = 0; r < Rows; r++)
  278. {
  279. for (var c = 0; c < Cols; c++)
  280. {
  281. string text = contents [r, c].Grapheme;
  282. sb.Append (text);
  283. if (text.GetColumns () > 1)
  284. {
  285. c++;
  286. }
  287. }
  288. sb.AppendLine ();
  289. }
  290. return sb.ToString ();
  291. }
  292. /// <inheritdoc/>
  293. public string ToAnsi () => _output.ToAnsi (OutputBuffer);
  294. #endregion Drawing and Rendering
  295. #region Cursor
  296. private CursorVisibility _lastCursor = CursorVisibility.Default;
  297. /// <inheritdoc/>
  298. public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }
  299. /// <inheritdoc/>
  300. public bool GetCursorVisibility (out CursorVisibility current)
  301. {
  302. current = _lastCursor;
  303. return true;
  304. }
  305. /// <inheritdoc/>
  306. public bool SetCursorVisibility (CursorVisibility visibility)
  307. {
  308. _lastCursor = visibility;
  309. _output.SetCursorVisibility (visibility);
  310. return true;
  311. }
  312. #endregion Cursor
  313. #region Input Events
  314. /// <summary>Event fired when a mouse event occurs.</summary>
  315. public event EventHandler<MouseEventArgs>? MouseEvent;
  316. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="IDriver.KeyUp"/>.</summary>
  317. public event EventHandler<Key>? KeyDown;
  318. /// <inheritdoc/>
  319. public event EventHandler<Key>? KeyUp;
  320. /// <inheritdoc/>
  321. public void EnqueueKeyEvent (Key key) { InputProcessor.EnqueueKeyDownEvent (key); }
  322. #endregion Input Events
  323. #region ANSI Escape Sequences
  324. private readonly AnsiRequestScheduler _ansiRequestScheduler;
  325. /// <inheritdoc/>
  326. public virtual void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (this, request); }
  327. #endregion ANSI Escape Sequences
  328. }