ConsoleDriver.cs 28 KB

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