OutputBuffer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Stores the desired output state for the whole application. This is updated during
  6. /// draw operations before being flushed to the console as part of <see cref="MainLoop{T}"/>
  7. /// operation
  8. /// </summary>
  9. public class OutputBuffer : IOutputBuffer
  10. {
  11. /// <summary>
  12. /// The contents of the application output. The driver outputs this buffer to the terminal when
  13. /// UpdateScreen is called.
  14. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  15. /// </summary>
  16. public Cell [,] Contents { get; set; } = new Cell[0, 0];
  17. private Attribute _currentAttribute;
  18. private int _cols;
  19. private int _rows;
  20. /// <summary>
  21. /// The <see cref="Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or <see cref="AddStr"/>
  22. /// call.
  23. /// </summary>
  24. public Attribute CurrentAttribute
  25. {
  26. get => _currentAttribute;
  27. set
  28. {
  29. // TODO: This makes IConsoleDriver dependent on Application, which is not ideal. Once Attribute.PlatformColor is removed, this can be fixed.
  30. if (Application.Driver is { })
  31. {
  32. _currentAttribute = new (value.Foreground, value.Background);
  33. return;
  34. }
  35. _currentAttribute = value;
  36. }
  37. }
  38. /// <summary>The leftmost column in the terminal.</summary>
  39. public virtual int Left { get; set; } = 0;
  40. /// <summary>
  41. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  42. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  43. /// </summary>
  44. public int Row { get; private set; }
  45. /// <summary>
  46. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  47. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  48. /// </summary>
  49. public int Col { get; private set; }
  50. /// <summary>The number of rows visible in the terminal.</summary>
  51. public int Rows
  52. {
  53. get => _rows;
  54. set
  55. {
  56. _rows = value;
  57. ClearContents ();
  58. }
  59. }
  60. /// <summary>The number of columns visible in the terminal.</summary>
  61. public int Cols
  62. {
  63. get => _cols;
  64. set
  65. {
  66. _cols = value;
  67. ClearContents ();
  68. }
  69. }
  70. /// <summary>The topmost row in the terminal.</summary>
  71. public virtual int Top { get; set; } = 0;
  72. /// <inheritdoc/>
  73. public bool [] DirtyLines { get; set; } = [];
  74. // QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
  75. /// <summary>Gets the location and size of the terminal screen.</summary>
  76. internal Rectangle Screen => new (0, 0, Cols, Rows);
  77. private Region? _clip;
  78. /// <summary>
  79. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  80. /// to.
  81. /// </summary>
  82. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  83. public Region? Clip
  84. {
  85. get => _clip;
  86. set
  87. {
  88. if (_clip == value)
  89. {
  90. return;
  91. }
  92. _clip = value;
  93. // Don't ever let Clip be bigger than Screen
  94. if (_clip is { })
  95. {
  96. _clip.Intersect (Screen);
  97. }
  98. }
  99. }
  100. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  101. /// <remarks>
  102. /// <para>
  103. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  104. /// <paramref name="rune"/> required, even if the new column value is outside of the <see cref="Clip"/> or screen
  105. /// dimensions defined by <see cref="Cols"/>.
  106. /// </para>
  107. /// <para>
  108. /// If <paramref name="rune"/> requires more than one column, and <see cref="Col"/> plus the number of columns
  109. /// needed exceeds the <see cref="Clip"/> or screen dimensions, the default Unicode replacement character (U+FFFD)
  110. /// will be added instead.
  111. /// </para>
  112. /// </remarks>
  113. /// <param name="rune">Rune to add.</param>
  114. public void AddRune (Rune rune)
  115. {
  116. int runeWidth = -1;
  117. bool validLocation = IsValidLocation (rune, Col, Row);
  118. if (Contents is null)
  119. {
  120. return;
  121. }
  122. Rectangle clipRect = Clip!.GetBounds ();
  123. if (validLocation)
  124. {
  125. rune = rune.MakePrintable ();
  126. runeWidth = rune.GetColumns ();
  127. lock (Contents)
  128. {
  129. if (runeWidth == 0 && rune.IsCombiningMark ())
  130. {
  131. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  132. // compatible with the driver architecture. Any CMs (except in the first col)
  133. // are correctly combined with the base char, but are ALSO treated as 1 column
  134. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  135. //
  136. // Until this is addressed (see Issue #), we do our best by
  137. // a) Attempting to normalize any CM with the base char to it's left
  138. // b) Ignoring any CMs that don't normalize
  139. if (Col > 0)
  140. {
  141. if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
  142. {
  143. // Just add this mark to the list
  144. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  145. // Ignore. Don't move to next column (let the driver figure out what to do).
  146. }
  147. else
  148. {
  149. // Attempt to normalize the cell to our left combined with this mark
  150. string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
  151. // Normalize to Form C (Canonical Composition)
  152. string normalized = combined.Normalize (NormalizationForm.FormC);
  153. if (normalized.Length == 1)
  154. {
  155. // It normalized! We can just set the Cell to the left with the
  156. // normalized codepoint
  157. Contents [Row, Col - 1].Rune = (Rune)normalized [0];
  158. // Ignore. Don't move to next column because we're already there
  159. }
  160. else
  161. {
  162. // It didn't normalize. Add it to the Cell to left's CM list
  163. Contents [Row, Col - 1].CombiningMarks.Add (rune);
  164. // Ignore. Don't move to next column (let the driver figure out what to do).
  165. }
  166. }
  167. Contents [Row, Col - 1].Attribute = CurrentAttribute;
  168. Contents [Row, Col - 1].IsDirty = true;
  169. }
  170. else
  171. {
  172. // Most drivers will render a combining mark at col 0 as the mark
  173. Contents [Row, Col].Rune = rune;
  174. Contents [Row, Col].Attribute = CurrentAttribute;
  175. Contents [Row, Col].IsDirty = true;
  176. Col++;
  177. }
  178. }
  179. else
  180. {
  181. Contents [Row, Col].Attribute = CurrentAttribute;
  182. Contents [Row, Col].IsDirty = true;
  183. if (Col > 0)
  184. {
  185. // Check if cell to left has a wide glyph
  186. if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
  187. {
  188. // Invalidate cell to left
  189. Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
  190. Contents [Row, Col - 1].IsDirty = true;
  191. }
  192. }
  193. if (runeWidth < 1)
  194. {
  195. Contents [Row, Col].Rune = Rune.ReplacementChar;
  196. }
  197. else if (runeWidth == 1)
  198. {
  199. Contents [Row, Col].Rune = rune;
  200. if (Col < clipRect.Right - 1)
  201. {
  202. Contents [Row, Col + 1].IsDirty = true;
  203. }
  204. }
  205. else if (runeWidth == 2)
  206. {
  207. if (!Clip.Contains (Col + 1, Row))
  208. {
  209. // We're at the right edge of the clip, so we can't display a wide character.
  210. // TODO: Figure out if it is better to show a replacement character or ' '
  211. Contents [Row, Col].Rune = Rune.ReplacementChar;
  212. }
  213. else if (!Clip.Contains (Col, Row))
  214. {
  215. // Our 1st column is outside the clip, so we can't display a wide character.
  216. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  217. }
  218. else
  219. {
  220. Contents [Row, Col].Rune = rune;
  221. if (Col < clipRect.Right - 1)
  222. {
  223. // Invalidate cell to right so that it doesn't get drawn
  224. // TODO: Figure out if it is better to show a replacement character or ' '
  225. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  226. Contents [Row, Col + 1].IsDirty = true;
  227. }
  228. }
  229. }
  230. else
  231. {
  232. // This is a non-spacing character, so we don't need to do anything
  233. Contents [Row, Col].Rune = (Rune)' ';
  234. Contents [Row, Col].IsDirty = false;
  235. }
  236. DirtyLines [Row] = true;
  237. }
  238. }
  239. }
  240. if (runeWidth is < 0 or > 0)
  241. {
  242. Col++;
  243. }
  244. if (runeWidth > 1)
  245. {
  246. Debug.Assert (runeWidth <= 2);
  247. if (validLocation && Col < clipRect.Right)
  248. {
  249. lock (Contents!)
  250. {
  251. // This is a double-width character, and we are not at the end of the line.
  252. // Col now points to the second column of the character. Ensure it doesn't
  253. // Get rendered.
  254. Contents [Row, Col].IsDirty = false;
  255. Contents [Row, Col].Attribute = CurrentAttribute;
  256. // TODO: Determine if we should wipe this out (for now now)
  257. //Contents [Row, Col].Rune = (Rune)' ';
  258. }
  259. }
  260. Col++;
  261. }
  262. }
  263. /// <summary>
  264. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  265. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  266. /// </summary>
  267. /// <param name="c">Character to add.</param>
  268. public void AddRune (char c) { AddRune (new Rune (c)); }
  269. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  270. /// <remarks>
  271. /// <para>
  272. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  273. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="Clip"/> or screen
  274. /// dimensions defined by <see cref="Cols"/>.
  275. /// </para>
  276. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  277. /// </remarks>
  278. /// <param name="str">String.</param>
  279. public void AddStr (string str)
  280. {
  281. List<Rune> runes = str.EnumerateRunes ().ToList ();
  282. for (var i = 0; i < runes.Count; i++)
  283. {
  284. AddRune (runes [i]);
  285. }
  286. }
  287. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  288. public void ClearContents ()
  289. {
  290. Contents = new Cell [Rows, Cols];
  291. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  292. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  293. Clip = new (Screen);
  294. DirtyLines = new bool [Rows];
  295. lock (Contents)
  296. {
  297. for (var row = 0; row < Rows; row++)
  298. {
  299. for (var c = 0; c < Cols; c++)
  300. {
  301. Contents [row, c] = new ()
  302. {
  303. Rune = (Rune)' ',
  304. Attribute = new Attribute (Color.White, Color.Black),
  305. IsDirty = true
  306. };
  307. }
  308. DirtyLines [row] = true;
  309. }
  310. }
  311. // TODO: Who uses this and why? I am removing for now - this class is a state class not an events class
  312. //ClearedContents?.Invoke (this, EventArgs.Empty);
  313. }
  314. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  315. /// <param name="rune">Used to determine if one or two columns are required.</param>
  316. /// <param name="col">The column.</param>
  317. /// <param name="row">The row.</param>
  318. /// <returns>
  319. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  320. /// <see langword="true"/> otherwise.
  321. /// </returns>
  322. public bool IsValidLocation (Rune rune, int col, int row)
  323. {
  324. if (rune.GetColumns () < 2)
  325. {
  326. return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row);
  327. }
  328. return Clip!.Contains (col, row) || Clip!.Contains (col + 1, row);
  329. }
  330. /// <inheritdoc/>
  331. public void SetWindowSize (int cols, int rows)
  332. {
  333. Cols = cols;
  334. Rows = rows;
  335. ClearContents ();
  336. }
  337. /// <inheritdoc/>
  338. public void FillRect (Rectangle rect, Rune rune)
  339. {
  340. // BUGBUG: This should be a method on Region
  341. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  342. lock (Contents!)
  343. {
  344. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  345. {
  346. for (int c = rect.X; c < rect.X + rect.Width; c++)
  347. {
  348. if (!IsValidLocation (rune, c, r))
  349. {
  350. continue;
  351. }
  352. Contents [r, c] = new ()
  353. {
  354. Rune = rune != default (Rune) ? rune : (Rune)' ',
  355. Attribute = CurrentAttribute, IsDirty = true
  356. };
  357. }
  358. }
  359. }
  360. }
  361. /// <inheritdoc/>
  362. public void FillRect (Rectangle rect, char rune)
  363. {
  364. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  365. {
  366. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  367. {
  368. Move (x, y);
  369. AddRune (rune);
  370. }
  371. }
  372. }
  373. // TODO: Make internal once Menu is upgraded
  374. /// <summary>
  375. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  376. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  377. /// </summary>
  378. /// <remarks>
  379. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  380. /// <para>
  381. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  382. /// <see cref="Rows"/>, the method still sets those properties.
  383. /// </para>
  384. /// </remarks>
  385. /// <param name="col">Column to move to.</param>
  386. /// <param name="row">Row to move to.</param>
  387. public virtual void Move (int col, int row)
  388. {
  389. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  390. Col = col;
  391. Row = row;
  392. }
  393. }