ConsoleDriver.cs 32 KB

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