ConsoleDriver.cs 28 KB

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