ConsoleDriver.cs 30 KB

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