ConsoleDriver.cs 35 KB

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