ConsoleDriver.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. namespace Terminal.Gui;
  5. /// <summary>Base class for Terminal.Gui ConsoleDriver implementations.</summary>
  6. /// <remarks>
  7. /// There are currently four implementations: - <see cref="CursesDriver"/> (for Unix and Mac) -
  8. /// <see cref="WindowsDriver"/> - <see cref="NetDriver"/> that uses the .NET Console API - <see cref="FakeConsole"/>
  9. /// for unit testing.
  10. /// </remarks>
  11. public abstract class ConsoleDriver
  12. {
  13. private readonly ManualResetEventSlim _waitAnsiRequest = new (false);
  14. private readonly ManualResetEventSlim _ansiResponseReady = new (false);
  15. private readonly CancellationTokenSource? _ansiRequestTokenSource = new ();
  16. private readonly ConcurrentQueue<AnsiEscapeSequenceRequest> _requestQueue = new ();
  17. private readonly ConcurrentQueue<AnsiEscapeSequenceRequest> _responseQueue = new ();
  18. private IMainLoopDriver? _mainLoopDriver;
  19. internal void ProcessAnsiRequestHandler ()
  20. {
  21. while (_ansiRequestTokenSource is { IsCancellationRequested: false})
  22. {
  23. try
  24. {
  25. if (_requestQueue.Count == 0)
  26. {
  27. try
  28. {
  29. _waitAnsiRequest.Wait (_ansiRequestTokenSource.Token);
  30. }
  31. catch (OperationCanceledException)
  32. {
  33. return;
  34. }
  35. _waitAnsiRequest.Reset ();
  36. }
  37. while (_requestQueue.TryDequeue (out AnsiEscapeSequenceRequest? ansiRequest))
  38. {
  39. try
  40. {
  41. lock (ansiRequest._responseLock)
  42. {
  43. AnsiEscapeSequenceRequest request = ansiRequest;
  44. ansiRequest.ResponseFromInput += (s, e) =>
  45. {
  46. Debug.Assert (s == request);
  47. Debug.Assert (e == request.AnsiEscapeSequenceResponse);
  48. _responseQueue.Enqueue (request);
  49. _ansiResponseReady.Set ();
  50. };
  51. AnsiEscapeSequenceRequests.Add (ansiRequest);
  52. WriteRaw (ansiRequest.Request);
  53. _mainLoopDriver!.ForceRead = true;
  54. }
  55. if (!_ansiRequestTokenSource.IsCancellationRequested)
  56. {
  57. _mainLoopDriver.WaitForInput.Set ();
  58. }
  59. }
  60. catch (OperationCanceledException)
  61. {
  62. return;
  63. }
  64. }
  65. }
  66. catch (OperationCanceledException)
  67. {
  68. return;
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Set this to true in any unit tests that attempt to test drivers other than FakeDriver.
  74. /// <code>
  75. /// public ColorTests ()
  76. /// {
  77. /// ConsoleDriver.RunningUnitTests = true;
  78. /// }
  79. /// </code>
  80. /// </summary>
  81. internal static bool RunningUnitTests { get; set; }
  82. /// <summary>Get the operating system clipboard.</summary>
  83. public IClipboard? Clipboard { get; internal set; }
  84. /// <summary>Returns the name of the driver and relevant library version information.</summary>
  85. /// <returns></returns>
  86. public virtual string GetVersionInfo () { return GetType ().Name; }
  87. #region ANSI Esc Sequence Handling
  88. /// <summary>
  89. /// Provide unique handling for all the terminal write ANSI escape sequence request.
  90. /// </summary>
  91. /// <param name="mainLoopDriver">The <see cref="IMainLoopDriver"/> object.</param>
  92. /// <param name="ansiRequest">The <see cref="AnsiEscapeSequenceRequest"/> object.</param>
  93. /// <returns><see languard="true"/> if the request response is valid, <see languard="false"/> otherwise.</returns>
  94. public bool TryWriteAnsiRequest (IMainLoopDriver mainLoopDriver, ref AnsiEscapeSequenceRequest ansiRequest)
  95. {
  96. ArgumentNullException.ThrowIfNull (mainLoopDriver, nameof (mainLoopDriver));
  97. ArgumentNullException.ThrowIfNull (ansiRequest, nameof (ansiRequest));
  98. lock (ansiRequest._responseLock)
  99. {
  100. _mainLoopDriver = mainLoopDriver;
  101. _requestQueue.Enqueue (ansiRequest);
  102. _waitAnsiRequest.Set ();
  103. }
  104. try
  105. {
  106. _ansiResponseReady.Wait (_ansiRequestTokenSource!.Token);
  107. _ansiResponseReady.Reset ();
  108. _responseQueue.TryDequeue (out _);
  109. lock (ansiRequest._responseLock)
  110. {
  111. _mainLoopDriver.ForceRead = false;
  112. if (AnsiEscapeSequenceRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request))
  113. {
  114. if (AnsiEscapeSequenceRequests.Statuses.Count > 0
  115. && string.IsNullOrEmpty (request.AnsiRequest.AnsiEscapeSequenceResponse?.Response))
  116. {
  117. lock (request.AnsiRequest._responseLock)
  118. {
  119. // Bad request or no response at all
  120. AnsiEscapeSequenceRequests.Statuses.TryDequeue (out _);
  121. }
  122. }
  123. }
  124. return ansiRequest.AnsiEscapeSequenceResponse is { Valid: true };
  125. }
  126. }
  127. catch (OperationCanceledException)
  128. {
  129. return false;
  130. }
  131. }
  132. // QUESTION: This appears to be an API to help in debugging. It's only implemented in CursesDriver and WindowsDriver.
  133. // QUESTION: Can it be factored such that it does not contaminate the ConsoleDriver API?
  134. /// <summary>
  135. /// Provide proper writing to send escape sequence recognized by the <see cref="ConsoleDriver"/>.
  136. /// </summary>
  137. /// <param name="ansi"></param>
  138. internal abstract void WriteRaw (string ansi);
  139. #endregion ANSI Esc Sequence Handling
  140. #region Screen and Contents
  141. // As performance is a concern, we keep track of the dirty lines and only refresh those.
  142. // This is in addition to the dirty flag on each cell.
  143. internal bool []? _dirtyLines;
  144. // QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
  145. /// <summary>Gets the location and size of the terminal screen.</summary>
  146. internal Rectangle Screen => new (0, 0, Cols, Rows);
  147. private Region? _clip;
  148. /// <summary>
  149. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  150. /// to.
  151. /// </summary>
  152. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  153. internal Region? Clip
  154. {
  155. get => _clip;
  156. set
  157. {
  158. if (_clip == value)
  159. {
  160. return;
  161. }
  162. _clip = value;
  163. // Don't ever let Clip be bigger than Screen
  164. if (_clip is { })
  165. {
  166. _clip.Intersect (Screen);
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  172. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  173. /// </summary>
  174. internal int Col { get; private set; }
  175. /// <summary>The number of columns visible in the terminal.</summary>
  176. internal virtual int Cols
  177. {
  178. get => _cols;
  179. set
  180. {
  181. _cols = value;
  182. ClearContents ();
  183. }
  184. }
  185. /// <summary>
  186. /// The contents of the application output. The driver outputs this buffer to the terminal when
  187. /// <see cref="UpdateScreen"/> is called.
  188. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  189. /// </summary>
  190. internal Cell [,]? Contents { get; set; }
  191. /// <summary>The leftmost column in the terminal.</summary>
  192. internal virtual int Left { get; set; } = 0;
  193. /// <summary>Tests if the specified rune is supported by the driver.</summary>
  194. /// <param name="rune"></param>
  195. /// <returns>
  196. /// <see langword="true"/> if the rune can be properly presented; <see langword="false"/> if the driver does not
  197. /// support displaying this rune.
  198. /// </returns>
  199. public virtual bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }
  200. /// <summary>Tests whether the specified coordinate are valid for drawing.</summary>
  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 <see cref="Clip"/>.
  205. /// <see langword="true"/> otherwise.
  206. /// </returns>
  207. public bool IsValidLocation (int col, int row) { return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row); }
  208. /// <summary>
  209. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  210. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  211. /// </summary>
  212. /// <remarks>
  213. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  214. /// <para>
  215. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  216. /// <see cref="Rows"/>, the method still sets those properties.
  217. /// </para>
  218. /// </remarks>
  219. /// <param name="col">Column to move to.</param>
  220. /// <param name="row">Row to move to.</param>
  221. public virtual void Move (int col, int row)
  222. {
  223. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  224. Col = col;
  225. Row = row;
  226. }
  227. /// <summary>
  228. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  229. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  230. /// </summary>
  231. internal int Row { get; private set; }
  232. /// <summary>The number of rows visible in the terminal.</summary>
  233. internal virtual int Rows
  234. {
  235. get => _rows;
  236. set
  237. {
  238. _rows = value;
  239. ClearContents ();
  240. }
  241. }
  242. /// <summary>The topmost row in the terminal.</summary>
  243. internal virtual int Top { get; set; } = 0;
  244. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  245. /// <remarks>
  246. /// <para>
  247. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  248. /// <paramref name="rune"/> required, even if the new column value is outside of the <see cref="Clip"/> or screen
  249. /// dimensions defined by <see cref="Cols"/>.
  250. /// </para>
  251. /// <para>
  252. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  253. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  254. /// will be added instead.
  255. /// </para>
  256. /// </remarks>
  257. /// <param name="rune">Rune to add.</param>
  258. internal void AddRune (Rune rune)
  259. {
  260. int runeWidth = -1;
  261. bool validLocation = IsValidLocation (rune, Col, Row);
  262. if (Contents is null)
  263. {
  264. return;
  265. }
  266. Rectangle clipRect = Clip!.GetBounds ();
  267. if (validLocation)
  268. {
  269. rune = rune.MakePrintable ();
  270. runeWidth = rune.GetColumns ();
  271. lock (Contents)
  272. {
  273. if (runeWidth == 0 && rune.IsCombiningMark ())
  274. {
  275. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  276. // compatible with the driver architecture. Any CMs (except in the first col)
  277. // are correctly combined with the base char, but are ALSO treated as 1 column
  278. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  279. //
  280. // Until this is addressed (see Issue #), we do our best by
  281. // a) Attempting to normalize any CM with the base char to it's left
  282. // b) Ignoring any CMs that don't normalize
  283. if (Col > 0)
  284. {
  285. if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
  286. {
  287. // Just add this mark to the list
  288. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  289. // Ignore. Don't move to next column (let the driver figure out what to do).
  290. }
  291. else
  292. {
  293. // Attempt to normalize the cell to our left combined with this mark
  294. string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
  295. // Normalize to Form C (Canonical Composition)
  296. string normalized = combined.Normalize (NormalizationForm.FormC);
  297. if (normalized.Length == 1)
  298. {
  299. // It normalized! We can just set the Cell to the left with the
  300. // normalized codepoint
  301. Contents [Row, Col - 1].Rune = (Rune)normalized [0];
  302. // Ignore. Don't move to next column because we're already there
  303. }
  304. else
  305. {
  306. // It didn't normalize. Add it to the Cell to left's CM list
  307. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  308. // Ignore. Don't move to next column (let the driver figure out what to do).
  309. }
  310. }
  311. Contents [Row, Col - 1].Attribute = CurrentAttribute;
  312. Contents [Row, Col - 1].IsDirty = true;
  313. }
  314. else
  315. {
  316. // Most drivers will render a combining mark at col 0 as the mark
  317. Contents [Row, Col].Rune = rune;
  318. Contents [Row, Col].Attribute = CurrentAttribute;
  319. Contents [Row, Col].IsDirty = true;
  320. Col++;
  321. }
  322. }
  323. else
  324. {
  325. Contents [Row, Col].Attribute = CurrentAttribute;
  326. Contents [Row, Col].IsDirty = true;
  327. if (Col > 0)
  328. {
  329. // Check if cell to left has a wide glyph
  330. if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
  331. {
  332. // Invalidate cell to left
  333. Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
  334. Contents [Row, Col - 1].IsDirty = true;
  335. }
  336. }
  337. if (runeWidth < 1)
  338. {
  339. Contents [Row, Col].Rune = Rune.ReplacementChar;
  340. }
  341. else if (runeWidth == 1)
  342. {
  343. Contents [Row, Col].Rune = rune;
  344. if (Col < clipRect.Right - 1)
  345. {
  346. Contents [Row, Col + 1].IsDirty = true;
  347. }
  348. }
  349. else if (runeWidth == 2)
  350. {
  351. if (!Clip.Contains (Col + 1, Row))
  352. {
  353. // We're at the right edge of the clip, so we can't display a wide character.
  354. // TODO: Figure out if it is better to show a replacement character or ' '
  355. Contents [Row, Col].Rune = Rune.ReplacementChar;
  356. }
  357. else if (!Clip.Contains (Col, Row))
  358. {
  359. // Our 1st column is outside the clip, so we can't display a wide character.
  360. Contents [Row, Col+1].Rune = Rune.ReplacementChar;
  361. }
  362. else
  363. {
  364. Contents [Row, Col].Rune = rune;
  365. if (Col < clipRect.Right - 1)
  366. {
  367. // Invalidate cell to right so that it doesn't get drawn
  368. // TODO: Figure out if it is better to show a replacement character or ' '
  369. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  370. Contents [Row, Col + 1].IsDirty = true;
  371. }
  372. }
  373. }
  374. else
  375. {
  376. // This is a non-spacing character, so we don't need to do anything
  377. Contents [Row, Col].Rune = (Rune)' ';
  378. Contents [Row, Col].IsDirty = false;
  379. }
  380. _dirtyLines! [Row] = true;
  381. }
  382. }
  383. }
  384. if (runeWidth is < 0 or > 0)
  385. {
  386. Col++;
  387. }
  388. if (runeWidth > 1)
  389. {
  390. Debug.Assert (runeWidth <= 2);
  391. if (validLocation && Col < clipRect.Right)
  392. {
  393. lock (Contents!)
  394. {
  395. // This is a double-width character, and we are not at the end of the line.
  396. // Col now points to the second column of the character. Ensure it doesn't
  397. // Get rendered.
  398. Contents [Row, Col].IsDirty = false;
  399. Contents [Row, Col].Attribute = CurrentAttribute;
  400. // TODO: Determine if we should wipe this out (for now now)
  401. //Contents [Row, Col].Rune = (Rune)' ';
  402. }
  403. }
  404. Col++;
  405. }
  406. }
  407. /// <summary>
  408. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  409. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  410. /// </summary>
  411. /// <param name="c">Character to add.</param>
  412. internal void AddRune (char c) { AddRune (new Rune (c)); }
  413. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  414. /// <remarks>
  415. /// <para>
  416. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  417. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="Clip"/> or screen
  418. /// dimensions defined by <see cref="Cols"/>.
  419. /// </para>
  420. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  421. /// </remarks>
  422. /// <param name="str">String.</param>
  423. internal void AddStr (string str)
  424. {
  425. List<Rune> runes = str.EnumerateRunes ().ToList ();
  426. for (var i = 0; i < runes.Count; i++)
  427. {
  428. AddRune (runes [i]);
  429. }
  430. }
  431. /// <summary>Fills the specified rectangle with the specified rune, using <see cref="CurrentAttribute"/></summary>
  432. /// <remarks>
  433. /// The value of <see cref="Clip"/> is honored. Any parts of the rectangle not in the clip will not be drawn.
  434. /// </remarks>
  435. /// <param name="rect">The Screen-relative rectangle.</param>
  436. /// <param name="rune">The Rune used to fill the rectangle</param>
  437. internal void FillRect (Rectangle rect, Rune rune = default)
  438. {
  439. // BUGBUG: This should be a method on Region
  440. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  441. lock (Contents!)
  442. {
  443. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  444. {
  445. for (int c = rect.X; c < rect.X + rect.Width; c++)
  446. {
  447. if (!IsValidLocation (rune, c, r))
  448. {
  449. continue;
  450. }
  451. Contents [r, c] = new Cell
  452. {
  453. Rune = rune != default ? rune : (Rune)' ',
  454. Attribute = CurrentAttribute, IsDirty = true
  455. };
  456. _dirtyLines! [r] = true;
  457. }
  458. }
  459. }
  460. }
  461. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  462. internal void ClearContents ()
  463. {
  464. Contents = new Cell [Rows, Cols];
  465. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  466. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  467. Clip = new (Screen);
  468. _dirtyLines = new bool [Rows];
  469. lock (Contents)
  470. {
  471. for (var row = 0; row < Rows; row++)
  472. {
  473. for (var c = 0; c < Cols; c++)
  474. {
  475. Contents [row, c] = new ()
  476. {
  477. Rune = (Rune)' ',
  478. Attribute = new Attribute (Color.White, Color.Black),
  479. IsDirty = true
  480. };
  481. }
  482. _dirtyLines [row] = true;
  483. }
  484. }
  485. ClearedContents?.Invoke (this, EventArgs.Empty);
  486. }
  487. /// <summary>
  488. /// Raised each time <see cref="ClearContents"/> is called. For benchmarking.
  489. /// </summary>
  490. public event EventHandler<EventArgs>? ClearedContents;
  491. /// <summary>
  492. /// Sets <see cref="Contents"/> as dirty for situations where views
  493. /// don't need layout and redrawing, but just refresh the screen.
  494. /// </summary>
  495. internal void SetContentsAsDirty ()
  496. {
  497. lock (Contents!)
  498. {
  499. for (var row = 0; row < Rows; row++)
  500. {
  501. for (var c = 0; c < Cols; c++)
  502. {
  503. Contents [row, c].IsDirty = true;
  504. }
  505. _dirtyLines! [row] = true;
  506. }
  507. }
  508. }
  509. /// <summary>
  510. /// Fills the specified rectangle with the specified <see langword="char"/>. This method is a convenience method
  511. /// that calls <see cref="FillRect(Rectangle, Rune)"/>.
  512. /// </summary>
  513. /// <param name="rect"></param>
  514. /// <param name="c"></param>
  515. internal void FillRect (Rectangle rect, char c) { FillRect (rect, new Rune (c)); }
  516. #endregion Screen and Contents
  517. #region Cursor Handling
  518. /// <summary>Determines if the terminal cursor should be visible or not and sets it accordingly.</summary>
  519. /// <returns><see langword="true"/> upon success</returns>
  520. public abstract bool EnsureCursorVisibility ();
  521. /// <summary>Gets the terminal cursor visibility.</summary>
  522. /// <param name="visibility">The current <see cref="CursorVisibility"/></param>
  523. /// <returns><see langword="true"/> upon success</returns>
  524. public abstract bool GetCursorVisibility (out CursorVisibility visibility);
  525. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  526. /// <param name="rune">Used to determine if one or two columns are required.</param>
  527. /// <param name="col">The column.</param>
  528. /// <param name="row">The row.</param>
  529. /// <returns>
  530. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  531. /// <see langword="true"/> otherwise.
  532. /// </returns>
  533. internal bool IsValidLocation (Rune rune, int col, int row)
  534. {
  535. if (rune.GetColumns () < 2)
  536. {
  537. return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row);
  538. }
  539. else
  540. {
  541. return Clip!.Contains (col, row) || Clip!.Contains (col + 1, row);
  542. }
  543. }
  544. /// <summary>Called when the terminal size changes. Fires the <see cref="SizeChanged"/> event.</summary>
  545. /// <param name="args"></param>
  546. internal void OnSizeChanged (SizeChangedEventArgs args) { SizeChanged?.Invoke (this, args); }
  547. /// <summary>Updates the screen to reflect all the changes that have been done to the display buffer</summary>
  548. internal void Refresh ()
  549. {
  550. bool updated = UpdateScreen ();
  551. UpdateCursor ();
  552. Refreshed?.Invoke (this, new EventArgs<bool> (in updated));
  553. }
  554. /// <summary>
  555. /// Raised each time <see cref="Refresh"/> is called. For benchmarking.
  556. /// </summary>
  557. public event EventHandler<EventArgs<bool>>? Refreshed;
  558. /// <summary>Sets the terminal cursor visibility.</summary>
  559. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  560. /// <returns><see langword="true"/> upon success</returns>
  561. public abstract bool SetCursorVisibility (CursorVisibility visibility);
  562. /// <summary>The event fired when the terminal is resized.</summary>
  563. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  564. #endregion Cursor Handling
  565. /// <summary>Suspends the application (e.g. on Linux via SIGTSTP) and upon resume, resets the console driver.</summary>
  566. /// <remarks>This is only implemented in <see cref="CursesDriver"/>.</remarks>
  567. public abstract void Suspend ();
  568. /// <summary>Sets the position of the terminal cursor to <see cref="Col"/> and <see cref="Row"/>.</summary>
  569. public abstract void UpdateCursor ();
  570. /// <summary>Redraws the physical screen with the contents that have been queued up via any of the printing commands.</summary>
  571. /// <returns><see langword="true"/> if any updates to the screen were made.</returns>
  572. public abstract bool UpdateScreen ();
  573. #region Setup & Teardown
  574. /// <summary>Initializes the driver</summary>
  575. /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
  576. internal abstract MainLoop Init ();
  577. /// <summary>Ends the execution of the console driver.</summary>
  578. internal abstract void End ();
  579. #endregion
  580. #region Color Handling
  581. /// <summary>Gets whether the <see cref="ConsoleDriver"/> supports TrueColor output.</summary>
  582. public virtual bool SupportsTrueColor => true;
  583. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  584. // BUGBUG: Application.Force16Colors should be bool? so if SupportsTrueColor and Application.Force16Colors == false, this doesn't override
  585. /// <summary>
  586. /// Gets or sets whether the <see cref="ConsoleDriver"/> should use 16 colors instead of the default TrueColors.
  587. /// See <see cref="Application.Force16Colors"/> to change this setting via <see cref="ConfigurationManager"/>.
  588. /// </summary>
  589. /// <remarks>
  590. /// <para>
  591. /// Will be forced to <see langword="true"/> if <see cref="ConsoleDriver.SupportsTrueColor"/> is
  592. /// <see langword="false"/>, indicating that the <see cref="ConsoleDriver"/> cannot support TrueColor.
  593. /// </para>
  594. /// </remarks>
  595. internal virtual bool Force16Colors
  596. {
  597. get => Application.Force16Colors || !SupportsTrueColor;
  598. set => Application.Force16Colors = value || !SupportsTrueColor;
  599. }
  600. private Attribute _currentAttribute;
  601. private int _cols;
  602. private int _rows;
  603. /// <summary>
  604. /// The <see cref="Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or <see cref="AddStr"/>
  605. /// call.
  606. /// </summary>
  607. public Attribute CurrentAttribute
  608. {
  609. get => _currentAttribute;
  610. set
  611. {
  612. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. Once Attribute.PlatformColor is removed, this can be fixed.
  613. if (Application.Driver is { })
  614. {
  615. _currentAttribute = new (value.Foreground, value.Background);
  616. return;
  617. }
  618. _currentAttribute = value;
  619. }
  620. }
  621. /// <summary>Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.</summary>
  622. /// <remarks>Implementations should call <c>base.SetAttribute(c)</c>.</remarks>
  623. /// <param name="c">C.</param>
  624. internal Attribute SetAttribute (Attribute c)
  625. {
  626. Attribute prevAttribute = CurrentAttribute;
  627. CurrentAttribute = c;
  628. return prevAttribute;
  629. }
  630. /// <summary>Gets the current <see cref="Attribute"/>.</summary>
  631. /// <returns>The current attribute.</returns>
  632. internal Attribute GetAttribute () { return CurrentAttribute; }
  633. // TODO: This is only overridden by CursesDriver. Once CursesDriver supports 24-bit color, this virtual method can be
  634. // removed (and Attribute can lose the platformColor property).
  635. /// <summary>Makes an <see cref="Attribute"/>.</summary>
  636. /// <param name="foreground">The foreground color.</param>
  637. /// <param name="background">The background color.</param>
  638. /// <returns>The attribute for the foreground and background colors.</returns>
  639. public virtual Attribute MakeColor (in Color foreground, in Color background)
  640. {
  641. // Encode the colors into the int value.
  642. return new (
  643. -1, // only used by cursesdriver!
  644. foreground,
  645. background
  646. );
  647. }
  648. #endregion Color Handling
  649. #region Mouse Handling
  650. /// <summary>Event fired when a mouse event occurs.</summary>
  651. public event EventHandler<MouseEventArgs>? MouseEvent;
  652. /// <summary>Called when a mouse event occurs. Fires the <see cref="MouseEvent"/> event.</summary>
  653. /// <param name="a"></param>
  654. public void OnMouseEvent (MouseEventArgs a)
  655. {
  656. // Ensure ScreenPosition is set
  657. a.ScreenPosition = a.Position;
  658. MouseEvent?.Invoke (this, a);
  659. }
  660. #endregion Mouse Handling
  661. #region Keyboard Handling
  662. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="KeyUp"/>.</summary>
  663. public event EventHandler<Key>? KeyDown;
  664. /// <summary>
  665. /// Called when a key is pressed down. Fires the <see cref="KeyDown"/> event. This is a precursor to
  666. /// <see cref="OnKeyUp"/>.
  667. /// </summary>
  668. /// <param name="a"></param>
  669. public void OnKeyDown (Key a) { KeyDown?.Invoke (this, a); }
  670. /// <summary>Event fired when a key is released.</summary>
  671. /// <remarks>
  672. /// Drivers that do not support key release events will fire this event after <see cref="KeyDown"/> processing is
  673. /// complete.
  674. /// </remarks>
  675. public event EventHandler<Key>? KeyUp;
  676. /// <summary>Called when a key is released. Fires the <see cref="KeyUp"/> event.</summary>
  677. /// <remarks>
  678. /// Drivers that do not support key release events will call this method after <see cref="OnKeyDown"/> processing
  679. /// is complete.
  680. /// </remarks>
  681. /// <param name="a"></param>
  682. public void OnKeyUp (Key a) { KeyUp?.Invoke (this, a); }
  683. // TODO: Remove this API - it was needed when we didn't have a reliable way to simulate key presses.
  684. // TODO: We now do: Applicaiton.RaiseKeyDown and Application.RaiseKeyUp
  685. /// <summary>Simulates a key press.</summary>
  686. /// <param name="keyChar">The key character.</param>
  687. /// <param name="key">The key.</param>
  688. /// <param name="shift">If <see langword="true"/> simulates the Shift key being pressed.</param>
  689. /// <param name="alt">If <see langword="true"/> simulates the Alt key being pressed.</param>
  690. /// <param name="ctrl">If <see langword="true"/> simulates the Ctrl key being pressed.</param>
  691. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl);
  692. #endregion Keyboard Handling
  693. }