DriverImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. public bool Force16Colors => _instanceForce16Colors || !SupportsTrueColor;
  165. /// <inheritdoc/>
  166. public bool GetForce16Colors () => _instanceForce16Colors || !SupportsTrueColor;
  167. /// <inheritdoc/>
  168. public Attribute CurrentAttribute
  169. {
  170. get => OutputBuffer.CurrentAttribute;
  171. set => OutputBuffer.CurrentAttribute = value;
  172. }
  173. /// <inheritdoc/>
  174. public void AddRune (Rune rune) { OutputBuffer.AddRune (rune); }
  175. /// <inheritdoc/>
  176. public void AddRune (char c) { OutputBuffer.AddRune (c); }
  177. /// <inheritdoc/>
  178. public void AddStr (string str) { OutputBuffer.AddStr (str); }
  179. /// <summary>Clears the <see cref="IDriver.Contents"/> of the driver.</summary>
  180. public void ClearContents ()
  181. {
  182. OutputBuffer.ClearContents ();
  183. ClearedContents?.Invoke (this, new MouseEventArgs ());
  184. }
  185. /// <inheritdoc/>
  186. public event EventHandler<EventArgs>? ClearedContents;
  187. /// <inheritdoc/>
  188. public void FillRect (Rectangle rect, Rune rune = default) { OutputBuffer.FillRect (rect, rune); }
  189. /// <inheritdoc/>
  190. public void FillRect (Rectangle rect, char c) { OutputBuffer.FillRect (rect, c); }
  191. /// <inheritdoc/>
  192. public virtual string GetVersionInfo ()
  193. {
  194. string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName));
  195. return type;
  196. }
  197. /// <inheritdoc/>
  198. public bool IsRuneSupported (Rune rune) => Rune.IsValid (rune.Value);
  199. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Text.</summary>
  200. /// <param name="text">Used to determine if one or two columns are required.</param>
  201. /// <param name="col">The column.</param>
  202. /// <param name="row">The row.</param>
  203. /// <returns>
  204. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of
  205. /// <see cref="IDriver.Clip"/>.
  206. /// <see langword="true"/> otherwise.
  207. /// </returns>
  208. public bool IsValidLocation (string text, int col, int row) { return OutputBuffer.IsValidLocation (text, col, row); }
  209. /// <inheritdoc/>
  210. public void Move (int col, int row) { OutputBuffer.Move (col, row); }
  211. // TODO: Probably part of output
  212. /// <inheritdoc/>
  213. public bool SetCursorVisibility (CursorVisibility visibility)
  214. {
  215. _lastCursor = visibility;
  216. _output.SetCursorVisibility (visibility);
  217. return true;
  218. }
  219. /// <inheritdoc/>
  220. public bool GetCursorVisibility (out CursorVisibility current)
  221. {
  222. current = _lastCursor;
  223. return true;
  224. }
  225. /// <inheritdoc/>
  226. public void Suspend ()
  227. {
  228. // BUGBUG: This is all platform-specific and should not be implemented here.
  229. // BUGBUG: This needs to be in each platform's driver implementation.
  230. if (Environment.OSVersion.Platform != PlatformID.Unix)
  231. {
  232. return;
  233. }
  234. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  235. try
  236. {
  237. Console.ResetColor ();
  238. Console.Clear ();
  239. //Disable alternative screen buffer.
  240. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  241. //Set cursor key to cursor.
  242. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  243. Platform.Suspend ();
  244. //Enable alternative screen buffer.
  245. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  246. }
  247. catch (Exception ex)
  248. {
  249. Logging.Error ($"Error suspending terminal: {ex.Message}");
  250. }
  251. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  252. }
  253. /// <inheritdoc/>
  254. public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }
  255. /// <inheritdoc/>
  256. public void Init () { throw new NotSupportedException (); }
  257. /// <inheritdoc/>
  258. public void End ()
  259. {
  260. // TODO: Nope
  261. }
  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. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="IDriver.KeyUp"/>.</summary>
  272. public event EventHandler<Key>? KeyDown;
  273. /// <inheritdoc/>
  274. public event EventHandler<Key>? KeyUp;
  275. /// <summary>Event fired when a mouse event occurs.</summary>
  276. public event EventHandler<MouseEventArgs>? MouseEvent;
  277. /// <inheritdoc/>
  278. public void WriteRaw (string ansi) { _output.Write (ansi); }
  279. /// <inheritdoc/>
  280. public void EnqueueKeyEvent (Key key) { InputProcessor.EnqueueKeyDownEvent (key); }
  281. /// <inheritdoc/>
  282. public void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (this, request); }
  283. /// <inheritdoc/>
  284. public AnsiRequestScheduler GetRequestScheduler () => _ansiRequestScheduler;
  285. /// <inheritdoc/>
  286. public void Refresh ()
  287. {
  288. _output.Write (OutputBuffer);
  289. }
  290. /// <inheritdoc/>
  291. public string? GetName () => InputProcessor.DriverName?.ToLowerInvariant ();
  292. /// <inheritdoc/>
  293. public new string ToString ()
  294. {
  295. StringBuilder sb = new ();
  296. Cell [,] contents = Contents!;
  297. for (var r = 0; r < Rows; r++)
  298. {
  299. for (var c = 0; c < Cols; c++)
  300. {
  301. string text = contents [r, c].Grapheme;
  302. sb.Append (text);
  303. if (text.GetColumns () > 1)
  304. {
  305. c++;
  306. }
  307. }
  308. sb.AppendLine ();
  309. }
  310. return sb.ToString ();
  311. }
  312. /// <inheritdoc />
  313. public string ToAnsi ()
  314. {
  315. return _output.ToAnsi (OutputBuffer);
  316. }
  317. }