DriverImpl.cs 12 KB

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