DriverImpl.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. /// <summary>
  68. /// The event fired when the screen changes (size, position, etc.).
  69. /// </summary>
  70. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  71. /// <inheritdoc/>
  72. public IInputProcessor InputProcessor { get; }
  73. /// <inheritdoc/>
  74. public IOutputBuffer OutputBuffer { get; }
  75. /// <inheritdoc/>
  76. public ISizeMonitor SizeMonitor { get; }
  77. private void CreateClipboard ()
  78. {
  79. if (InputProcessor.DriverName is { } && InputProcessor.DriverName.Contains ("fake"))
  80. {
  81. if (Clipboard is null)
  82. {
  83. Clipboard = new FakeClipboard ();
  84. }
  85. return;
  86. }
  87. PlatformID p = Environment.OSVersion.Platform;
  88. if (p is PlatformID.Win32NT or PlatformID.Win32S or PlatformID.Win32Windows)
  89. {
  90. Clipboard = new WindowsClipboard ();
  91. }
  92. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  93. {
  94. Clipboard = new MacOSXClipboard ();
  95. }
  96. else if (PlatformDetection.IsWSLPlatform ())
  97. {
  98. Clipboard = new WSLClipboard ();
  99. }
  100. // Clipboard is set to FakeClipboard at initialization
  101. }
  102. /// <summary>Gets the location and size of the terminal screen.</summary>
  103. public Rectangle Screen
  104. {
  105. get
  106. {
  107. //if (Application.RunningUnitTests && _output is WindowsConsoleOutput or NetOutput)
  108. //{
  109. // // In unit tests, we don't have a real output, so we return an empty rectangle.
  110. // return Rectangle.Empty;
  111. //}
  112. return new (0, 0, OutputBuffer.Cols, OutputBuffer.Rows);
  113. }
  114. }
  115. /// <summary>
  116. /// Sets the screen size for testing purposes. Only supported by FakeDriver.
  117. /// </summary>
  118. /// <param name="width">The new width in columns.</param>
  119. /// <param name="height">The new height in rows.</param>
  120. /// <exception cref="NotSupportedException">Thrown when called on non-FakeDriver instances.</exception>
  121. public virtual void SetScreenSize (int width, int height)
  122. {
  123. OutputBuffer.SetSize (width, height);
  124. _output.SetSize (width, height);
  125. SizeChanged?.Invoke (this, new (new (width, height)));
  126. }
  127. /// <summary>
  128. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  129. /// to.
  130. /// </summary>
  131. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  132. public Region? Clip
  133. {
  134. get => OutputBuffer.Clip;
  135. set => OutputBuffer.Clip = value;
  136. }
  137. /// <summary>Get the operating system clipboard.</summary>
  138. public IClipboard? Clipboard { get; private set; } = new FakeClipboard ();
  139. /// <summary>
  140. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  141. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  142. /// </summary>
  143. public int Col => OutputBuffer.Col;
  144. /// <summary>The number of columns visible in the terminal.</summary>
  145. public int Cols
  146. {
  147. get => OutputBuffer.Cols;
  148. set => OutputBuffer.Cols = value;
  149. }
  150. /// <summary>
  151. /// The contents of the application output. The driver outputs this buffer to the terminal.
  152. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  153. /// </summary>
  154. public Cell [,]? Contents
  155. {
  156. get => OutputBuffer.Contents;
  157. set => OutputBuffer.Contents = value;
  158. }
  159. /// <summary>The leftmost column in the terminal.</summary>
  160. public int Left
  161. {
  162. get => OutputBuffer.Left;
  163. set => OutputBuffer.Left = value;
  164. }
  165. /// <summary>
  166. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  167. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  168. /// </summary>
  169. public int Row => OutputBuffer.Row;
  170. /// <summary>The number of rows visible in the terminal.</summary>
  171. public int Rows
  172. {
  173. get => OutputBuffer.Rows;
  174. set => OutputBuffer.Rows = value;
  175. }
  176. /// <summary>The topmost row in the terminal.</summary>
  177. public int Top
  178. {
  179. get => OutputBuffer.Top;
  180. set => OutputBuffer.Top = value;
  181. }
  182. // TODO: Probably not everyone right?
  183. /// <summary>Gets whether the <see cref="IDriver"/> supports TrueColor output.</summary>
  184. public bool SupportsTrueColor => true;
  185. // TODO: Currently ignored
  186. /// <summary>
  187. /// Gets or sets whether the <see cref="IDriver"/> should use 16 colors instead of the default TrueColors.
  188. /// See <see cref="Application.Force16Colors"/> to change this setting via <see cref="ConfigurationManager"/>.
  189. /// </summary>
  190. /// <remarks>
  191. /// <para>
  192. /// Will be forced to <see langword="true"/> if <see cref="IDriver.SupportsTrueColor"/> is
  193. /// <see langword="false"/>, indicating that the <see cref="IDriver"/> cannot support TrueColor.
  194. /// </para>
  195. /// </remarks>
  196. public bool Force16Colors
  197. {
  198. get => Application.Force16Colors || !SupportsTrueColor;
  199. set => Application.Force16Colors = value || !SupportsTrueColor;
  200. }
  201. /// <summary>
  202. /// The <see cref="System.Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or
  203. /// <see cref="AddStr"/>
  204. /// call.
  205. /// </summary>
  206. public Attribute CurrentAttribute
  207. {
  208. get => OutputBuffer.CurrentAttribute;
  209. set => OutputBuffer.CurrentAttribute = value;
  210. }
  211. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  212. /// <remarks>
  213. /// <para>
  214. /// When the method returns, <see cref="IDriver.Col"/> will be incremented by the number of columns
  215. /// <paramref name="rune"/> required, even if the new column value is outside of the
  216. /// <see cref="IDriver.Clip"/> or screen
  217. /// dimensions defined by <see cref="IDriver.Cols"/>.
  218. /// </para>
  219. /// <para>
  220. /// If <paramref name="rune"/> requires more than one column, and <see cref="IDriver.Col"/> plus the number
  221. /// of columns
  222. /// needed exceeds the <see cref="IDriver.Clip"/> or screen dimensions, the default Unicode replacement
  223. /// character (U+FFFD)
  224. /// will be added instead.
  225. /// </para>
  226. /// </remarks>
  227. /// <param name="rune">Rune to add.</param>
  228. public void AddRune (Rune rune) { OutputBuffer.AddRune (rune); }
  229. /// <summary>
  230. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  231. /// convenience method that calls <see cref="IDriver.AddRune(System.Text.Rune)"/> with the <see cref="Rune"/>
  232. /// constructor.
  233. /// </summary>
  234. /// <param name="c">Character to add.</param>
  235. public void AddRune (char c) { OutputBuffer.AddRune (c); }
  236. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  237. /// <remarks>
  238. /// <para>
  239. /// When the method returns, <see cref="IDriver.Col"/> will be incremented by the number of columns
  240. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="IDriver.Clip"/>
  241. /// or screen
  242. /// dimensions defined by <see cref="IDriver.Cols"/>.
  243. /// </para>
  244. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  245. /// </remarks>
  246. /// <param name="str">String.</param>
  247. public void AddStr (string str) { OutputBuffer.AddStr (str); }
  248. /// <summary>Clears the <see cref="IDriver.Contents"/> of the driver.</summary>
  249. public void ClearContents ()
  250. {
  251. OutputBuffer.ClearContents ();
  252. ClearedContents?.Invoke (this, new MouseEventArgs ());
  253. }
  254. /// <summary>
  255. /// Raised each time <see cref="IDriver.ClearContents"/> is called. For benchmarking.
  256. /// </summary>
  257. public event EventHandler<EventArgs>? ClearedContents;
  258. /// <summary>
  259. /// Fills the specified rectangle with the specified rune, using <see cref="IDriver.CurrentAttribute"/>
  260. /// </summary>
  261. /// <remarks>
  262. /// The value of <see cref="IDriver.Clip"/> is honored. Any parts of the rectangle not in the clip will not be
  263. /// drawn.
  264. /// </remarks>
  265. /// <param name="rect">The Screen-relative rectangle.</param>
  266. /// <param name="rune">The Rune used to fill the rectangle</param>
  267. public void FillRect (Rectangle rect, Rune rune = default) { OutputBuffer.FillRect (rect, rune); }
  268. /// <summary>
  269. /// Fills the specified rectangle with the specified <see langword="char"/>. This method is a convenience method
  270. /// that calls <see cref="IDriver.FillRect(System.Drawing.Rectangle,System.Text.Rune)"/>.
  271. /// </summary>
  272. /// <param name="rect"></param>
  273. /// <param name="c"></param>
  274. public void FillRect (Rectangle rect, char c) { OutputBuffer.FillRect (rect, c); }
  275. /// <inheritdoc/>
  276. public virtual string GetVersionInfo ()
  277. {
  278. string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName));
  279. return type;
  280. }
  281. /// <summary>Tests if the specified rune is supported by the driver.</summary>
  282. /// <param name="rune"></param>
  283. /// <returns>
  284. /// <see langword="true"/> if the rune can be properly presented; <see langword="false"/> if the driver does not
  285. /// support displaying this rune.
  286. /// </returns>
  287. public bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }
  288. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  289. /// <param name="rune">Used to determine if one or two columns are required.</param>
  290. /// <param name="col">The column.</param>
  291. /// <param name="row">The row.</param>
  292. /// <returns>
  293. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of
  294. /// <see cref="IDriver.Clip"/>.
  295. /// <see langword="true"/> otherwise.
  296. /// </returns>
  297. public bool IsValidLocation (Rune rune, int col, int row) { return OutputBuffer.IsValidLocation (rune, col, row); }
  298. /// <summary>
  299. /// Updates <see cref="IDriver.Col"/> and <see cref="IDriver.Row"/> to the specified column and row in
  300. /// <see cref="IDriver.Contents"/>.
  301. /// Used by <see cref="IDriver.AddRune(System.Text.Rune)"/> and <see cref="IDriver.AddStr"/> to determine
  302. /// where to add content.
  303. /// </summary>
  304. /// <remarks>
  305. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  306. /// <para>
  307. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="IDriver.Cols"/>
  308. /// and
  309. /// <see cref="IDriver.Rows"/>, the method still sets those properties.
  310. /// </para>
  311. /// </remarks>
  312. /// <param name="col">Column to move to.</param>
  313. /// <param name="row">Row to move to.</param>
  314. public void Move (int col, int row) { OutputBuffer.Move (col, row); }
  315. // TODO: Probably part of output
  316. /// <summary>Sets the terminal cursor visibility.</summary>
  317. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  318. /// <returns><see langword="true"/> upon success</returns>
  319. public bool SetCursorVisibility (CursorVisibility visibility)
  320. {
  321. _lastCursor = visibility;
  322. _output.SetCursorVisibility (visibility);
  323. return true;
  324. }
  325. /// <inheritdoc/>
  326. public bool GetCursorVisibility (out CursorVisibility current)
  327. {
  328. current = _lastCursor;
  329. return true;
  330. }
  331. /// <inheritdoc/>
  332. public void Suspend ()
  333. {
  334. // BUGBUG: This is all platform-specific and should not be implemented here.
  335. // BUGBUG: This needs to be in each platform's driver implementation.
  336. if (Environment.OSVersion.Platform != PlatformID.Unix)
  337. {
  338. return;
  339. }
  340. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  341. try
  342. {
  343. Console.ResetColor ();
  344. Console.Clear ();
  345. //Disable alternative screen buffer.
  346. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  347. //Set cursor key to cursor.
  348. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  349. Platform.Suspend ();
  350. //Enable alternative screen buffer.
  351. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  352. }
  353. catch (Exception ex)
  354. {
  355. Logging.Error ($"Error suspending terminal: {ex.Message}");
  356. }
  357. Application.LayoutAndDraw ();
  358. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  359. }
  360. /// <summary>
  361. /// Sets the position of the terminal cursor to <see cref="IDriver.Col"/> and
  362. /// <see cref="IDriver.Row"/>.
  363. /// </summary>
  364. public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }
  365. /// <summary>Initializes the driver</summary>
  366. public void Init () { throw new NotSupportedException (); }
  367. /// <summary>Ends the execution of the console driver.</summary>
  368. public void End ()
  369. {
  370. // TODO: Nope
  371. }
  372. /// <summary>Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.</summary>
  373. /// <remarks>Implementations should call <c>base.SetAttribute(c)</c>.</remarks>
  374. /// <param name="newAttribute">C.</param>
  375. /// <returns>The previously set Attribute.</returns>
  376. public Attribute SetAttribute (Attribute newAttribute)
  377. {
  378. Attribute currentAttribute = OutputBuffer.CurrentAttribute;
  379. OutputBuffer.CurrentAttribute = newAttribute;
  380. return currentAttribute;
  381. }
  382. /// <summary>Gets the current <see cref="Attribute"/>.</summary>
  383. /// <returns>The current attribute.</returns>
  384. public Attribute GetAttribute () { return OutputBuffer.CurrentAttribute; }
  385. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="IDriver.KeyUp"/>.</summary>
  386. public event EventHandler<Key>? KeyDown;
  387. /// <summary>Event fired when a key is released.</summary>
  388. /// <remarks>
  389. /// Drivers that do not support key release events will fire this event after <see cref="IDriver.KeyDown"/>
  390. /// processing is
  391. /// complete.
  392. /// </remarks>
  393. public event EventHandler<Key>? KeyUp;
  394. /// <summary>Event fired when a mouse event occurs.</summary>
  395. public event EventHandler<MouseEventArgs>? MouseEvent;
  396. /// <summary>
  397. /// Provide proper writing to send escape sequence recognized by the <see cref="IDriver"/>.
  398. /// </summary>
  399. /// <param name="ansi"></param>
  400. public void WriteRaw (string ansi) { _output.Write (ansi); }
  401. /// <inheritdoc/>
  402. public void EnqueueKeyEvent (Key key)
  403. {
  404. InputProcessor.EnqueueKeyDownEvent (key);
  405. }
  406. /// <summary>
  407. /// Queues the specified ANSI escape sequence request for execution.
  408. /// </summary>
  409. /// <param name="request">The ANSI request to queue.</param>
  410. /// <remarks>
  411. /// The request is sent immediately if possible, or queued for later execution
  412. /// by the <see cref="AnsiRequestScheduler"/> to prevent overwhelming the console.
  413. /// </remarks>
  414. public void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (request); }
  415. /// <summary>
  416. /// Gets the <see cref="AnsiRequestScheduler"/> instance used by this driver.
  417. /// </summary>
  418. /// <returns>The ANSI request scheduler.</returns>
  419. public AnsiRequestScheduler GetRequestScheduler () { return _ansiRequestScheduler; }
  420. /// <inheritdoc/>
  421. public void Refresh ()
  422. {
  423. // No need we will always draw when dirty
  424. }
  425. public string? GetName ()
  426. {
  427. return InputProcessor.DriverName?.ToLowerInvariant ();
  428. }
  429. }