ConsoleDriver.cs 28 KB

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