buffer.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import 'dart:math' show max, min;
  2. import 'package:xterm/src/core/buffer/cell_offset.dart';
  3. import 'package:xterm/src/core/buffer/line.dart';
  4. import 'package:xterm/src/core/buffer/range_line.dart';
  5. import 'package:xterm/src/core/buffer/range.dart';
  6. import 'package:xterm/src/core/charset.dart';
  7. import 'package:xterm/src/core/cursor.dart';
  8. import 'package:xterm/src/core/reflow.dart';
  9. import 'package:xterm/src/core/state.dart';
  10. import 'package:xterm/src/utils/circular_buffer.dart';
  11. import 'package:xterm/src/utils/unicode_v11.dart';
  12. class Buffer {
  13. final TerminalState terminal;
  14. final int maxLines;
  15. final bool isAltBuffer;
  16. /// Characters that break selection when calling [getWordBoundary]. If null,
  17. /// defaults to [defaultWordSeparators].
  18. final Set<int>? wordSeparators;
  19. Buffer(
  20. this.terminal, {
  21. required this.maxLines,
  22. required this.isAltBuffer,
  23. this.wordSeparators,
  24. }) {
  25. for (int i = 0; i < terminal.viewHeight; i++) {
  26. lines.push(_newEmptyLine());
  27. }
  28. resetVerticalMargins();
  29. }
  30. int _cursorX = 0;
  31. int _cursorY = 0;
  32. late int _marginTop;
  33. late int _marginBottom;
  34. var _savedCursorX = 0;
  35. var _savedCursorY = 0;
  36. final _savedCursorStyle = CursorStyle();
  37. final charset = Charset();
  38. /// Width of the viewport in columns. Also the index of the last column.
  39. int get viewWidth => terminal.viewWidth;
  40. /// Height of the viewport in rows. Also the index of the last line.
  41. int get viewHeight => terminal.viewHeight;
  42. /// lines of the buffer. the length of [lines] should always be equal or
  43. /// greater than [viewHeight].
  44. late final lines = IndexAwareCircularBuffer<BufferLine>(maxLines);
  45. /// Total number of lines in the buffer. Always equal or greater than
  46. /// [viewHeight].
  47. int get height => lines.length;
  48. /// Horizontal position of the cursor relative to the top-left cornor of the
  49. /// screen, starting from 0.
  50. int get cursorX => _cursorX.clamp(0, terminal.viewWidth - 1);
  51. /// Vertical position of the cursor relative to the top-left cornor of the
  52. /// screen, starting from 0.
  53. int get cursorY => _cursorY;
  54. /// Index of the first line in the scroll region.
  55. int get marginTop => _marginTop;
  56. /// Index of the last line in the scroll region.
  57. int get marginBottom => _marginBottom;
  58. /// The number of lines above the viewport.
  59. int get scrollBack => height - viewHeight;
  60. /// Vertical position of the cursor relative to the top of the buffer,
  61. /// starting from 0.
  62. int get absoluteCursorY => _cursorY + scrollBack;
  63. /// Absolute index of the first line in the scroll region.
  64. int get absoluteMarginTop => _marginTop + scrollBack;
  65. /// Absolute index of the last line in the scroll region.
  66. int get absoluteMarginBottom => _marginBottom + scrollBack;
  67. /// Writes data to the _terminal. Terminal sequences or special characters are
  68. /// not interpreted and directly added to the buffer.
  69. ///
  70. /// See also: [Terminal.write]
  71. void write(String text) {
  72. for (var char in text.runes) {
  73. writeChar(char);
  74. }
  75. }
  76. /// Writes a single character to the _terminal. Escape sequences or special
  77. /// characters are not interpreted and directly added to the buffer.
  78. ///
  79. /// See also: [Terminal.writeChar]
  80. void writeChar(int codePoint) {
  81. codePoint = charset.translate(codePoint);
  82. final cellWidth = unicodeV11.wcwidth(codePoint);
  83. if (_cursorX >= terminal.viewWidth) {
  84. index();
  85. setCursorX(0);
  86. if (terminal.autoWrapMode) {
  87. currentLine.isWrapped = true;
  88. }
  89. }
  90. final line = currentLine;
  91. line.setCell(_cursorX, codePoint, cellWidth, terminal.cursor);
  92. if (_cursorX < viewWidth) {
  93. _cursorX++;
  94. }
  95. if (cellWidth == 2) {
  96. writeChar(0);
  97. }
  98. }
  99. /// The line at the current cursor position.
  100. BufferLine get currentLine {
  101. return lines[absoluteCursorY];
  102. }
  103. void backspace() {
  104. if (_cursorX == 0 && currentLine.isWrapped) {
  105. currentLine.isWrapped = false;
  106. moveCursor(viewWidth - 1, -1);
  107. } else if (_cursorX == viewWidth) {
  108. moveCursor(-2, 0);
  109. } else {
  110. moveCursor(-1, 0);
  111. }
  112. }
  113. /// Erases the viewport from the cursor position to the end of the buffer,
  114. /// including the cursor position.
  115. void eraseDisplayFromCursor() {
  116. eraseLineFromCursor();
  117. for (var i = absoluteCursorY + 1; i < height; i++) {
  118. final line = lines[i];
  119. line.isWrapped = false;
  120. line.eraseRange(0, viewWidth, terminal.cursor);
  121. }
  122. }
  123. /// Erases the viewport from the top-left corner to the cursor, including the
  124. /// cursor.
  125. void eraseDisplayToCursor() {
  126. eraseLineToCursor();
  127. for (var i = 0; i < _cursorY; i++) {
  128. final line = lines[i + scrollBack];
  129. line.isWrapped = false;
  130. line.eraseRange(0, viewWidth, terminal.cursor);
  131. }
  132. }
  133. /// Erases the whole viewport.
  134. void eraseDisplay() {
  135. for (var i = 0; i < viewHeight; i++) {
  136. final line = lines[i + scrollBack];
  137. line.isWrapped = false;
  138. line.eraseRange(0, viewWidth, terminal.cursor);
  139. }
  140. }
  141. /// Erases the line from the cursor to the end of the line, including the
  142. /// cursor position.
  143. void eraseLineFromCursor() {
  144. currentLine.isWrapped = false;
  145. currentLine.eraseRange(_cursorX, viewWidth, terminal.cursor);
  146. }
  147. /// Erases the line from the start of the line to the cursor, including the
  148. /// cursor.
  149. void eraseLineToCursor() {
  150. currentLine.isWrapped = false;
  151. currentLine.eraseRange(0, _cursorX, terminal.cursor);
  152. }
  153. /// Erases the line at the current cursor position.
  154. void eraseLine() {
  155. currentLine.isWrapped = false;
  156. currentLine.eraseRange(0, viewWidth, terminal.cursor);
  157. }
  158. /// Erases [count] cells starting at the cursor position.
  159. void eraseChars(int count) {
  160. final start = _cursorX;
  161. currentLine.eraseRange(start, start + count, terminal.cursor);
  162. }
  163. void scrollDown(int lines) {
  164. for (var i = absoluteMarginBottom; i >= absoluteMarginTop; i--) {
  165. if (i >= absoluteMarginTop + lines) {
  166. this.lines[i] = this.lines[i - lines];
  167. } else {
  168. this.lines[i] = _newEmptyLine();
  169. }
  170. }
  171. }
  172. void scrollUp(int lines) {
  173. for (var i = absoluteMarginTop; i <= absoluteMarginBottom; i++) {
  174. if (i <= absoluteMarginBottom - lines) {
  175. this.lines[i] = this.lines[i + lines];
  176. } else {
  177. this.lines[i] = _newEmptyLine();
  178. }
  179. }
  180. }
  181. /// https://vt100.net/docs/vt100-ug/chapter3.html#IND IND – Index
  182. ///
  183. /// ESC D
  184. ///
  185. /// [index] causes the active position to move downward one line without
  186. /// changing the column position. If the active position is at the bottom
  187. /// margin, a scroll up is performed.
  188. void index() {
  189. if (isInVerticalMargin) {
  190. if (_cursorY == _marginBottom) {
  191. if (marginTop == 0 && !isAltBuffer) {
  192. lines.insert(absoluteMarginBottom + 1, _newEmptyLine());
  193. } else {
  194. scrollUp(1);
  195. }
  196. } else {
  197. moveCursorY(1);
  198. }
  199. return;
  200. }
  201. // the cursor is not in the scrollable region
  202. if (_cursorY >= viewHeight - 1) {
  203. // we are at the bottom
  204. if (isAltBuffer) {
  205. scrollUp(1);
  206. } else {
  207. lines.push(_newEmptyLine());
  208. }
  209. } else {
  210. // there're still lines so we simply move cursor down.
  211. moveCursorY(1);
  212. }
  213. }
  214. void lineFeed() {
  215. index();
  216. if (terminal.lineFeedMode) {
  217. setCursorX(0);
  218. }
  219. }
  220. /// https://terminalguide.namepad.de/seq/a_esc_cm/
  221. void reverseIndex() {
  222. if (isInVerticalMargin) {
  223. if (_cursorY == _marginTop) {
  224. scrollDown(1);
  225. } else {
  226. moveCursorY(-1);
  227. }
  228. } else {
  229. moveCursorY(-1);
  230. }
  231. }
  232. void cursorGoForward() {
  233. _cursorX = min(_cursorX + 1, viewWidth);
  234. }
  235. void setCursorX(int cursorX) {
  236. _cursorX = cursorX.clamp(0, viewWidth - 1);
  237. }
  238. void setCursorY(int cursorY) {
  239. _cursorY = cursorY.clamp(0, viewHeight - 1);
  240. }
  241. void moveCursorX(int offset) {
  242. setCursorX(_cursorX + offset);
  243. }
  244. void moveCursorY(int offset) {
  245. setCursorY(_cursorY + offset);
  246. }
  247. void setCursor(int cursorX, int cursorY) {
  248. var maxCursorY = viewHeight - 1;
  249. if (terminal.originMode) {
  250. cursorY += _marginTop;
  251. maxCursorY = _marginBottom;
  252. }
  253. _cursorX = cursorX.clamp(0, viewWidth - 1);
  254. _cursorY = cursorY.clamp(0, maxCursorY);
  255. }
  256. void moveCursor(int offsetX, int offsetY) {
  257. final cursorX = _cursorX + offsetX;
  258. final cursorY = _cursorY + offsetY;
  259. setCursor(cursorX, cursorY);
  260. }
  261. /// Save cursor position, charmap and text attributes.
  262. void saveCursor() {
  263. _savedCursorX = _cursorX;
  264. _savedCursorY = _cursorY;
  265. _savedCursorStyle.foreground = terminal.cursor.foreground;
  266. _savedCursorStyle.background = terminal.cursor.background;
  267. _savedCursorStyle.attrs = terminal.cursor.attrs;
  268. charset.save();
  269. }
  270. /// Restore cursor position, charmap and text attributes.
  271. void restoreCursor() {
  272. _cursorX = _savedCursorX;
  273. _cursorY = _savedCursorY;
  274. terminal.cursor.foreground = _savedCursorStyle.foreground;
  275. terminal.cursor.background = _savedCursorStyle.background;
  276. terminal.cursor.attrs = _savedCursorStyle.attrs;
  277. charset.restore();
  278. }
  279. /// Sets the vertical scrolling margin to [top] and [bottom].
  280. /// Both values must be between 0 and [viewHeight] - 1.
  281. void setVerticalMargins(int top, int bottom) {
  282. _marginTop = top.clamp(0, viewHeight - 1);
  283. _marginBottom = bottom.clamp(0, viewHeight - 1);
  284. _marginTop = min(_marginTop, _marginBottom);
  285. _marginBottom = max(_marginTop, _marginBottom);
  286. }
  287. bool get isInVerticalMargin {
  288. return _cursorY >= _marginTop && _cursorY <= _marginBottom;
  289. }
  290. void resetVerticalMargins() {
  291. setVerticalMargins(0, viewHeight - 1);
  292. }
  293. void deleteChars(int count) {
  294. final start = _cursorX.clamp(0, viewWidth);
  295. count = min(count, viewWidth - start);
  296. currentLine.removeCells(start, count, terminal.cursor);
  297. }
  298. /// Remove all lines above the top of the viewport.
  299. void clearScrollback() {
  300. if (height <= viewHeight) {
  301. return;
  302. }
  303. lines.trimStart(scrollBack);
  304. }
  305. /// Clears the viewport and scrollback buffer. Then fill with empty lines.
  306. void clear() {
  307. lines.clear();
  308. for (int i = 0; i < viewHeight; i++) {
  309. lines.push(_newEmptyLine());
  310. }
  311. }
  312. void insertBlankChars(int count) {
  313. currentLine.insertCells(_cursorX, count, terminal.cursor);
  314. }
  315. void insertLines(int count) {
  316. if (!isInVerticalMargin) {
  317. return;
  318. }
  319. setCursorX(0);
  320. // Number of lines from the cursor to the bottom of the scrollable region
  321. // including the cursor itself.
  322. final linesBelow = absoluteMarginBottom - absoluteCursorY + 1;
  323. // Number of empty lines to insert.
  324. final linesToInsert = min(count, linesBelow);
  325. // Number of lines to move up.
  326. final linesToMove = linesBelow - linesToInsert;
  327. for (var i = 0; i < linesToMove; i++) {
  328. final index = absoluteMarginBottom - i;
  329. lines[index] = lines.swap(index - linesToInsert, _newEmptyLine());
  330. }
  331. for (var i = linesToMove; i < linesToInsert; i++) {
  332. lines[absoluteCursorY + i] = _newEmptyLine();
  333. }
  334. }
  335. /// Remove [count] lines starting at the current cursor position. Lines below
  336. /// the removed lines are shifted up. This only affects the scrollable region.
  337. /// Lines outside the scrollable region are not affected.
  338. void deleteLines(int count) {
  339. if (!isInVerticalMargin) {
  340. return;
  341. }
  342. setCursorX(0);
  343. count = min(count, absoluteMarginBottom - absoluteCursorY + 1);
  344. final linesToMove = absoluteMarginBottom - absoluteCursorY + 1 - count;
  345. for (var i = 0; i < linesToMove; i++) {
  346. final index = absoluteCursorY + i;
  347. lines[index] = lines[index + count];
  348. }
  349. for (var i = 0; i < count; i++) {
  350. lines[absoluteMarginBottom - i] = _newEmptyLine();
  351. }
  352. }
  353. void resize(int oldWidth, int oldHeight, int newWidth, int newHeight) {
  354. // 1. Adjust the height.
  355. if (newHeight > oldHeight) {
  356. // Grow larger
  357. for (var i = 0; i < newHeight - oldHeight; i++) {
  358. if (newHeight > lines.length) {
  359. lines.push(_newEmptyLine(newWidth));
  360. } else {
  361. _cursorY++;
  362. }
  363. }
  364. } else {
  365. // Shrink smaller
  366. for (var i = 0; i < oldHeight - newHeight; i++) {
  367. if (_cursorY > newHeight - 1) {
  368. _cursorY--;
  369. } else {
  370. lines.pop();
  371. }
  372. }
  373. }
  374. // Ensure cursor is within the screen.
  375. _cursorX = _cursorX.clamp(0, newWidth - 1);
  376. _cursorY = _cursorY.clamp(0, newHeight - 1);
  377. // 2. Adjust the width.
  378. if (newWidth != oldWidth) {
  379. if (terminal.reflowEnabled && !isAltBuffer) {
  380. final reflowResult = reflow(lines, oldWidth, newWidth);
  381. while (reflowResult.length < newHeight) {
  382. reflowResult.add(_newEmptyLine(newWidth));
  383. }
  384. lines.replaceWith(reflowResult);
  385. } else {
  386. lines.forEach((item) => item.resize(newWidth));
  387. }
  388. }
  389. }
  390. /// Create a new [CellAnchor] at the specified [x] and [y] coordinates.
  391. CellAnchor createAnchor(int x, int y) {
  392. return lines[y].createAnchor(x);
  393. }
  394. /// Create a new [CellAnchor] at the specified [x] and [y] coordinates.
  395. CellAnchor createAnchorFromOffset(CellOffset offset) {
  396. return lines[offset.y].createAnchor(offset.x);
  397. }
  398. CellAnchor createAnchorFromCursor() {
  399. return createAnchor(cursorX, absoluteCursorY);
  400. }
  401. /// Create a new empty [BufferLine] with the current [viewWidth] if [width]
  402. /// is not specified.
  403. BufferLine _newEmptyLine([int? width]) {
  404. final line = BufferLine(width ?? viewWidth);
  405. return line;
  406. }
  407. static final defaultWordSeparators = <int>{
  408. 0,
  409. r' '.codeUnitAt(0),
  410. r'.'.codeUnitAt(0),
  411. r':'.codeUnitAt(0),
  412. r'-'.codeUnitAt(0),
  413. r'\'.codeUnitAt(0),
  414. r'"'.codeUnitAt(0),
  415. r'*'.codeUnitAt(0),
  416. r'+'.codeUnitAt(0),
  417. r'/'.codeUnitAt(0),
  418. r'\'.codeUnitAt(0),
  419. };
  420. BufferRangeLine? getWordBoundary(CellOffset position) {
  421. var separators = wordSeparators ?? defaultWordSeparators;
  422. if (position.y >= lines.length) {
  423. return null;
  424. }
  425. var line = lines[position.y];
  426. var start = position.x;
  427. var end = position.x;
  428. do {
  429. if (start == 0) {
  430. break;
  431. }
  432. final char = line.getCodePoint(start - 1);
  433. if (separators.contains(char)) {
  434. break;
  435. }
  436. start--;
  437. } while (true);
  438. do {
  439. if (end >= viewWidth) {
  440. break;
  441. }
  442. final char = line.getCodePoint(end);
  443. if (separators.contains(char)) {
  444. break;
  445. }
  446. end++;
  447. } while (true);
  448. if (start == end) {
  449. return null;
  450. }
  451. return BufferRangeLine(
  452. CellOffset(start, position.y),
  453. CellOffset(end, position.y),
  454. );
  455. }
  456. /// Get the plain text content of the buffer including the scrollback.
  457. /// Accepts an optional [range] to get a specific part of the buffer.
  458. String getText([BufferRange? range]) {
  459. range ??= BufferRangeLine(
  460. CellOffset(0, 0),
  461. CellOffset(viewWidth - 1, height - 1),
  462. );
  463. range = range.normalized;
  464. final builder = StringBuffer();
  465. for (var segment in range.toSegments()) {
  466. if (segment.line < 0 || segment.line >= height) {
  467. continue;
  468. }
  469. final line = lines[segment.line];
  470. if (!(segment.line == range.begin.y ||
  471. segment.line == 0 ||
  472. line.isWrapped)) {
  473. builder.write("\n");
  474. }
  475. builder.write(line.getText(segment.start, segment.end));
  476. }
  477. return builder.toString();
  478. }
  479. /// Returns a debug representation of the buffer.
  480. @override
  481. String toString() {
  482. final builder = StringBuffer();
  483. final lineNumberLength = lines.length.toString().length;
  484. for (var i = 0; i < lines.length; i++) {
  485. final line = lines[i];
  486. builder.write('${i.toString().padLeft(lineNumberLength)}: |${lines[i]}|');
  487. if (line.isWrapped) {
  488. builder.write(' (⏎)');
  489. }
  490. builder.write('\n');
  491. }
  492. return builder.toString();
  493. }
  494. }