OutputBuffer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. Clip ??= new Region (Screen);
  124. Rectangle clipRect = Clip!.GetBounds ();
  125. if (validLocation)
  126. {
  127. rune = rune.MakePrintable ();
  128. runeWidth = rune.GetColumns ();
  129. lock (Contents)
  130. {
  131. if (runeWidth == 0 && rune.IsCombiningMark ())
  132. {
  133. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  134. // compatible with the driver architecture. Any CMs (except in the first col)
  135. // are correctly combined with the base char, but are ALSO treated as 1 column
  136. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  137. //
  138. // Until this is addressed (see Issue #), we do our best by
  139. // a) Attempting to normalize any CM with the base char to it's left
  140. // b) Ignoring any CMs that don't normalize
  141. if (Col > 0)
  142. {
  143. if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
  144. {
  145. // Just add this mark to the list
  146. Contents [Row, Col - 1].AddCombiningMark (rune);
  147. // Ignore. Don't move to next column (let the driver figure out what to do).
  148. }
  149. else
  150. {
  151. // Attempt to normalize the cell to our left combined with this mark
  152. string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
  153. // Normalize to Form C (Canonical Composition)
  154. string normalized = combined.Normalize (NormalizationForm.FormC);
  155. if (normalized.Length == 1)
  156. {
  157. // It normalized! We can just set the Cell to the left with the
  158. // normalized codepoint
  159. Contents [Row, Col - 1].Rune = (Rune)normalized [0];
  160. // Ignore. Don't move to next column because we're already there
  161. }
  162. else
  163. {
  164. // It didn't normalize. Add it to the Cell to left's CM list
  165. Contents [Row, Col - 1].AddCombiningMark (rune);
  166. // Ignore. Don't move to next column (let the driver figure out what to do).
  167. }
  168. }
  169. Contents [Row, Col - 1].Attribute = CurrentAttribute;
  170. Contents [Row, Col - 1].IsDirty = true;
  171. }
  172. else
  173. {
  174. // Most drivers will render a combining mark at col 0 as the mark
  175. Contents [Row, Col].Rune = rune;
  176. Contents [Row, Col].Attribute = CurrentAttribute;
  177. Contents [Row, Col].IsDirty = true;
  178. Col++;
  179. }
  180. }
  181. else
  182. {
  183. Contents [Row, Col].Attribute = CurrentAttribute;
  184. Contents [Row, Col].IsDirty = true;
  185. if (Col > 0)
  186. {
  187. // Check if cell to left has a wide glyph
  188. if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
  189. {
  190. // Invalidate cell to left
  191. Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
  192. Contents [Row, Col - 1].IsDirty = true;
  193. }
  194. }
  195. if (runeWidth < 1)
  196. {
  197. Contents [Row, Col].Rune = Rune.ReplacementChar;
  198. }
  199. else if (runeWidth == 1)
  200. {
  201. Contents [Row, Col].Rune = rune;
  202. if (Col < clipRect.Right - 1)
  203. {
  204. Contents [Row, Col + 1].IsDirty = true;
  205. }
  206. }
  207. else if (runeWidth == 2)
  208. {
  209. if (!Clip.Contains (Col + 1, Row))
  210. {
  211. // We're at the right edge of the clip, so we can't display a wide character.
  212. // TODO: Figure out if it is better to show a replacement character or ' '
  213. Contents [Row, Col].Rune = Rune.ReplacementChar;
  214. }
  215. else if (!Clip.Contains (Col, Row))
  216. {
  217. // Our 1st column is outside the clip, so we can't display a wide character.
  218. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  219. }
  220. else
  221. {
  222. Contents [Row, Col].Rune = rune;
  223. if (Col < clipRect.Right - 1)
  224. {
  225. // Invalidate cell to right so that it doesn't get drawn
  226. // TODO: Figure out if it is better to show a replacement character or ' '
  227. Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
  228. Contents [Row, Col + 1].IsDirty = true;
  229. }
  230. }
  231. }
  232. else
  233. {
  234. // This is a non-spacing character, so we don't need to do anything
  235. Contents [Row, Col].Rune = (Rune)' ';
  236. Contents [Row, Col].IsDirty = false;
  237. }
  238. DirtyLines [Row] = true;
  239. }
  240. }
  241. }
  242. if (runeWidth is < 0 or > 0)
  243. {
  244. Col++;
  245. }
  246. if (runeWidth > 1)
  247. {
  248. Debug.Assert (runeWidth <= 2);
  249. if (validLocation && Col < clipRect.Right)
  250. {
  251. lock (Contents!)
  252. {
  253. // This is a double-width character, and we are not at the end of the line.
  254. // Col now points to the second column of the character. Ensure it doesn't
  255. // Get rendered.
  256. Contents [Row, Col].IsDirty = false;
  257. Contents [Row, Col].Attribute = CurrentAttribute;
  258. // TODO: Determine if we should wipe this out (for now now)
  259. //Contents [Row, Col].Rune = (Rune)' ';
  260. }
  261. }
  262. Col++;
  263. }
  264. }
  265. /// <summary>
  266. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  267. /// convenience method that calls <see cref="AddRune(Rune)"/> with the <see cref="Rune"/> constructor.
  268. /// </summary>
  269. /// <param name="c">Character to add.</param>
  270. public void AddRune (char c) { AddRune (new Rune (c)); }
  271. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  272. /// <remarks>
  273. /// <para>
  274. /// When the method returns, <see cref="Col"/> will be incremented by the number of columns
  275. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="Clip"/> or screen
  276. /// dimensions defined by <see cref="Cols"/>.
  277. /// </para>
  278. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  279. /// </remarks>
  280. /// <param name="str">String.</param>
  281. public void AddStr (string str)
  282. {
  283. List<Rune> runes = str.EnumerateRunes ().ToList ();
  284. for (var i = 0; i < runes.Count; i++)
  285. {
  286. AddRune (runes [i]);
  287. }
  288. }
  289. /// <summary>Clears the <see cref="Contents"/> of the driver.</summary>
  290. public void ClearContents ()
  291. {
  292. Contents = new Cell [Rows, Cols];
  293. //CONCURRENCY: Unsynchronized access to Clip isn't safe.
  294. // TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
  295. Clip = new (Screen);
  296. DirtyLines = new bool [Rows];
  297. lock (Contents)
  298. {
  299. for (var row = 0; row < Rows; row++)
  300. {
  301. for (var c = 0; c < Cols; c++)
  302. {
  303. Contents [row, c] = new ()
  304. {
  305. Rune = (Rune)' ',
  306. Attribute = new Attribute (Color.White, Color.Black),
  307. IsDirty = true
  308. };
  309. }
  310. DirtyLines [row] = true;
  311. }
  312. }
  313. // TODO: Who uses this and why? I am removing for now - this class is a state class not an events class
  314. //ClearedContents?.Invoke (this, EventArgs.Empty);
  315. }
  316. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  317. /// <param name="rune">Used to determine if one or two columns are required.</param>
  318. /// <param name="col">The column.</param>
  319. /// <param name="row">The row.</param>
  320. /// <returns>
  321. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of <see cref="Clip"/>.
  322. /// <see langword="true"/> otherwise.
  323. /// </returns>
  324. public bool IsValidLocation (Rune rune, int col, int row)
  325. {
  326. if (rune.GetColumns () < 2)
  327. {
  328. return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip!.Contains (col, row);
  329. }
  330. return Clip!.Contains (col, row) || Clip!.Contains (col + 1, row);
  331. }
  332. /// <inheritdoc/>
  333. public void SetWindowSize (int cols, int rows)
  334. {
  335. Cols = cols;
  336. Rows = rows;
  337. ClearContents ();
  338. }
  339. /// <inheritdoc/>
  340. public void FillRect (Rectangle rect, Rune rune)
  341. {
  342. // BUGBUG: This should be a method on Region
  343. rect = Rectangle.Intersect (rect, Clip?.GetBounds () ?? Screen);
  344. lock (Contents!)
  345. {
  346. for (int r = rect.Y; r < rect.Y + rect.Height; r++)
  347. {
  348. for (int c = rect.X; c < rect.X + rect.Width; c++)
  349. {
  350. if (!IsValidLocation (rune, c, r))
  351. {
  352. continue;
  353. }
  354. Contents [r, c] = new ()
  355. {
  356. Rune = rune != default (Rune) ? rune : (Rune)' ',
  357. Attribute = CurrentAttribute, IsDirty = true
  358. };
  359. }
  360. }
  361. }
  362. }
  363. /// <inheritdoc/>
  364. public void FillRect (Rectangle rect, char rune)
  365. {
  366. for (int y = rect.Top; y < rect.Top + rect.Height; y++)
  367. {
  368. for (int x = rect.Left; x < rect.Left + rect.Width; x++)
  369. {
  370. Move (x, y);
  371. AddRune (rune);
  372. }
  373. }
  374. }
  375. // TODO: Make internal once Menu is upgraded
  376. /// <summary>
  377. /// Updates <see cref="Col"/> and <see cref="Row"/> to the specified column and row in <see cref="Contents"/>.
  378. /// Used by <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  379. /// </summary>
  380. /// <remarks>
  381. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  382. /// <para>
  383. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="Cols"/> and
  384. /// <see cref="Rows"/>, the method still sets those properties.
  385. /// </para>
  386. /// </remarks>
  387. /// <param name="col">Column to move to.</param>
  388. /// <param name="row">Row to move to.</param>
  389. public virtual void Move (int col, int row)
  390. {
  391. //Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
  392. Col = col;
  393. Row = row;
  394. }
  395. }