buffer_reflow.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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();
  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();
  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]);
  114. }
  115. }
  116. // Adjust viewport as needed
  117. //TODO: probably nothing to do here because of the way the ViewPort is handled compared to the xterm.js project
  118. // int viewportAdjustments = linesToAdd;
  119. // while (viewportAdjustments-- > 0) {
  120. // if (Buffer.YBase == 0) {
  121. // if (Buffer.Y < newRows - 1) {
  122. // Buffer.Y++;
  123. // Buffer.Lines.Pop();
  124. // } else {
  125. // Buffer.YBase++;
  126. // Buffer.YDisp++;
  127. // }
  128. // } else {
  129. // // Ensure ybase does not exceed its maximum value
  130. // if (Buffer.YBase <
  131. // Math.Min(Buffer.Lines.MaxLength,
  132. // Buffer.Lines.Length + countToInsert) -
  133. // newRows) {
  134. // if (Buffer.YBase == Buffer.YDisp) {
  135. // Buffer.YDisp++;
  136. // }
  137. //
  138. // Buffer.YBase++;
  139. // }
  140. // }
  141. // }
  142. _buffer.adjustSavedCursor(0, linesToAdd);
  143. //TODO: maybe row count has to be handled here?
  144. }
  145. _rearrange(toInsert, countToInsert);
  146. }
  147. void _rearrange(List<InsertionSet> toInsert, int countToInsert) {
  148. // Rearrange lines in the buffer if there are any insertions, this is done at the end rather
  149. // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many
  150. // costly calls to CircularList.splice.
  151. if (toInsert.length > 0) {
  152. // Record buffer insert events and then play them back backwards so that the indexes are
  153. // correct
  154. List<int> insertEvents = [];
  155. // Record original lines so they don't get overridden when we rearrange the list
  156. List<BufferLine> originalLines = List<BufferLine>.from(_buffer.lines);
  157. _buffer.lines.addAll(List<BufferLine>.generate(countToInsert,
  158. (index) => BufferLine()));
  159. int originalLinesLength = originalLines.length;
  160. int originalLineIndex = originalLinesLength - 1;
  161. int nextToInsertIndex = 0;
  162. InsertionSet nextToInsert = toInsert[nextToInsertIndex];
  163. //TODO: remove rows that now are "too much"
  164. int countInsertedSoFar = 0;
  165. for (int i = originalLinesLength + countToInsert - 1; i >= 0; i--) {
  166. if (!nextToInsert.isNull &&
  167. nextToInsert.start != null &&
  168. nextToInsert.lines != null &&
  169. nextToInsert.start! > originalLineIndex + countInsertedSoFar) {
  170. // Insert extra lines here, adjusting i as needed
  171. for (int nextI = nextToInsert.lines!.length - 1;
  172. nextI >= 0;
  173. nextI--) {
  174. if (i < 0) {
  175. // if we reflow and the content has to be scrolled back past the beginning
  176. // of the buffer then we end up loosing those lines
  177. break;
  178. }
  179. _buffer.lines[i--] = nextToInsert.lines![nextI];
  180. }
  181. i++;
  182. countInsertedSoFar += nextToInsert.lines!.length;
  183. if (nextToInsertIndex < toInsert.length - 1) {
  184. nextToInsert = toInsert[++nextToInsertIndex];
  185. } else {
  186. nextToInsert = InsertionSet.nullValue; //TODO: just break?
  187. }
  188. } else {
  189. _buffer.lines[i] = originalLines[originalLineIndex--];
  190. }
  191. }
  192. }
  193. }
  194. /// <summary>
  195. /// Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-
  196. /// compute the wrapping points since wide characters may need to be wrapped onto the following line.
  197. /// This function will return an array of numbers of where each line wraps to, the resulting array
  198. /// will only contain the values `newCols` (when the line does not end with a wide character) and
  199. /// `newCols - 1` (when the line does end with a wide character), except for the last value which
  200. /// will contain the remaining items to fill the line.
  201. /// Calling this with a `newCols` value of `1` will lock up.
  202. /// </summary>
  203. List<int> _getNewLineLengths(
  204. List<BufferLine> wrappedLines, int oldCols, int newCols) {
  205. List<int> newLineLengths = [];
  206. int cellsNeeded = 0;
  207. for (int i = 0; i < wrappedLines.length; i++) {
  208. cellsNeeded += _getWrappedLineTrimmedLengthRow(wrappedLines, i, oldCols);
  209. }
  210. // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and
  211. // linesNeeded
  212. int srcCol = 0;
  213. int srcLine = 0;
  214. int cellsAvailable = 0;
  215. while (cellsAvailable < cellsNeeded) {
  216. if (cellsNeeded - cellsAvailable < newCols) {
  217. // Add the final line and exit the loop
  218. newLineLengths.add(cellsNeeded - cellsAvailable);
  219. break;
  220. }
  221. srcCol += newCols;
  222. int oldTrimmedLength =
  223. _getWrappedLineTrimmedLengthRow(wrappedLines, srcLine, oldCols);
  224. if (srcCol > oldTrimmedLength) {
  225. srcCol -= oldTrimmedLength;
  226. srcLine++;
  227. }
  228. bool endsWithWide = wrappedLines[srcLine].getWidthAt(srcCol - 1) == 2;
  229. if (endsWithWide) {
  230. srcCol--;
  231. }
  232. int lineLength = endsWithWide ? newCols - 1 : newCols;
  233. newLineLengths.add(lineLength);
  234. cellsAvailable += lineLength;
  235. }
  236. return newLineLengths;
  237. }
  238. void _reflowLargerAdjustViewport(
  239. int colsBefore, int colsAfter, int countRemoved) {
  240. // Adjust viewport based on number of items removed
  241. var viewportAdjustments = countRemoved;
  242. while (viewportAdjustments-- > 0) {
  243. //viewport is at the top
  244. if (_buffer.lines.length <= _buffer.terminal.viewHeight) {
  245. //cursor is not at the top
  246. if (_buffer.cursorY > 0) {
  247. _buffer.moveCursorY(-1);
  248. }
  249. //buffer doesn't have enough lines
  250. if (_buffer.lines.length < _buffer.terminal.viewHeight) {
  251. // Add an extra row at the bottom of the viewport
  252. _buffer.lines
  253. .add(BufferLine());
  254. }
  255. } else {
  256. //Nothing to do here due to the way scrolling is handled
  257. // //user didn't scroll
  258. // if (this.ydisp === this.ybase) {
  259. // //scroll viewport according to...
  260. // this.ydisp--;
  261. // }
  262. // //base window
  263. // this.ybase--;
  264. }
  265. }
  266. //TODO: adjust buffer content to max length
  267. _buffer.adjustSavedCursor(0, -countRemoved);
  268. }
  269. void _reflowLargerApplyNewLayout(List<int> newLayout) {
  270. var newLayoutLines = List<BufferLine>.generate(newLayout.length, (index) => _buffer.lines[newLayout[index]]);
  271. // Rearrange the list
  272. for (int i = 0; i < newLayoutLines.length; i++) {
  273. _buffer.lines[i] = newLayoutLines[i];
  274. }
  275. _buffer.lines.removeRange(newLayoutLines.length - 1, _buffer.lines.length - 1);
  276. }
  277. LayoutResult _reflowLargerCreateNewLayout(
  278. List<BufferLine> lines, List<int> toRemove) {
  279. var layout = List<int>.empty(growable: true);
  280. // First iterate through the list and get the actual indexes to use for rows
  281. int nextToRemoveIndex = 0;
  282. int nextToRemoveStart = toRemove[nextToRemoveIndex];
  283. int countRemovedSoFar = 0;
  284. for (int i = 0; i < lines.length; i++) {
  285. if (nextToRemoveStart == i) {
  286. int countToRemove = toRemove[++nextToRemoveIndex];
  287. // Tell markers that there was a deletion
  288. //lines.onDeleteEmitter.fire ({
  289. // index: i - countRemovedSoFar,
  290. // amount: countToRemove
  291. //});
  292. i += countToRemove - 1;
  293. countRemovedSoFar += countToRemove;
  294. nextToRemoveStart = lines.length + 1;
  295. if (nextToRemoveIndex < toRemove.length - 1)
  296. nextToRemoveStart = toRemove[++nextToRemoveIndex];
  297. } else {
  298. layout.add(i);
  299. }
  300. }
  301. return LayoutResult(layout, countRemovedSoFar);
  302. }
  303. List<int> _reflowLargerGetLinesToRemove(int colsBefore, int colsAfter) {
  304. List<int> toRemove = List<int>.empty(growable: true);
  305. for (int y = 0; y < _buffer.lines.length - 1; y++) {
  306. // Check if this row is wrapped
  307. int i = y;
  308. BufferLine nextLine = _buffer.lines[++i];
  309. if (!nextLine.isWrapped) {
  310. continue;
  311. }
  312. // Check how many lines it's wrapped for
  313. List<BufferLine> wrappedLines = List<BufferLine>.empty(growable: true);
  314. wrappedLines.add(_buffer.lines[y]);
  315. while (i < _buffer.lines.length && nextLine.isWrapped) {
  316. wrappedLines.add(nextLine);
  317. nextLine = _buffer.lines[++i];
  318. }
  319. final bufferAbsoluteY = _buffer.cursorY + _buffer.scrollOffsetFromTop;
  320. // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped
  321. // lines with the cursor
  322. if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {
  323. y += wrappedLines.length - 1;
  324. continue;
  325. }
  326. // Copy buffer data to new locations
  327. int destLineIndex = 0;
  328. int destCol = _getWrappedLineTrimmedLengthRow(
  329. _buffer.lines, destLineIndex, colsBefore);
  330. int srcLineIndex = 1;
  331. int srcCol = 0;
  332. while (srcLineIndex < wrappedLines.length) {
  333. int srcTrimmedTineLength = _getWrappedLineTrimmedLengthRow(
  334. wrappedLines, srcLineIndex, colsBefore);
  335. int srcRemainingCells = srcTrimmedTineLength - srcCol;
  336. int destRemainingCells = colsAfter - destCol;
  337. int cellsToCopy = min(srcRemainingCells, destRemainingCells);
  338. wrappedLines[destLineIndex].copyCellsFrom(
  339. wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy);
  340. destCol += cellsToCopy;
  341. if (destCol == colsAfter) {
  342. destLineIndex++;
  343. destCol = 0;
  344. }
  345. srcCol += cellsToCopy;
  346. if (srcCol == srcTrimmedTineLength) {
  347. srcLineIndex++;
  348. srcCol = 0;
  349. }
  350. // Make sure the last cell isn't wide, if it is copy it to the current dest
  351. if (destCol == 0 && destLineIndex != 0) {
  352. if (wrappedLines[destLineIndex - 1].getWidthAt(colsAfter - 1) == 2) {
  353. wrappedLines[destLineIndex].copyCellsFrom(
  354. wrappedLines[destLineIndex - 1], colsAfter - 1, destCol++, 1);
  355. // Null out the end of the last row
  356. wrappedLines[destLineIndex - 1]
  357. .erase(_buffer.terminal.cellAttr.value, colsAfter - 1, colsAfter, false);
  358. }
  359. }
  360. }
  361. // Clear out remaining cells or fragments could remain;
  362. wrappedLines[destLineIndex].erase(_buffer.terminal.cellAttr.value, destCol, colsAfter, false);
  363. // Work backwards and remove any rows at the end that only contain null cells
  364. int countToRemove = 0;
  365. for (int ix = wrappedLines.length - 1; ix > 0; ix--) {
  366. if (ix > destLineIndex || wrappedLines[ix].getTrimmedLength() == 0) {
  367. countToRemove++;
  368. } else {
  369. break;
  370. }
  371. }
  372. if (countToRemove > 0) {
  373. toRemove.add(y + wrappedLines.length - countToRemove); // index
  374. toRemove.add(countToRemove);
  375. }
  376. y += wrappedLines.length - 1;
  377. }
  378. return toRemove;
  379. }
  380. int _getWrappedLineTrimmedLengthRow(
  381. List<BufferLine> lines, int row, int cols) {
  382. return _getWrappedLineTrimmedLength(
  383. lines[row], row == lines.length - 1 ? null : lines[row + 1], cols);
  384. }
  385. int _getWrappedLineTrimmedLength(
  386. BufferLine line, BufferLine? nextLine, int cols) {
  387. // If this is the last row in the wrapped line, get the actual trimmed length
  388. if (nextLine == null) {
  389. return line.getTrimmedLength();
  390. }
  391. // Detect whether the following line starts with a wide character and the end of the current line
  392. // is null, if so then we can be pretty sure the null character should be excluded from the line
  393. // length]
  394. bool endsInNull =
  395. !(line.hasContentAt(cols - 1)) && line.getWidthAt(cols - 1) == 1;
  396. bool followingLineStartsWithWide = nextLine.getWidthAt(0) == 2;
  397. if (endsInNull && followingLineStartsWithWide) {
  398. return cols - 1;
  399. }
  400. return cols;
  401. }
  402. }