ConsoleDriver.cs 28 KB

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