ConsoleDriver.cs 30 KB

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