buffer_reflow.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import 'dart:math';
  2. import 'buffer.dart';
  3. import 'buffer_line.dart';
  4. class LayoutResult {
  5. LayoutResult(this.layout, this.removedCount);
  6. final List<int> layout;
  7. final int removedCount;
  8. }
  9. class InsertionSet {
  10. InsertionSet({this.lines, this.start, this.isNull = false});
  11. final List<BufferLine>? lines;
  12. final int? start;
  13. final bool isNull;
  14. static InsertionSet nullValue = InsertionSet(isNull: true);
  15. }
  16. class BufferReflow {
  17. BufferReflow(this._buffer);
  18. final Buffer _buffer;
  19. void doReflow(int colsBefore, int colsAfter) {
  20. if (colsBefore == colsAfter) {
  21. return;
  22. }
  23. if (colsAfter > colsBefore) {
  24. //got larger
  25. _reflowLarger(colsBefore, colsAfter);
  26. } else {
  27. //got smaller
  28. _reflowSmaller(colsBefore, colsAfter);
  29. }
  30. }
  31. void _reflowLarger(int colsBefore, int colsAfter) {
  32. var toRemove = _reflowLargerGetLinesToRemove(colsBefore, colsAfter);
  33. if (toRemove.length > 0) {
  34. var newLayoutResult =
  35. _reflowLargerCreateNewLayout(_buffer.lines, toRemove);
  36. _reflowLargerApplyNewLayout(newLayoutResult.layout);
  37. _reflowLargerAdjustViewport(
  38. colsBefore, colsAfter, newLayoutResult.removedCount);
  39. }
  40. }
  41. void _reflowSmaller(int colsBefore, int colsAfter) {
  42. // Gather all BufferLines that need to be inserted into the Buffer here so that they can be
  43. // batched up and only committed once
  44. List<InsertionSet> toInsert = [];
  45. int countToInsert = 0;
  46. // Go backwards as many lines may be trimmed and this will avoid considering them
  47. for (int y = _buffer.lines.length - 1; y >= 0; y--) {
  48. // Check whether this line is a problem or not, if not skip it
  49. BufferLine nextLine = _buffer.lines[y];
  50. int lineLength = nextLine.getTrimmedLength(colsBefore);
  51. if (!nextLine.isWrapped && lineLength <= colsAfter) {
  52. continue;
  53. }
  54. // Gather wrapped lines and adjust y to be the starting line
  55. List<BufferLine> wrappedLines = [];
  56. wrappedLines.add(nextLine);
  57. while (nextLine.isWrapped && y > 0) {
  58. nextLine = _buffer.lines[--y];
  59. wrappedLines.insert(0, nextLine);
  60. }
  61. // If these lines contain the cursor don't touch them, the program will handle fixing up
  62. // wrapped lines with the cursor
  63. final absoluteY = _buffer.cursorY + _buffer.scrollOffsetFromTop;
  64. if (absoluteY >= y && absoluteY < y + wrappedLines.length) {
  65. continue;
  66. }
  67. int lastLineLength = wrappedLines.last.getTrimmedLength(colsBefore);
  68. List<int> destLineLengths =
  69. _getNewLineLengths(wrappedLines, colsBefore, colsAfter);
  70. int linesToAdd = destLineLengths.length - wrappedLines.length;
  71. // Add the new lines
  72. List<BufferLine> newLines = [];
  73. for (int i = 0; i < linesToAdd; i++) {
  74. BufferLine newLine = BufferLine(isWrapped: true);
  75. newLines.add(newLine);
  76. }
  77. if (newLines.length > 0) {
  78. toInsert.add(InsertionSet(
  79. start: y + wrappedLines.length + countToInsert, lines: newLines));
  80. countToInsert += newLines.length;
  81. }
  82. newLines.forEach((l) => wrappedLines.add(l));
  83. // Copy buffer data to new locations, this needs to happen backwards to do in-place
  84. int destLineIndex =
  85. destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);
  86. int destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;
  87. if (destCol == 0) {
  88. destLineIndex--;
  89. destCol = destLineLengths[destLineIndex];
  90. }
  91. int srcLineIndex = wrappedLines.length - linesToAdd - 1;
  92. int srcCol = lastLineLength;
  93. while (srcLineIndex >= 0) {
  94. int cellsToCopy = min(srcCol, destCol);
  95. wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex],
  96. srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy);
  97. destCol -= cellsToCopy;
  98. if (destCol == 0) {
  99. destLineIndex--;
  100. if (destLineIndex >= 0) destCol = destLineLengths[destLineIndex];
  101. }
  102. srcCol -= cellsToCopy;
  103. if (srcCol == 0) {
  104. srcLineIndex--;
  105. int wrappedLinesIndex = max(srcLineIndex, 0);
  106. srcCol = _getWrappedLineTrimmedLengthRow(
  107. wrappedLines, wrappedLinesIndex, colsBefore);
  108. }
  109. }
  110. // Null out the end of the line ends if a wide character wrapped to the following line
  111. for (int i = 0; i < wrappedLines.length; i++) {
  112. if (destLineLengths[i] < colsAfter) {
  113. wrappedLines[i].removeRange(destLineLengths[i], colsBefore);
  114. }
  115. }
  116. _buffer.adjustSavedCursor(0, linesToAdd);
  117. //TODO: maybe row count has to be handled here?
  118. }
  119. _rearrange(toInsert, countToInsert);
  120. }
  121. void _rearrange(List<InsertionSet> toInsert, int countToInsert) {
  122. // Rearrange lines in the buffer if there are any insertions, this is done at the end rather
  123. // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many
  124. // costly calls to CircularList.splice.
  125. if (toInsert.length > 0) {
  126. // Record original lines so they don't get overridden when we rearrange the list
  127. List<BufferLine> originalLines = List<BufferLine>.from(_buffer.lines);
  128. _buffer.lines.addAll(
  129. List<BufferLine>.generate(countToInsert, (index) => BufferLine()));
  130. int originalLinesLength = originalLines.length;
  131. int originalLineIndex = originalLinesLength - 1;
  132. int nextToInsertIndex = 0;
  133. InsertionSet nextToInsert = toInsert[nextToInsertIndex];
  134. //TODO: remove rows that now are "too much"
  135. int countInsertedSoFar = 0;
  136. for (int i = originalLinesLength + countToInsert - 1; i >= 0; i--) {
  137. if (!nextToInsert.isNull &&
  138. nextToInsert.start != null &&
  139. nextToInsert.lines != null &&
  140. nextToInsert.start! > originalLineIndex + countInsertedSoFar) {
  141. // Insert extra lines here, adjusting i as needed
  142. for (int nextI = nextToInsert.lines!.length - 1;
  143. nextI >= 0;
  144. nextI--) {
  145. if (i < 0) {
  146. // if we reflow and the content has to be scrolled back past the beginning
  147. // of the buffer then we end up loosing those lines
  148. break;
  149. }
  150. _buffer.lines[i--] = nextToInsert.lines![nextI];
  151. }
  152. i++;
  153. countInsertedSoFar += nextToInsert.lines!.length;
  154. if (nextToInsertIndex < toInsert.length - 1) {
  155. nextToInsert = toInsert[++nextToInsertIndex];
  156. } else {
  157. nextToInsert = InsertionSet.nullValue; //TODO: just break?
  158. }
  159. } else {
  160. _buffer.lines[i] = originalLines[originalLineIndex--];
  161. }
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-
  167. /// compute the wrapping points since wide characters may need to be wrapped onto the following line.
  168. /// This function will return an array of numbers of where each line wraps to, the resulting array
  169. /// will only contain the values `newCols` (when the line does not end with a wide character) and
  170. /// `newCols - 1` (when the line does end with a wide character), except for the last value which
  171. /// will contain the remaining items to fill the line.
  172. /// Calling this with a `newCols` value of `1` will lock up.
  173. /// </summary>
  174. List<int> _getNewLineLengths(
  175. List<BufferLine> wrappedLines, int oldCols, int newCols) {
  176. List<int> newLineLengths = [];
  177. int cellsNeeded = 0;
  178. for (int i = 0; i < wrappedLines.length; i++) {
  179. cellsNeeded += _getWrappedLineTrimmedLengthRow(wrappedLines, i, oldCols);
  180. }
  181. // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and
  182. // linesNeeded
  183. int srcCol = 0;
  184. int srcLine = 0;
  185. int cellsAvailable = 0;
  186. while (cellsAvailable < cellsNeeded) {
  187. if (cellsNeeded - cellsAvailable < newCols) {
  188. // Add the final line and exit the loop
  189. newLineLengths.add(cellsNeeded - cellsAvailable);
  190. break;
  191. }
  192. srcCol += newCols;
  193. int oldTrimmedLength =
  194. _getWrappedLineTrimmedLengthRow(wrappedLines, srcLine, oldCols);
  195. if (srcCol > oldTrimmedLength) {
  196. srcCol -= oldTrimmedLength;
  197. srcLine++;
  198. }
  199. bool endsWithWide = wrappedLines[srcLine].cellGetWidth(srcCol - 1) == 2;
  200. if (endsWithWide) {
  201. srcCol--;
  202. }
  203. int lineLength = endsWithWide ? newCols - 1 : newCols;
  204. newLineLengths.add(lineLength);
  205. cellsAvailable += lineLength;
  206. }
  207. return newLineLengths;
  208. }
  209. void _reflowLargerAdjustViewport(
  210. int colsBefore, int colsAfter, int countRemoved) {
  211. // Adjust viewport based on number of items removed
  212. var viewportAdjustments = countRemoved;
  213. while (viewportAdjustments-- > 0) {
  214. //viewport is at the top
  215. if (_buffer.lines.length <= _buffer.terminal.viewHeight) {
  216. //cursor is not at the top
  217. if (_buffer.cursorY > 0) {
  218. _buffer.moveCursorY(-1);
  219. }
  220. //buffer doesn't have enough lines
  221. if (_buffer.lines.length < _buffer.terminal.viewHeight) {
  222. // Add an extra row at the bottom of the viewport
  223. _buffer.lines.add(BufferLine());
  224. }
  225. }
  226. }
  227. //TODO: adjust buffer content to max length
  228. _buffer.adjustSavedCursor(0, -countRemoved);
  229. }
  230. void _reflowLargerApplyNewLayout(List<int> newLayout) {
  231. var newLayoutLines = List<BufferLine>.generate(
  232. newLayout.length, (index) => _buffer.lines[newLayout[index]]);
  233. // Rearrange the list
  234. for (int i = 0; i < newLayoutLines.length; i++) {
  235. _buffer.lines[i] = newLayoutLines[i];
  236. }
  237. _buffer.lines
  238. .removeRange(newLayoutLines.length - 1, _buffer.lines.length - 1);
  239. }
  240. LayoutResult _reflowLargerCreateNewLayout(
  241. List<BufferLine> lines, List<int> toRemove) {
  242. var layout = List<int>.empty(growable: true);
  243. // First iterate through the list and get the actual indexes to use for rows
  244. int nextToRemoveIndex = 0;
  245. int nextToRemoveStart = toRemove[nextToRemoveIndex];
  246. int countRemovedSoFar = 0;
  247. for (int i = 0; i < lines.length; i++) {
  248. if (nextToRemoveStart == i) {
  249. int countToRemove = toRemove[++nextToRemoveIndex];
  250. i += countToRemove - 1;
  251. countRemovedSoFar += countToRemove;
  252. nextToRemoveStart = lines.length + 1;
  253. if (nextToRemoveIndex < toRemove.length - 1)
  254. nextToRemoveStart = toRemove[++nextToRemoveIndex];
  255. } else {
  256. layout.add(i);
  257. }
  258. }
  259. return LayoutResult(layout, countRemovedSoFar);
  260. }
  261. List<int> _reflowLargerGetLinesToRemove(int colsBefore, int colsAfter) {
  262. List<int> toRemove = List<int>.empty(growable: true);
  263. for (int y = 0; y < _buffer.lines.length - 1; y++) {
  264. // Check if this row is wrapped
  265. int i = y;
  266. BufferLine nextLine = _buffer.lines[++i];
  267. if (!nextLine.isWrapped) {
  268. continue;
  269. }
  270. // Check how many lines it's wrapped for
  271. List<BufferLine> wrappedLines = List<BufferLine>.empty(growable: true);
  272. wrappedLines.add(_buffer.lines[y]);
  273. while (i < _buffer.lines.length && nextLine.isWrapped) {
  274. wrappedLines.add(nextLine);
  275. nextLine = _buffer.lines[++i];
  276. }
  277. final bufferAbsoluteY = _buffer.cursorY + _buffer.scrollOffsetFromTop;
  278. // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped
  279. // lines with the cursor
  280. if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {
  281. y += wrappedLines.length - 1;
  282. continue;
  283. }
  284. // Copy buffer data to new locations
  285. int destLineIndex = 0;
  286. int destCol = _getWrappedLineTrimmedLengthRow(
  287. _buffer.lines, destLineIndex, colsBefore);
  288. int srcLineIndex = 1;
  289. int srcCol = 0;
  290. while (srcLineIndex < wrappedLines.length) {
  291. int srcTrimmedTineLength = _getWrappedLineTrimmedLengthRow(
  292. wrappedLines, srcLineIndex, colsBefore);
  293. int srcRemainingCells = srcTrimmedTineLength - srcCol;
  294. int destRemainingCells = colsAfter - destCol;
  295. int cellsToCopy = min(srcRemainingCells, destRemainingCells);
  296. wrappedLines[destLineIndex].copyCellsFrom(
  297. wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy);
  298. destCol += cellsToCopy;
  299. if (destCol == colsAfter) {
  300. destLineIndex++;
  301. destCol = 0;
  302. }
  303. srcCol += cellsToCopy;
  304. if (srcCol == srcTrimmedTineLength) {
  305. srcLineIndex++;
  306. srcCol = 0;
  307. }
  308. // Make sure the last cell isn't wide, if it is copy it to the current dest
  309. if (destCol == 0 && destLineIndex != 0) {
  310. if (wrappedLines[destLineIndex - 1].cellGetWidth(colsAfter - 1) ==
  311. 2) {
  312. wrappedLines[destLineIndex].copyCellsFrom(
  313. wrappedLines[destLineIndex - 1], colsAfter - 1, destCol++, 1);
  314. // Null out the end of the last row
  315. wrappedLines[destLineIndex - 1].erase(
  316. _buffer.terminal.cursor, colsAfter - 1, colsAfter, false);
  317. }
  318. }
  319. }
  320. // Clear out remaining cells or fragments could remain;
  321. wrappedLines[destLineIndex]
  322. .erase(_buffer.terminal.cursor, destCol, colsAfter, false);
  323. // Work backwards and remove any rows at the end that only contain null cells
  324. int countToRemove = 0;
  325. for (int ix = wrappedLines.length - 1; ix > 0; ix--) {
  326. if (ix > destLineIndex ||
  327. wrappedLines[ix].getTrimmedLength(colsBefore) == 0) {
  328. countToRemove++;
  329. } else {
  330. break;
  331. }
  332. }
  333. if (countToRemove > 0) {
  334. toRemove.add(y + wrappedLines.length - countToRemove); // index
  335. toRemove.add(countToRemove);
  336. }
  337. y += wrappedLines.length - 1;
  338. }
  339. return toRemove;
  340. }
  341. int _getWrappedLineTrimmedLengthRow(
  342. List<BufferLine> lines, int row, int cols) {
  343. return _getWrappedLineTrimmedLength(
  344. lines[row], row == lines.length - 1 ? null : lines[row + 1], cols);
  345. }
  346. int _getWrappedLineTrimmedLength(
  347. BufferLine line, BufferLine? nextLine, int cols) {
  348. // If this is the last row in the wrapped line, get the actual trimmed length
  349. if (nextLine == null) {
  350. return line.getTrimmedLength(cols);
  351. }
  352. // Detect whether the following line starts with a wide character and the end of the current line
  353. // is null, if so then we can be pretty sure the null character should be excluded from the line
  354. // length]
  355. bool endsInNull =
  356. !(line.cellHasContent(cols - 1)) && line.cellGetWidth(cols - 1) == 1;
  357. bool followingLineStartsWithWide = nextLine.cellGetWidth(0) == 2;
  358. if (endsInNull && followingLineStartsWithWide) {
  359. return cols - 1;
  360. }
  361. return cols;
  362. }
  363. }