DriverImpl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. GetInputProcessor ().KeyDown += (s, e) => KeyDown?.Invoke (s, e);
  51. GetInputProcessor ().KeyUp += (s, e) => KeyUp?.Invoke (s, e);
  52. GetInputProcessor ().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 ()
  67. {
  68. _output.Write (OutputBuffer);
  69. }
  70. /// <inheritdoc/>
  71. public string? GetName () => GetInputProcessor ().DriverName?.ToLowerInvariant ();
  72. /// <inheritdoc/>
  73. public virtual string GetVersionInfo ()
  74. {
  75. string type = GetInputProcessor ().DriverName ?? throw new InvalidOperationException ("Driver name is not set.");
  76. return type;
  77. }
  78. /// <inheritdoc/>
  79. public void Suspend ()
  80. {
  81. // BUGBUG: This is all platform-specific and should not be implemented here.
  82. // BUGBUG: This needs to be in each platform's driver implementation.
  83. if (Environment.OSVersion.Platform != PlatformID.Unix)
  84. {
  85. return;
  86. }
  87. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  88. try
  89. {
  90. Console.ResetColor ();
  91. Console.Clear ();
  92. //Disable alternative screen buffer.
  93. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  94. //Set cursor key to cursor.
  95. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  96. Platform.Suspend ();
  97. //Enable alternative screen buffer.
  98. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  99. }
  100. catch (Exception ex)
  101. {
  102. Logging.Error ($"Error suspending terminal: {ex.Message}");
  103. }
  104. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  105. }
  106. /// <inheritdoc/>
  107. public bool IsLegacyConsole
  108. {
  109. get => _output.IsLegacyConsole;
  110. set => _output.IsLegacyConsole = value;
  111. }
  112. /// <inheritdoc/>
  113. public void Dispose ()
  114. {
  115. SizeMonitor.SizeChanged -= OnSizeMonitorOnSizeChanged;
  116. Driver.Force16ColorsChanged -= OnDriverOnForce16ColorsChanged;
  117. _output.Dispose ();
  118. }
  119. #endregion Driver Lifecycle
  120. #region Driver Components
  121. private readonly IOutput _output;
  122. public IOutput GetOutput () => _output;
  123. private readonly IInputProcessor _inputProcessor;
  124. /// <inheritdoc/>
  125. public IInputProcessor GetInputProcessor () => _inputProcessor;
  126. /// <inheritdoc/>
  127. public IOutputBuffer OutputBuffer { get; }
  128. /// <inheritdoc/>
  129. public ISizeMonitor SizeMonitor { get; }
  130. /// <inheritdoc/>
  131. public IClipboard? Clipboard { get; private set; } = new FakeClipboard ();
  132. private void CreateClipboard ()
  133. {
  134. if (GetInputProcessor ().DriverName is { } && GetInputProcessor ()!.DriverName!.Contains ("fake"))
  135. {
  136. if (Clipboard is null)
  137. {
  138. Clipboard = new FakeClipboard ();
  139. }
  140. return;
  141. }
  142. PlatformID p = Environment.OSVersion.Platform;
  143. if (p is PlatformID.Win32NT or PlatformID.Win32S or PlatformID.Win32Windows)
  144. {
  145. Clipboard = new WindowsClipboard ();
  146. }
  147. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  148. {
  149. Clipboard = new MacOSXClipboard ();
  150. }
  151. else if (PlatformDetection.IsWSLPlatform ())
  152. {
  153. Clipboard = new WSLClipboard ();
  154. }
  155. // Clipboard is set to FakeClipboard at initialization
  156. }
  157. #endregion Driver Components
  158. #region Screen and Display
  159. /// <inheritdoc/>
  160. public Rectangle Screen => new (0, 0, OutputBuffer.Cols, OutputBuffer.Rows);
  161. /// <inheritdoc/>
  162. public virtual void SetScreenSize (int width, int height)
  163. {
  164. OutputBuffer.SetSize (width, height);
  165. _output.SetSize (width, height);
  166. SizeChanged?.Invoke (this, new (new (width, height)));
  167. }
  168. /// <inheritdoc/>
  169. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  170. private void OnSizeMonitorOnSizeChanged (object? _, SizeChangedEventArgs e) { SetScreenSize (e.Size!.Value.Width, e.Size.Value.Height); }
  171. /// <inheritdoc/>
  172. public int Cols
  173. {
  174. get => OutputBuffer.Cols;
  175. set => OutputBuffer.Cols = value;
  176. }
  177. /// <inheritdoc/>
  178. public int Rows
  179. {
  180. get => OutputBuffer.Rows;
  181. set => OutputBuffer.Rows = value;
  182. }
  183. /// <inheritdoc/>
  184. public int Left
  185. {
  186. get => OutputBuffer.Left;
  187. set => OutputBuffer.Left = value;
  188. }
  189. /// <inheritdoc/>
  190. public int Top
  191. {
  192. get => OutputBuffer.Top;
  193. set => OutputBuffer.Top = value;
  194. }
  195. #endregion Screen and Display
  196. #region Color Support
  197. /// <inheritdoc/>
  198. public bool SupportsTrueColor => !IsLegacyConsole;
  199. /// <inheritdoc/>
  200. public bool Force16Colors
  201. {
  202. get => _output.Force16Colors;
  203. set => _output.Force16Colors = value;
  204. }
  205. private void OnDriverOnForce16ColorsChanged (object? _, ValueChangedEventArgs<bool> e) { Force16Colors = e.NewValue; }
  206. #endregion Color Support
  207. #region Content Buffer
  208. /// <inheritdoc/>
  209. public Cell [,]? Contents
  210. {
  211. get => OutputBuffer.Contents;
  212. set => OutputBuffer.Contents = value;
  213. }
  214. /// <inheritdoc/>
  215. public Region? Clip
  216. {
  217. get => OutputBuffer.Clip;
  218. set => OutputBuffer.Clip = value;
  219. }
  220. /// <summary>Clears the <see cref="IDriver.Contents"/> of the driver.</summary>
  221. public void ClearContents ()
  222. {
  223. OutputBuffer.ClearContents ();
  224. ClearedContents?.Invoke (this, new MouseEventArgs ());
  225. }
  226. /// <inheritdoc/>
  227. public event EventHandler<EventArgs>? ClearedContents;
  228. #endregion Content Buffer
  229. #region Drawing and Rendering
  230. /// <inheritdoc/>
  231. public int Col => OutputBuffer.Col;
  232. /// <inheritdoc/>
  233. public int Row => OutputBuffer.Row;
  234. /// <inheritdoc/>
  235. public Attribute CurrentAttribute
  236. {
  237. get => OutputBuffer.CurrentAttribute;
  238. set => OutputBuffer.CurrentAttribute = value;
  239. }
  240. /// <inheritdoc/>
  241. public void Move (int col, int row) { OutputBuffer.Move (col, row); }
  242. /// <inheritdoc/>
  243. public bool IsRuneSupported (Rune rune) => Rune.IsValid (rune.Value);
  244. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  245. /// <param name="text">Used to determine if one or two columns are required.</param>
  246. /// <param name="col">The column.</param>
  247. /// <param name="row">The row.</param>
  248. /// <returns>
  249. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of
  250. /// <see cref="IDriver.Clip"/>.
  251. /// <see langword="true"/> otherwise.
  252. /// </returns>
  253. public bool IsValidLocation (string text, int col, int row) => OutputBuffer.IsValidLocation (text, col, row);
  254. /// <inheritdoc/>
  255. public void AddRune (Rune rune) { OutputBuffer.AddRune (rune); }
  256. /// <inheritdoc/>
  257. public void AddRune (char c) { OutputBuffer.AddRune (c); }
  258. /// <inheritdoc/>
  259. public void AddStr (string str) { OutputBuffer.AddStr (str); }
  260. /// <inheritdoc/>
  261. public void FillRect (Rectangle rect, Rune rune = default) { OutputBuffer.FillRect (rect, rune); }
  262. /// <inheritdoc/>
  263. public Attribute SetAttribute (Attribute newAttribute)
  264. {
  265. Attribute currentAttribute = OutputBuffer.CurrentAttribute;
  266. OutputBuffer.CurrentAttribute = newAttribute;
  267. return currentAttribute;
  268. }
  269. /// <inheritdoc/>
  270. public Attribute GetAttribute () => OutputBuffer.CurrentAttribute;
  271. /// <inheritdoc/>
  272. public void WriteRaw (string ansi) { _output.Write (ansi); }
  273. /// <inheritdoc/>
  274. public ConcurrentQueue<SixelToRender> GetSixels () => _output.GetSixels ();
  275. /// <inheritdoc/>
  276. public new string ToString ()
  277. {
  278. StringBuilder sb = new ();
  279. Cell [,] contents = Contents!;
  280. for (var r = 0; r < Rows; r++)
  281. {
  282. for (var c = 0; c < Cols; c++)
  283. {
  284. string text = contents [r, c].Grapheme;
  285. sb.Append (text);
  286. if (text.GetColumns () > 1)
  287. {
  288. c++;
  289. }
  290. }
  291. sb.AppendLine ();
  292. }
  293. return sb.ToString ();
  294. }
  295. /// <inheritdoc/>
  296. public string ToAnsi () => _output.ToAnsi (OutputBuffer);
  297. #endregion Drawing and Rendering
  298. #region Cursor
  299. private CursorVisibility _lastCursor = CursorVisibility.Default;
  300. /// <inheritdoc/>
  301. public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }
  302. /// <inheritdoc/>
  303. public bool GetCursorVisibility (out CursorVisibility current)
  304. {
  305. current = _lastCursor;
  306. return true;
  307. }
  308. /// <inheritdoc/>
  309. public bool SetCursorVisibility (CursorVisibility visibility)
  310. {
  311. _lastCursor = visibility;
  312. _output.SetCursorVisibility (visibility);
  313. return true;
  314. }
  315. #endregion Cursor
  316. #region Input Events
  317. /// <summary>Event fired when a mouse event occurs.</summary>
  318. public event EventHandler<MouseEventArgs>? MouseEvent;
  319. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="IDriver.KeyUp"/>.</summary>
  320. public event EventHandler<Key>? KeyDown;
  321. /// <inheritdoc/>
  322. public event EventHandler<Key>? KeyUp;
  323. /// <inheritdoc/>
  324. public void EnqueueKeyEvent (Key key) { GetInputProcessor ().EnqueueKeyDownEvent (key); }
  325. #endregion Input Events
  326. #region ANSI Escape Sequences
  327. private readonly AnsiRequestScheduler _ansiRequestScheduler;
  328. /// <inheritdoc/>
  329. public virtual void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (this, request); }
  330. #endregion ANSI Escape Sequences
  331. }