ConsoleDriver.cs 36 KB

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