2
0

ConsoleDriver.cs 41 KB

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