DriverImpl.cs 19 KB

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