DriverImpl.cs 12 KB

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