OutputBuffer.cs 17 KB

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