ConsoleDriver.cs 28 KB

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