ConsoleDriver.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. #nullable enable
  2. //
  3. // ConsoleDriver.cs: Base class for Terminal.Gui ConsoleDriver implementations.
  4. //
  5. using System.Diagnostics;
  6. namespace Terminal.Gui;
  7. /// <summary>Base class for Terminal.Gui ConsoleDriver implementations.</summary>
  8. /// <remarks>
  9. /// There are currently four implementations: - <see cref="CursesDriver"/> (for Unix and Mac) -
  10. /// <see cref="WindowsDriver"/> - <see cref="NetDriver"/> that uses the .NET Console API - <see cref="FakeConsole"/>
  11. /// for unit testing.
  12. /// </remarks>
  13. public abstract class ConsoleDriver
  14. {
  15. /// <summary>
  16. /// How long after Esc has been pressed before we give up on getting an Ansi escape sequence
  17. /// </summary>
  18. internal TimeSpan EscTimeout = TimeSpan.FromMilliseconds (50);
  19. // As performance is a concern, we keep track of the dirty lines and only refresh those.
  20. // This is in addition to the dirty flag on each cell.
  21. internal bool []? _dirtyLines;
  22. // QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
  23. /// <summary>Gets the location and size of the terminal screen.</summary>
  24. internal Rectangle Screen => new (0, 0, Cols, Rows);
  25. private Region? _clip = null;
  26. /// <summary>
  27. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  28. /// to.
  29. /// </summary>
  30. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  31. internal Region? Clip
  32. {
  33. get => _clip;
  34. set
  35. {
  36. if (_clip == value)
  37. {
  38. return;
  39. }
  40. _clip = value;
  41. // Don't ever let Clip be bigger than Screen
  42. if (_clip is { })
  43. {
  44. _clip.Intersect (Screen);
  45. }
  46. }
  47. }
  48. /// <summary>Get the operating system clipboard.</summary>
  49. public IClipboard? Clipboard { get; internal set; }
  50. /// <summary>
  51. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  52. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  53. /// </summary>
  54. internal int Col { get; private set; }
  55. /// <summary>The number of columns visible in the terminal.</summary>
  56. internal virtual int Cols
  57. {
  58. get => _cols;
  59. set
  60. {
  61. _cols = value;
  62. ClearContents ();
  63. }
  64. }
  65. /// <summary>
  66. /// The contents of the application output. The driver outputs this buffer to the terminal when
  67. /// <see cref="UpdateScreen"/> is called.
  68. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  69. /// </summary>
  70. internal Cell [,]? Contents { get; set; }
  71. /// <summary>The leftmost column in the terminal.</summary>
  72. internal virtual int Left { get; set; } = 0;
  73. /// <summary>
  74. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  75. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  76. /// </summary>
  77. internal int Row { get; private set; }
  78. /// <summary>The number of rows visible in the terminal.</summary>
  79. internal virtual int Rows
  80. {
  81. get => _rows;
  82. set
  83. {
  84. _rows = value;
  85. ClearContents ();
  86. }
  87. }
  88. /// <summary>The topmost row in the terminal.</summary>
  89. internal virtual int Top { get; set; } = 0;
  90. /// <summary>
  91. /// Set this to true in any unit tests that attempt to test drivers other than FakeDriver.
  92. /// <code>
  93. /// public ColorTests ()
  94. /// {
  95. /// ConsoleDriver.RunningUnitTests = true;
  96. /// }
  97. /// </code>
  98. /// </summary>
  99. internal static bool RunningUnitTests { get; set; }
  100. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  101. /// <remarks>
  102. /// <para>
  103. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  104. /// <paramref name="rune"/> required, even if the new column value is outside of the <see cref="Clip"/> or screen
  105. /// dimensions defined by <see cref="Cols"/>.
  106. /// </para>
  107. /// <para>
  108. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  109. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  110. /// will be added instead.
  111. /// </para>
  112. /// </remarks>
  113. /// <param name="rune">Rune to add.</param>
  114. internal void AddRune (Rune rune)
  115. {
  116. int runeWidth = -1;
  117. bool validLocation = IsValidLocation (rune, Col, Row);
  118. if (Contents is null)
  119. {
  120. return;
  121. }
  122. Rectangle clipRect = Clip!.GetBounds ();
  123. if (validLocation)
  124. {
  125. rune = rune.MakePrintable ();
  126. runeWidth = rune.GetColumns ();
  127. lock (Contents)
  128. {
  129. if (runeWidth == 0 && rune.IsCombiningMark ())
  130. {
  131. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  132. // compatible with the driver architecture. Any CMs (except in the first col)
  133. // are correctly combined with the base char, but are ALSO treated as 1 column
  134. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  135. //
  136. // Until this is addressed (see Issue #), we do our best by
  137. // a) Attempting to normalize any CM with the base char to it's left
  138. // b) Ignoring any CMs that don't normalize
  139. if (Col > 0)
  140. {
  141. if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
  142. {
  143. // Just add this mark to the list
  144. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  145. // Ignore. Don't move to next column (let the driver figure out what to do).
  146. }
  147. else
  148. {
  149. // Attempt to normalize the cell to our left combined with this mark
  150. string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
  151. // Normalize to Form C (Canonical Composition)
  152. string normalized = combined.Normalize (NormalizationForm.FormC);
  153. if (normalized.Length == 1)
  154. {
  155. // It normalized! We can just set the Cell to the left with the
  156. // normalized codepoint
  157. Contents [Row, Col - 1].Rune = (Rune)normalized [0];
  158. // Ignore. Don't move to next column because we're already there
  159. }
  160. else
  161. {
  162. // It didn't normalize. Add it to the Cell to left's CM list
  163. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  164. // Ignore. Don't move to next column (let the driver figure out what to do).
  165. }
  166. }
  167. Contents [Row, Col - 1].Attribute = CurrentAttribute;
  168. Contents [Row, Col - 1].IsDirty = true;
  169. }
  170. else
  171. {
  172. // Most drivers will render a combining mark at col 0 as the mark
  173. Contents [Row, Col].Rune = rune;
  174. Contents [Row, Col].Attribute = CurrentAttribute;
  175. Contents [Row, Col].IsDirty = true;
  176. Col++;
  177. }
  178. }
  179. else
  180. {
  181. Contents [Row, Col].Attribute = CurrentAttribute;
  182. Contents [Row, Col].IsDirty = true;
  183. if (Col > 0)
  184. {
  185. // Check if cell to left has a wide glyph
  186. if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
  187. {
  188. // Invalidate cell to left
  189. Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
  190. Contents [Row, Col - 1].IsDirty = true;
  191. }
  192. }
  193. if (runeWidth < 1)
  194. {
  195. Contents [Row, Col].Rune = Rune.ReplacementChar;
  196. }
  197. else if (runeWidth == 1)
  198. {
  199. Contents [Row, Col].Rune = rune;
  200. if (Col < clipRect.Right - 1)
  201. {
  202. Contents [Row, Col + 1].IsDirty = true;
  203. }
  204. }
  205. else if (runeWidth == 2)
  206. {
  207. if (!Clip.Contains (Col + 1, Row))
  208. {
  209. // We're at the right edge of the clip, so we can't display a wide character.
  210. // TODO: Figure out if it is better to show a replacement character or ' '
  211. Contents [Row, Col].Rune = Rune.ReplacementChar;
  212. }
  213. else if (!Clip.Contains (Col, Row))
  214. {
  215. // Our 1st column is outside the clip, so we can't display a wide character.
  216. Contents [Row, Col+1].Rune = Rune.ReplacementChar;
  217. }
  218. else
  219. {
  220. Contents [Row, Col].Rune = rune;
  221. if (Col < clipRect.Right - 1)
  222. {
  223. // Invalidate cell to right so that it doesn't get drawn
  224. // TODO: Figure out if it is better to show a replacement character or ' '
  225. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  226. Contents [Row, Col + 1].IsDirty = true;
  227. }
  228. }
  229. }
  230. else
  231. {
  232. // This is a non-spacing character, so we don't need to do anything
  233. Contents [Row, Col].Rune = (Rune)' ';
  234. Contents [Row, Col].IsDirty = false;
  235. }
  236. _dirtyLines! [Row] = true;
  237. }
  238. }
  239. }
  240. if (runeWidth is < 0 or > 0)
  241. {
  242. Col++;
  243. }
  244. if (runeWidth > 1)
  245. {
  246. Debug.Assert (runeWidth <= 2);
  247. if (validLocation && Col < clipRect.Right)
  248. {
  249. lock (Contents!)
  250. {
  251. // This is a double-width character, and we are not at the end of the line.
  252. // Col now points to the second column of the character. Ensure it doesn't
  253. // Get rendered.
  254. Contents [Row, Col].IsDirty = false;
  255. Contents [Row, Col].Attribute = CurrentAttribute;
  256. // TODO: Determine if we should wipe this out (for now now)
  257. //Contents [Row, Col].Rune = (Rune)' ';
  258. }
  259. }
  260. Col++;
  261. }
  262. }
  263. /// <summary>
  264. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  265. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  266. /// </summary>
  267. /// <param name="c">Character to add.</param>
  268. internal void AddRune (char c) { AddRune (new Rune (c)); }
  269. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  270. /// <remarks>
  271. /// <para>
  272. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  273. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="Clip"/> or screen
  274. /// dimensions defined by <see cref="Cols"/>.
  275. /// </para>
  276. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  277. /// </remarks>
  278. /// <param name="str">String.</param>
  279. internal void AddStr (string str)
  280. {
  281. List<Rune> runes = str.EnumerateRunes ().ToList ();
  282. for (var i = 0; i < runes.Count; i++)
  283. {
  284. AddRune (runes [i]);
  285. }
  286. }
  287. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  288. internal void ClearContents ()
  289. {
  290. Contents = new Cell [Rows, Cols];
  291. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  292. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  293. Clip = new (Screen);
  294. _dirtyLines = new bool [Rows];
  295. lock (Contents)
  296. {
  297. for (var row = 0; row < Rows; row++)
  298. {
  299. for (var c = 0; c < Cols; c++)
  300. {
  301. Contents [row, c] = new Cell
  302. {
  303. Rune = (Rune)' ',
  304. Attribute = new Attribute (Color.White, Color.Black),
  305. IsDirty = true
  306. };
  307. }
  308. _dirtyLines [row] = true;
  309. }
  310. }
  311. ClearedContents?.Invoke (this, EventArgs.Empty);
  312. }
  313. /// <summary>
  314. /// Raised each time <see cref="ClearContents"/> is called. For benchmarking.
  315. /// </summary>
  316. public event EventHandler<EventArgs>? ClearedContents;
  317. /// <summary>
  318. /// Sets <see cref="Contents"/> as dirty for situations where views
  319. /// don't need layout and redrawing, but just refresh the screen.
  320. /// </summary>
  321. internal void SetContentsAsDirty ()
  322. {
  323. lock (Contents!)
  324. {
  325. for (var row = 0; row < Rows; row++)
  326. {
  327. for (var c = 0; c < Cols; c++)
  328. {
  329. Contents [row, c].IsDirty = true;
  330. }
  331. _dirtyLines! [row] = true;
  332. }
  333. }
  334. }
  335. /// <summary>Determines if the terminal cursor should be visible or not and sets it accordingly.</summary>
  336. /// <returns><see langword="true"/> upon success</returns>
  337. public abstract bool EnsureCursorVisibility ();
  338. /// <summary>Fills the specified rectangle with the specified rune, using <see cref="CurrentAttribute"/></summary>
  339. /// <remarks>
  340. /// The value of <see cref="Clip"/> is honored. Any parts of the rectangle not in the clip will not be drawn.
  341. /// </remarks>
  342. /// <param name="rect">The Screen-relative rectangle.</param>
  343. /// <param name="rune">The Rune used to fill the rectangle</param>
  344. internal void FillRect (Rectangle rect, Rune rune = default)
  345. {
  346. // BUGBUG: This should be a method on Region
  347. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  348. lock (Contents!)
  349. {
  350. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  351. {
  352. for (int c = rect.X; c < rect.X + rect.Width; c++)
  353. {
  354. if (!IsValidLocation (rune, c, r))
  355. {
  356. continue;
  357. }
  358. Contents [r, c] = new Cell
  359. {
  360. Rune = (rune != default ? rune : (Rune)' '),
  361. Attribute = CurrentAttribute, IsDirty = true
  362. };
  363. _dirtyLines! [r] = true;
  364. }
  365. }
  366. }
  367. }
  368. /// <summary>
  369. /// Fills the specified rectangle with the specified <see langword="char"/>. This method is a convenience method
  370. /// that calls <see cref="FillRect(Rectangle, Rune)"/>.
  371. /// </summary>
  372. /// <param name="rect"></param>
  373. /// <param name="c"></param>
  374. internal void FillRect (Rectangle rect, char c) { FillRect (rect, new Rune (c)); }
  375. /// <summary>Gets the terminal cursor visibility.</summary>
  376. /// <param name="visibility">The current <see cref="CursorVisibility"/></param>
  377. /// <returns><see langword="true"/> upon success</returns>
  378. public abstract bool GetCursorVisibility (out CursorVisibility visibility);
  379. /// <summary>Returns the name of the driver and relevant library version information.</summary>
  380. /// <returns></returns>
  381. public virtual string GetVersionInfo () { return GetType ().Name; }
  382. /// <summary>Tests if the specified rune is supported by the driver.</summary>
  383. /// <param name="rune"></param>
  384. /// <returns>
  385. /// <see langword="true"/> if the rune can be properly presented; <see langword="false"/> if the driver does not
  386. /// support displaying this rune.
  387. /// </returns>
  388. public virtual bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }
  389. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  390. /// <param name="rune">Used to determine if one or two columns are required.</param>
  391. /// <param name="col">The column.</param>
  392. /// <param name="row">The row.</param>
  393. /// <returns>
  394. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  395. /// <see langword="true"/> otherwise.
  396. /// </returns>
  397. internal bool IsValidLocation (Rune rune, int col, int row)
  398. {
  399. if (rune.GetColumns () < 2)
  400. {
  401. return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row);
  402. }
  403. else
  404. {
  405. return Clip!.Contains (col, row) || Clip!.Contains (col + 1, row);
  406. }
  407. }
  408. // TODO: Make internal once Menu is upgraded
  409. /// <summary>
  410. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  411. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  412. /// </summary>
  413. /// <remarks>
  414. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  415. /// <para>
  416. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  417. /// <see cref="Rows"/>, the method still sets those properties.
  418. /// </para>
  419. /// </remarks>
  420. /// <param name="col">Column to move to.</param>
  421. /// <param name="row">Row to move to.</param>
  422. public virtual void Move (int col, int row)
  423. {
  424. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  425. Col = col;
  426. Row = row;
  427. }
  428. /// <summary>Called when the terminal size changes. Fires the <see cref="SizeChanged"/> event.</summary>
  429. /// <param name="args"></param>
  430. internal void OnSizeChanged (SizeChangedEventArgs args) { SizeChanged?.Invoke (this, args); }
  431. /// <summary>Updates the screen to reflect all the changes that have been done to the display buffer</summary>
  432. internal void Refresh ()
  433. {
  434. bool updated = UpdateScreen ();
  435. UpdateCursor ();
  436. Refreshed?.Invoke (this, new EventArgs<bool> (in updated));
  437. }
  438. /// <summary>
  439. /// Raised each time <see cref="Refresh"/> is called. For benchmarking.
  440. /// </summary>
  441. public event EventHandler<EventArgs<bool>>? Refreshed;
  442. /// <summary>Sets the terminal cursor visibility.</summary>
  443. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  444. /// <returns><see langword="true"/> upon success</returns>
  445. public abstract bool SetCursorVisibility (CursorVisibility visibility);
  446. /// <summary>The event fired when the terminal is resized.</summary>
  447. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  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="CursesDriver"/>.</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. /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
  459. internal abstract MainLoop Init ();
  460. /// <summary>Ends the execution of the console driver.</summary>
  461. internal abstract void End ();
  462. #endregion
  463. #region Color Handling
  464. /// <summary>Gets whether the <see cref="ConsoleDriver"/> supports TrueColor output.</summary>
  465. public virtual bool SupportsTrueColor => true;
  466. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  467. // BUGBUG: Application.Force16Colors should be bool? so if SupportsTrueColor and Application.Force16Colors == false, this doesn't override
  468. /// <summary>
  469. /// Gets or sets whether the <see cref="ConsoleDriver"/> should use 16 colors instead of the default TrueColors.
  470. /// See <see cref="Application.Force16Colors"/> to change this setting via <see cref="ConfigurationManager"/>.
  471. /// </summary>
  472. /// <remarks>
  473. /// <para>
  474. /// Will be forced to <see langword="true"/> if <see cref="ConsoleDriver.SupportsTrueColor"/> is
  475. /// <see langword="false"/>, indicating that the <see cref="ConsoleDriver"/> cannot support TrueColor.
  476. /// </para>
  477. /// </remarks>
  478. internal virtual bool Force16Colors
  479. {
  480. get => Application.Force16Colors || !SupportsTrueColor;
  481. set => Application.Force16Colors = value || !SupportsTrueColor;
  482. }
  483. private Attribute _currentAttribute;
  484. private int _cols;
  485. private int _rows;
  486. /// <summary>
  487. /// The <see cref="Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or <see cref="AddStr"/>
  488. /// call.
  489. /// </summary>
  490. public Attribute CurrentAttribute
  491. {
  492. get => _currentAttribute;
  493. set
  494. {
  495. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. Once Attribute.PlatformColor is removed, this can be fixed.
  496. if (Application.Driver is { })
  497. {
  498. _currentAttribute = new Attribute (value.Foreground, value.Background);
  499. return;
  500. }
  501. _currentAttribute = value;
  502. }
  503. }
  504. /// <summary>Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.</summary>
  505. /// <remarks>Implementations should call <c>base.SetAttribute(c)</c>.</remarks>
  506. /// <param name="c">C.</param>
  507. internal Attribute SetAttribute (Attribute c)
  508. {
  509. Attribute prevAttribute = CurrentAttribute;
  510. CurrentAttribute = c;
  511. return prevAttribute;
  512. }
  513. /// <summary>Gets the current <see cref="Attribute"/>.</summary>
  514. /// <returns>The current attribute.</returns>
  515. internal Attribute GetAttribute () { return CurrentAttribute; }
  516. // TODO: This is only overridden by CursesDriver. Once CursesDriver supports 24-bit color, this virtual method can be
  517. // removed (and Attribute can lose the platformColor property).
  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 Attribute (
  526. -1, // only used by cursesdriver!
  527. foreground,
  528. background
  529. );
  530. }
  531. #endregion
  532. #region Mouse and Keyboard
  533. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="KeyUp"/>.</summary>
  534. public event EventHandler<Key>? KeyDown;
  535. /// <summary>
  536. /// Called when a key is pressed down. Fires the <see cref="KeyDown"/> event. This is a precursor to
  537. /// <see cref="OnKeyUp"/>.
  538. /// </summary>
  539. /// <param name="a"></param>
  540. public void OnKeyDown (Key a) { KeyDown?.Invoke (this, a); }
  541. /// <summary>Event fired when a key is released.</summary>
  542. /// <remarks>
  543. /// Drivers that do not support key release events will fire this event after <see cref="KeyDown"/> processing is
  544. /// complete.
  545. /// </remarks>
  546. public event EventHandler<Key>? KeyUp;
  547. /// <summary>Called when a key is released. Fires the <see cref="KeyUp"/> event.</summary>
  548. /// <remarks>
  549. /// Drivers that do not support key release events will call this method after <see cref="OnKeyDown"/> processing
  550. /// is complete.
  551. /// </remarks>
  552. /// <param name="a"></param>
  553. public void OnKeyUp (Key a) { KeyUp?.Invoke (this, a); }
  554. /// <summary>Event fired when a mouse event occurs.</summary>
  555. public event EventHandler<MouseEventArgs>? MouseEvent;
  556. /// <summary>Called when a mouse event occurs. Fires the <see cref="MouseEvent"/> event.</summary>
  557. /// <param name="a"></param>
  558. public void OnMouseEvent (MouseEventArgs a)
  559. {
  560. // Ensure ScreenPosition is set
  561. a.ScreenPosition = a.Position;
  562. MouseEvent?.Invoke (this, a);
  563. }
  564. /// <summary>Simulates a key press.</summary>
  565. /// <param name="keyChar">The key character.</param>
  566. /// <param name="key">The key.</param>
  567. /// <param name="shift">If <see langword="true"/> simulates the Shift key being pressed.</param>
  568. /// <param name="alt">If <see langword="true"/> simulates the Alt key being pressed.</param>
  569. /// <param name="ctrl">If <see langword="true"/> simulates the Ctrl key being pressed.</param>
  570. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl);
  571. #endregion
  572. private AnsiRequestScheduler? _scheduler;
  573. /// <summary>
  574. /// Queues the given <paramref name="request"/> for execution
  575. /// </summary>
  576. /// <param name="request"></param>
  577. public void QueueAnsiRequest (AnsiEscapeSequenceRequest request)
  578. {
  579. GetRequestScheduler ().SendOrSchedule (request);
  580. }
  581. internal abstract IAnsiResponseParser GetParser ();
  582. internal AnsiRequestScheduler GetRequestScheduler ()
  583. {
  584. // Lazy initialization because GetParser is virtual
  585. return _scheduler ??= new (GetParser ());
  586. }
  587. /// <summary>
  588. /// Writes the given <paramref name="str"/> directly to the console (rather than the output
  589. /// draw buffer).
  590. /// </summary>
  591. /// <param name="str"></param>
  592. internal abstract void RawWrite (string str);
  593. }
  594. /// <summary>
  595. /// The <see cref="KeyCode"/> enumeration encodes key information from <see cref="ConsoleDriver"/>s and provides a
  596. /// consistent way for application code to specify keys and receive key events.
  597. /// <para>
  598. /// The <see cref="Key"/> class provides a higher-level abstraction, with helper methods and properties for
  599. /// common operations. For example, <see cref="Key.IsAlt"/> and <see cref="Key.IsCtrl"/> provide a convenient way
  600. /// to check whether the Alt or Ctrl modifier keys were pressed when a key was pressed.
  601. /// </para>
  602. /// </summary>
  603. /// <remarks>
  604. /// <para>
  605. /// Lowercase alpha keys are encoded as values between 65 and 90 corresponding to the un-shifted A to Z keys on a
  606. /// keyboard. Enum values are provided for these (e.g. <see cref="KeyCode.A"/>, <see cref="KeyCode.B"/>, etc.).
  607. /// Even though the values are the same as the ASCII values for uppercase characters, these enum values represent
  608. /// *lowercase*, un-shifted characters.
  609. /// </para>
  610. /// <para>
  611. /// Numeric keys are the values between 48 and 57 corresponding to 0 to 9 (e.g. <see cref="KeyCode.D0"/>,
  612. /// <see cref="KeyCode.D1"/>, etc.).
  613. /// </para>
  614. /// <para>
  615. /// The shift modifiers (<see cref="KeyCode.ShiftMask"/>, <see cref="KeyCode.CtrlMask"/>, and
  616. /// <see cref="KeyCode.AltMask"/>) can be combined (with logical or) with the other key codes to represent shifted
  617. /// keys. For example, the <see cref="KeyCode.A"/> enum value represents the un-shifted 'a' key, while
  618. /// <see cref="KeyCode.ShiftMask"/> | <see cref="KeyCode.A"/> represents the 'A' key (shifted 'a' key). Likewise,
  619. /// <see cref="KeyCode.AltMask"/> | <see cref="KeyCode.A"/> represents the 'Alt+A' key combination.
  620. /// </para>
  621. /// <para>
  622. /// All other keys that produce a printable character are encoded as the Unicode value of the character. For
  623. /// example, the <see cref="KeyCode"/> for the '!' character is 33, which is the Unicode value for '!'. Likewise,
  624. /// `â` is 226, `Â` is 194, etc.
  625. /// </para>
  626. /// <para>
  627. /// If the <see cref="SpecialMask"/> is set, then the value is that of the special mask, otherwise, the value is
  628. /// the one of the lower bits (as extracted by <see cref="CharMask"/>).
  629. /// </para>
  630. /// </remarks>
  631. [Flags]
  632. public enum KeyCode : uint
  633. {
  634. /// <summary>
  635. /// Mask that indicates that the key is a unicode codepoint. Values outside this range indicate the key has shift
  636. /// modifiers or is a special key like function keys, arrows keys and so on.
  637. /// </summary>
  638. CharMask = 0x_f_ffff,
  639. /// <summary>
  640. /// If the <see cref="SpecialMask"/> is set, then the value is that of the special mask, otherwise, the value is
  641. /// in the lower bits (as extracted by <see cref="CharMask"/>).
  642. /// </summary>
  643. SpecialMask = 0x_fff0_0000,
  644. /// <summary>
  645. /// When this value is set, the Key encodes the sequence Shift-KeyValue. The actual value must be extracted by
  646. /// removing the ShiftMask.
  647. /// </summary>
  648. ShiftMask = 0x_1000_0000,
  649. /// <summary>
  650. /// When this value is set, the Key encodes the sequence Alt-KeyValue. The actual value must be extracted by
  651. /// removing the AltMask.
  652. /// </summary>
  653. AltMask = 0x_8000_0000,
  654. /// <summary>
  655. /// When this value is set, the Key encodes the sequence Ctrl-KeyValue. The actual value must be extracted by
  656. /// removing the CtrlMask.
  657. /// </summary>
  658. CtrlMask = 0x_4000_0000,
  659. /// <summary>The key code representing an invalid or empty key.</summary>
  660. Null = 0,
  661. /// <summary>Backspace key.</summary>
  662. Backspace = 8,
  663. /// <summary>The key code for the tab key (forwards tab key).</summary>
  664. Tab = 9,
  665. /// <summary>The key code for the return key.</summary>
  666. Enter = ConsoleKey.Enter,
  667. /// <summary>The key code for the clear key.</summary>
  668. Clear = 12,
  669. /// <summary>The key code for the escape key.</summary>
  670. Esc = 27,
  671. /// <summary>The key code for the space bar key.</summary>
  672. Space = 32,
  673. /// <summary>Digit 0.</summary>
  674. D0 = 48,
  675. /// <summary>Digit 1.</summary>
  676. D1,
  677. /// <summary>Digit 2.</summary>
  678. D2,
  679. /// <summary>Digit 3.</summary>
  680. D3,
  681. /// <summary>Digit 4.</summary>
  682. D4,
  683. /// <summary>Digit 5.</summary>
  684. D5,
  685. /// <summary>Digit 6.</summary>
  686. D6,
  687. /// <summary>Digit 7.</summary>
  688. D7,
  689. /// <summary>Digit 8.</summary>
  690. D8,
  691. /// <summary>Digit 9.</summary>
  692. D9,
  693. /// <summary>The key code for the A key</summary>
  694. A = 65,
  695. /// <summary>The key code for the B key</summary>
  696. B,
  697. /// <summary>The key code for the C key</summary>
  698. C,
  699. /// <summary>The key code for the D key</summary>
  700. D,
  701. /// <summary>The key code for the E key</summary>
  702. E,
  703. /// <summary>The key code for the F key</summary>
  704. F,
  705. /// <summary>The key code for the G key</summary>
  706. G,
  707. /// <summary>The key code for the H key</summary>
  708. H,
  709. /// <summary>The key code for the I key</summary>
  710. I,
  711. /// <summary>The key code for the J key</summary>
  712. J,
  713. /// <summary>The key code for the K key</summary>
  714. K,
  715. /// <summary>The key code for the L key</summary>
  716. L,
  717. /// <summary>The key code for the M key</summary>
  718. M,
  719. /// <summary>The key code for the N key</summary>
  720. N,
  721. /// <summary>The key code for the O key</summary>
  722. O,
  723. /// <summary>The key code for the P key</summary>
  724. P,
  725. /// <summary>The key code for the Q key</summary>
  726. Q,
  727. /// <summary>The key code for the R key</summary>
  728. R,
  729. /// <summary>The key code for the S key</summary>
  730. S,
  731. /// <summary>The key code for the T key</summary>
  732. T,
  733. /// <summary>The key code for the U key</summary>
  734. U,
  735. /// <summary>The key code for the V key</summary>
  736. V,
  737. /// <summary>The key code for the W key</summary>
  738. W,
  739. /// <summary>The key code for the X key</summary>
  740. X,
  741. /// <summary>The key code for the Y key</summary>
  742. Y,
  743. /// <summary>The key code for the Z key</summary>
  744. Z,
  745. ///// <summary>
  746. ///// The key code for the Delete key.
  747. ///// </summary>
  748. //Delete = 127,
  749. // --- Special keys ---
  750. // The values below are common non-alphanum keys. Their values are
  751. // based on the .NET ConsoleKey values, which, in-turn are based on the
  752. // VK_ values from the Windows API.
  753. // We add MaxCodePoint to avoid conflicts with the Unicode values.
  754. /// <summary>The maximum Unicode codepoint value. Used to encode the non-alphanumeric control keys.</summary>
  755. MaxCodePoint = 0x10FFFF,
  756. /// <summary>Cursor up key</summary>
  757. CursorUp = MaxCodePoint + ConsoleKey.UpArrow,
  758. /// <summary>Cursor down key.</summary>
  759. CursorDown = MaxCodePoint + ConsoleKey.DownArrow,
  760. /// <summary>Cursor left key.</summary>
  761. CursorLeft = MaxCodePoint + ConsoleKey.LeftArrow,
  762. /// <summary>Cursor right key.</summary>
  763. CursorRight = MaxCodePoint + ConsoleKey.RightArrow,
  764. /// <summary>Page Up key.</summary>
  765. PageUp = MaxCodePoint + ConsoleKey.PageUp,
  766. /// <summary>Page Down key.</summary>
  767. PageDown = MaxCodePoint + ConsoleKey.PageDown,
  768. /// <summary>Home key.</summary>
  769. Home = MaxCodePoint + ConsoleKey.Home,
  770. /// <summary>End key.</summary>
  771. End = MaxCodePoint + ConsoleKey.End,
  772. /// <summary>Insert (INS) key.</summary>
  773. Insert = MaxCodePoint + ConsoleKey.Insert,
  774. /// <summary>Delete (DEL) key.</summary>
  775. Delete = MaxCodePoint + ConsoleKey.Delete,
  776. /// <summary>Print screen character key.</summary>
  777. PrintScreen = MaxCodePoint + ConsoleKey.PrintScreen,
  778. /// <summary>F1 key.</summary>
  779. F1 = MaxCodePoint + ConsoleKey.F1,
  780. /// <summary>F2 key.</summary>
  781. F2 = MaxCodePoint + ConsoleKey.F2,
  782. /// <summary>F3 key.</summary>
  783. F3 = MaxCodePoint + ConsoleKey.F3,
  784. /// <summary>F4 key.</summary>
  785. F4 = MaxCodePoint + ConsoleKey.F4,
  786. /// <summary>F5 key.</summary>
  787. F5 = MaxCodePoint + ConsoleKey.F5,
  788. /// <summary>F6 key.</summary>
  789. F6 = MaxCodePoint + ConsoleKey.F6,
  790. /// <summary>F7 key.</summary>
  791. F7 = MaxCodePoint + ConsoleKey.F7,
  792. /// <summary>F8 key.</summary>
  793. F8 = MaxCodePoint + ConsoleKey.F8,
  794. /// <summary>F9 key.</summary>
  795. F9 = MaxCodePoint + ConsoleKey.F9,
  796. /// <summary>F10 key.</summary>
  797. F10 = MaxCodePoint + ConsoleKey.F10,
  798. /// <summary>F11 key.</summary>
  799. F11 = MaxCodePoint + ConsoleKey.F11,
  800. /// <summary>F12 key.</summary>
  801. F12 = MaxCodePoint + ConsoleKey.F12,
  802. /// <summary>F13 key.</summary>
  803. F13 = MaxCodePoint + ConsoleKey.F13,
  804. /// <summary>F14 key.</summary>
  805. F14 = MaxCodePoint + ConsoleKey.F14,
  806. /// <summary>F15 key.</summary>
  807. F15 = MaxCodePoint + ConsoleKey.F15,
  808. /// <summary>F16 key.</summary>
  809. F16 = MaxCodePoint + ConsoleKey.F16,
  810. /// <summary>F17 key.</summary>
  811. F17 = MaxCodePoint + ConsoleKey.F17,
  812. /// <summary>F18 key.</summary>
  813. F18 = MaxCodePoint + ConsoleKey.F18,
  814. /// <summary>F19 key.</summary>
  815. F19 = MaxCodePoint + ConsoleKey.F19,
  816. /// <summary>F20 key.</summary>
  817. F20 = MaxCodePoint + ConsoleKey.F20,
  818. /// <summary>F21 key.</summary>
  819. F21 = MaxCodePoint + ConsoleKey.F21,
  820. /// <summary>F22 key.</summary>
  821. F22 = MaxCodePoint + ConsoleKey.F22,
  822. /// <summary>F23 key.</summary>
  823. F23 = MaxCodePoint + ConsoleKey.F23,
  824. /// <summary>F24 key.</summary>
  825. F24 = MaxCodePoint + ConsoleKey.F24
  826. }