ConsoleDriver.cs 32 KB

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