terminal.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import 'dart:async';
  2. import 'dart:collection';
  3. import 'dart:math' show max, min;
  4. import 'package:xterm/buffer/buffer.dart';
  5. import 'package:xterm/buffer/line/line.dart';
  6. import 'package:xterm/input/keys.dart';
  7. import 'package:xterm/input/keytab/keytab.dart';
  8. import 'package:xterm/input/keytab/keytab_escape.dart';
  9. import 'package:xterm/input/keytab/keytab_record.dart';
  10. import 'package:xterm/mouse/mouse_mode.dart';
  11. import 'package:xterm/mouse/position.dart';
  12. import 'package:xterm/mouse/selection.dart';
  13. import 'package:xterm/terminal/ansi.dart';
  14. import 'package:xterm/terminal/cursor.dart';
  15. import 'package:xterm/terminal/platform.dart';
  16. import 'package:xterm/terminal/sbc.dart';
  17. import 'package:xterm/terminal/tabs.dart';
  18. import 'package:xterm/terminal/terminal_backend.dart';
  19. import 'package:xterm/terminal/terminal_ui_interaction.dart';
  20. import 'package:xterm/theme/terminal_color.dart';
  21. import 'package:xterm/theme/terminal_theme.dart';
  22. import 'package:xterm/theme/terminal_themes.dart';
  23. import 'package:xterm/util/debug_handler.dart';
  24. import 'package:xterm/util/observable.dart';
  25. typedef TerminalInputHandler = void Function(String);
  26. typedef BellHandler = void Function();
  27. typedef TitleChangeHandler = void Function(String);
  28. typedef IconChangeHandler = void Function(String);
  29. void _defaultBellHandler() {}
  30. void _defaultTitleHandler(String _) {}
  31. void _defaultIconHandler(String _) {}
  32. class Terminal with Observable implements TerminalUiInteraction {
  33. Terminal({
  34. this.backend,
  35. this.onBell = _defaultBellHandler,
  36. this.onTitleChange = _defaultTitleHandler,
  37. this.onIconChange = _defaultIconHandler,
  38. this.platform = PlatformBehaviors.unix,
  39. this.theme = TerminalThemes.defaultTheme,
  40. required int maxLines,
  41. }) : _maxLines = maxLines {
  42. backend?.init();
  43. backend?.exitCode.then((value) {
  44. _isTerminated = true;
  45. _backendExited.complete(value);
  46. });
  47. backend?.out.listen(write);
  48. _mainBuffer = Buffer(terminal: this, isAltBuffer: false);
  49. _altBuffer = Buffer(terminal: this, isAltBuffer: true);
  50. _buffer = _mainBuffer;
  51. cursor = Cursor(
  52. fg: theme.foreground,
  53. bg: TerminalColor.transparent, // transparent
  54. flags: 0x00, // no flags
  55. );
  56. tabs.reset();
  57. }
  58. bool _dirty = false;
  59. @override
  60. bool get dirty {
  61. if (_dirty) {
  62. _dirty = false;
  63. return true;
  64. } else {
  65. return false;
  66. }
  67. }
  68. int _maxLines;
  69. int get maxLines {
  70. return max(viewHeight, _maxLines);
  71. }
  72. int _viewWidth = 80;
  73. int _viewHeight = 25;
  74. int get viewWidth => _viewWidth;
  75. int get viewHeight => _viewHeight;
  76. int get visibleHeight => min(_viewHeight, buffer.height);
  77. @override
  78. int get invisibleHeight => buffer.height - visibleHeight;
  79. /// ### Insert/Replace Mode (IRM)
  80. ///
  81. /// The terminal displays received characters at the cursor position.
  82. /// Insert/Replace mode determines how the terminal adds characters to the
  83. /// screen. Insert mode displays the new character and moves previously
  84. /// displayed characters to the right. Replace mode adds characters by
  85. /// replacing the character at the cursor position.
  86. ///
  87. /// You can set or reset insert/replace mode as follows.
  88. bool _replaceMode = true; // ignore: unused_field
  89. bool _screenMode = false; // ignore: unused_field, // DECSCNM (black on white background)
  90. bool _autoWrapMode = true;
  91. bool get autoWrapMode => _autoWrapMode;
  92. /// ### DECOM – Origin Mode (DEC Private)
  93. ///
  94. /// This is a private parameter applicable to set mode (SM) and reset mode
  95. /// (RM) control sequences. The reset state causes the origin to be at the
  96. /// upper-left character position on the screen. Line and column numbers are,
  97. /// therefore, independent of current margin settings. The cursor may be
  98. /// positioned outside the margins with a cursor position (CUP) or horizontal
  99. /// and vertical position (HVP) control.
  100. ///
  101. /// The set state causes the origin to be at the upper-left character position
  102. /// within the margins. Line and column numbers are therefore relative to the
  103. /// current margin settings. The cursor is not allowed to be positioned
  104. /// outside the margins.
  105. ///
  106. /// The cursor is moved to the new home position when this mode is set or
  107. /// reset.
  108. ///
  109. /// Lines and columns are numbered consecutively, with the origin being line
  110. /// 1, column 1.
  111. bool get originMode => _originMode;
  112. bool _originMode = false;
  113. /// ### LNM – Line Feed/New Line Mode
  114. ///
  115. /// This is a parameter applicable to set mode (SM) and reset mode (RM)
  116. /// control sequences. The reset state causes the interpretation of the line
  117. /// feed (LF), defined in ANSI Standard X3.4-1977, to imply only vertical
  118. /// movement of the active position and causes the RETURN key (CR) to send the
  119. /// single code CR. The set state causes the LF to imply movement to the first
  120. /// position of the following line and causes the RETURN key to send the two
  121. /// codes (CR, LF). This is the New Line (NL) option.
  122. ///
  123. /// This mode does not affect the index (IND), or next line (NEL) format
  124. /// effectors.
  125. bool get lineFeedMode => _lineFeedMode;
  126. bool _lineFeedMode = true;
  127. /// See: [lineFeedMode]
  128. bool get newLineMode => !_lineFeedMode;
  129. /// ### Bracketed Paste Mode
  130. ///
  131. /// When bracketed paste mode is set, pasted text is bracketed with control
  132. /// sequences so that the program can differentiate pasted text from typed-in
  133. /// text. When bracketed paste mode is set, the program will receive: `ESC
  134. /// [200 ~`, followed by the pasted text, followed by `ESC [ 201 ~`.
  135. bool get bracketedPasteMode => _bracketedPasteMode;
  136. bool _bracketedPasteMode = false;
  137. bool _showCursor = true;
  138. @override
  139. bool get showCursor => _showCursor;
  140. /// DECCKM – Cursor Keys Mode (DEC Private)
  141. ///
  142. /// This is a private parameter applicable to set mode (SM) and reset mode
  143. /// (RM) control sequences. This mode is only effective when the terminal is
  144. /// in keypad application mode (see DECKPAM) and the ANSI/VT52 mode (DECANM)
  145. /// is set (see DECANM). Under these conditions, if the cursor key mode is
  146. /// reset, the four cursor function keys will send ANSI cursor control
  147. /// commands. If cursor key mode is set, the four cursor function keys will
  148. /// send application functions.
  149. bool get applicationCursorKeys => _applicationCursorKeys;
  150. bool _applicationCursorKeys = false;
  151. bool _blinkingCursor = true;
  152. bool get blinkingCursor => _blinkingCursor;
  153. late Buffer _buffer;
  154. late Buffer _mainBuffer;
  155. late Buffer _altBuffer;
  156. /// Queue of input characters. addLast() to add, removeFirst() to consume.
  157. final _queue = ListQueue<int>(81920);
  158. bool _slowMotion = false;
  159. bool get slowMotion => _slowMotion;
  160. MouseMode _mouseMode = MouseMode.none;
  161. MouseMode get mouseMode => _mouseMode;
  162. final TerminalTheme theme;
  163. // final cellAttr = CellAttrTemplate();
  164. late final Cursor cursor;
  165. final keytab = Keytab.defaultKeytab();
  166. final _selection = Selection();
  167. final tabs = Tabs();
  168. final debug = DebugHandler();
  169. final TerminalBackend? backend;
  170. final BellHandler onBell;
  171. final TitleChangeHandler onTitleChange;
  172. final IconChangeHandler onIconChange;
  173. @override
  174. final PlatformBehavior platform;
  175. Buffer get buffer {
  176. return _buffer;
  177. }
  178. @override
  179. int get cursorX => buffer.cursorX;
  180. @override
  181. int get cursorY => buffer.cursorY;
  182. @override
  183. void setScrollOffsetFromBottom(int scrollOffset) {
  184. final oldOffset = _buffer.scrollOffsetFromBottom;
  185. _buffer.setScrollOffsetFromBottom(scrollOffset);
  186. if (oldOffset != scrollOffset) {
  187. _dirty = true;
  188. refresh();
  189. }
  190. }
  191. /// Writes data to the terminal. Terminal sequences and special characters are
  192. /// interpreted.
  193. ///
  194. /// See also: [Buffer.write]
  195. @override
  196. void write(String text) {
  197. _queue.addAll(text.runes);
  198. _processInput();
  199. backend?.ackProcessed();
  200. refresh();
  201. }
  202. /// Writes data to the terminal. Special characters are interpreted.
  203. ///
  204. /// See also: [Buffer.writeChar]
  205. void writeChar(int codePoint) {
  206. _queue.addLast(codePoint);
  207. _processInput();
  208. refresh();
  209. }
  210. @override
  211. List<BufferLine> getVisibleLines() {
  212. return _buffer.getVisibleLines();
  213. }
  214. void _processInput() {
  215. while (_queue.isNotEmpty) {
  216. // if (_slowMotion) {
  217. // await Future.delayed(Duration(milliseconds: 100));
  218. // }
  219. const esc = 0x1b;
  220. final char = _queue.removeFirst();
  221. if (char == esc) {
  222. final finished = ansiHandler(_queue, this);
  223. // Terminal sequence in the queue is not completed, and no charater is
  224. // consumed.
  225. if (!finished) {
  226. _queue.addFirst(esc);
  227. break;
  228. }
  229. continue;
  230. }
  231. _processChar(char);
  232. }
  233. }
  234. void _processChar(int codePoint) {
  235. // If the character doesn't have special effect. Write it directly to the
  236. // buffer.
  237. if (codePoint > sbcMaxCodePoint) {
  238. debug.onChar(codePoint);
  239. _buffer.writeChar(codePoint);
  240. return;
  241. }
  242. // The character may have special effect.
  243. final sbcHandler = sbcHandlers[codePoint];
  244. if (sbcHandler != null) {
  245. debug.onSbc(codePoint);
  246. sbcHandler(codePoint, this);
  247. }
  248. }
  249. @override
  250. void refresh() {
  251. _dirty = true;
  252. notifyListeners();
  253. }
  254. void setSlowMotion(bool enabled) {
  255. _slowMotion = enabled;
  256. }
  257. void setOriginMode(bool enabled) {
  258. _originMode = enabled;
  259. buffer.setPosition(0, 0);
  260. }
  261. void setScreenMode(bool enabled) {
  262. _screenMode = true;
  263. }
  264. void setApplicationCursorKeys(bool enabled) {
  265. _applicationCursorKeys = enabled;
  266. }
  267. void setShowCursor(bool showCursor) {
  268. _showCursor = showCursor;
  269. }
  270. void setBlinkingCursor(bool enabled) {
  271. _blinkingCursor = enabled;
  272. }
  273. void setAutoWrapMode(bool enabled) {
  274. _autoWrapMode = enabled;
  275. }
  276. void setBracketedPasteMode(bool enabled) {
  277. _bracketedPasteMode = enabled;
  278. }
  279. void setInsertMode() {
  280. _replaceMode = false;
  281. }
  282. void setReplaceMode() {
  283. _replaceMode = true;
  284. }
  285. void setNewLineMode() {
  286. _lineFeedMode = false;
  287. }
  288. void setLineFeedMode() {
  289. _lineFeedMode = true;
  290. }
  291. void setMouseMode(MouseMode mode) {
  292. _mouseMode = mode;
  293. }
  294. void useMainBuffer() {
  295. _buffer = _mainBuffer;
  296. }
  297. void useAltBuffer() {
  298. _buffer = _altBuffer;
  299. }
  300. bool isUsingMainBuffer() {
  301. return _buffer == _mainBuffer;
  302. }
  303. bool isUsingAltBuffer() {
  304. return _buffer == _altBuffer;
  305. }
  306. /// Resize the terminal screen. [newWidth] and [newHeight] should be greater
  307. /// than 0. Text reflow is currently not implemented and will be avaliable in
  308. /// the future.
  309. @override
  310. void resize(
  311. int newWidth, int newHeight, int newPixelWidth, int newPixelHeight) {
  312. backend?.resize(newWidth, newHeight, newPixelWidth, newPixelHeight);
  313. newWidth = max(newWidth, 1);
  314. newHeight = max(newHeight, 1);
  315. final oldWidth = _viewWidth;
  316. final oldHeight = _viewHeight;
  317. _viewWidth = newWidth;
  318. _viewHeight = newHeight;
  319. //we need to resize both buffers so that they are ready when we switch between them
  320. _altBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  321. _mainBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  322. // maybe reflow should happen here.
  323. if (buffer == _altBuffer) {
  324. buffer.clearScrollback();
  325. }
  326. buffer.resetVerticalMargins();
  327. }
  328. @override
  329. void keyInput(
  330. TerminalKey key, {
  331. bool ctrl = false,
  332. bool alt = false,
  333. bool shift = false,
  334. bool mac = false,
  335. // bool meta,
  336. }) {
  337. debug.onMsg(key);
  338. for (var record in keytab.records) {
  339. if (record.key != key) {
  340. continue;
  341. }
  342. if (record.ctrl != null && record.ctrl != ctrl) {
  343. continue;
  344. }
  345. if (record.shift != null && record.shift != shift) {
  346. continue;
  347. }
  348. if (record.alt != null && record.alt != alt) {
  349. continue;
  350. }
  351. if (record.anyModifier == true &&
  352. (ctrl != true && alt != true && shift != true)) {
  353. continue;
  354. }
  355. if (record.anyModifier == false &&
  356. !(ctrl != true && alt != true && shift != true)) {
  357. continue;
  358. }
  359. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  360. continue;
  361. }
  362. if (record.newLine != null && record.newLine != newLineMode) {
  363. continue;
  364. }
  365. if (record.appCursorKeys != null &&
  366. record.appCursorKeys != applicationCursorKeys) {
  367. continue;
  368. }
  369. if (record.mac != null && record.mac != mac) {
  370. continue;
  371. }
  372. // TODO: support VT52
  373. if (record.ansi == false) {
  374. continue;
  375. }
  376. if (record.action.type == KeytabActionType.input) {
  377. debug.onMsg('input: ${record.action.value}');
  378. final input = keytabUnescape(record.action.value);
  379. backend?.write(input);
  380. return;
  381. }
  382. }
  383. if (ctrl) {
  384. if (key.index >= TerminalKey.keyA.index &&
  385. key.index <= TerminalKey.keyZ.index) {
  386. final input = key.index - TerminalKey.keyA.index + 1;
  387. backend?.write(String.fromCharCode(input));
  388. return;
  389. }
  390. }
  391. if (alt) {
  392. if (key.index >= TerminalKey.keyA.index &&
  393. key.index <= TerminalKey.keyZ.index) {
  394. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  395. backend?.write(String.fromCharCodes(input));
  396. return;
  397. }
  398. }
  399. }
  400. final wordSeparatorCodes = <String>[
  401. String.fromCharCode(0),
  402. ' ',
  403. '.',
  404. ':',
  405. '/'
  406. ];
  407. void selectWordOrRow(Position position) {
  408. if (position.y > buffer.lines.length) {
  409. return;
  410. }
  411. final row = position.y;
  412. final line = buffer.lines[row];
  413. final positionIsInSelection = _selection.contains(position);
  414. final completeLineIsSelected =
  415. _selection.start?.x == 0 && _selection.end?.x == terminalWidth;
  416. if (positionIsInSelection && !completeLineIsSelected) {
  417. // select area on an already existing selection extends it to the full line
  418. _selection.clear();
  419. _selection.init(Position(0, row));
  420. _selection.update(Position(terminalWidth, row));
  421. } else {
  422. // select the word that is under position
  423. var start = position.x;
  424. var end = position.x;
  425. do {
  426. if (start == 0) {
  427. break;
  428. }
  429. final content = line.cellGetContent(start - 1);
  430. if (wordSeparatorCodes.contains(String.fromCharCode(content))) {
  431. break;
  432. }
  433. start--;
  434. } while (true);
  435. do {
  436. if (end >= terminalWidth - 1) {
  437. break;
  438. }
  439. final content = line.cellGetContent(end + 1);
  440. if (wordSeparatorCodes.contains(String.fromCharCode(content))) {
  441. break;
  442. }
  443. end++;
  444. } while (true);
  445. _selection.clear();
  446. _selection.init(Position(start, row));
  447. _selection.update(Position(end, row));
  448. }
  449. }
  450. String? getSelectedText() {
  451. if (_selection.isEmpty) {
  452. return null;
  453. }
  454. final builder = StringBuffer();
  455. for (var row = _selection.start!.y; row <= _selection.end!.y; row++) {
  456. if (row >= buffer.height) {
  457. break;
  458. }
  459. final line = buffer.lines[row];
  460. var xStart = 0;
  461. var xEnd = viewWidth - 1;
  462. if (row == _selection.start!.y) {
  463. xStart = _selection.start!.x;
  464. } else if (!line.isWrapped) {
  465. builder.write("\n");
  466. }
  467. if (row == _selection.end!.y) {
  468. xEnd = _selection.end!.x;
  469. }
  470. for (var col = xStart; col <= xEnd; col++) {
  471. // if (col >= line.length) {
  472. // break;
  473. // }
  474. if (line.cellGetWidth(col) == 0) {
  475. continue;
  476. }
  477. var char = line.cellGetContent(col);
  478. if (char == 0x00) {
  479. const blank = 32;
  480. char = blank;
  481. }
  482. builder.writeCharCode(char);
  483. }
  484. }
  485. return builder.toString();
  486. }
  487. @override
  488. void paste(String data) {
  489. if (bracketedPasteMode) {
  490. data = '\x1b[200~$data\x1b[201~';
  491. }
  492. backend?.write(data);
  493. }
  494. void selectWord(int x, int y) {}
  495. int get _tabIndexFromCursor {
  496. var index = buffer.cursorX;
  497. if (buffer.cursorX == viewWidth) {
  498. index = 0;
  499. }
  500. return index;
  501. }
  502. void tabSetAtCursor() {
  503. tabs.setAt(_tabIndexFromCursor);
  504. }
  505. void tabClearAtCursor() {
  506. tabs.clearAt(_tabIndexFromCursor);
  507. }
  508. void tab() {
  509. while (buffer.cursorX < viewWidth) {
  510. buffer.write(' ');
  511. if (tabs.isSetAt(buffer.cursorX)) {
  512. break;
  513. }
  514. }
  515. }
  516. @override
  517. int get backgroundColor => theme.background;
  518. @override
  519. int get bufferHeight => buffer.height;
  520. @override
  521. void clearSelection() {
  522. selection?.clear();
  523. }
  524. @override
  525. int convertViewLineToRawLine(int viewLine) {
  526. if (viewHeight > buffer.height) {
  527. return viewLine;
  528. }
  529. return viewLine + (buffer.height - viewHeight);
  530. }
  531. @override
  532. BufferLine? get currentLine => buffer.currentLine;
  533. @override
  534. int get cursorColor => theme.cursor;
  535. @override
  536. String? get selectedText => getSelectedText();
  537. @override
  538. bool get isReady => true;
  539. @override
  540. void onMouseTap(Position position) {
  541. mouseMode.onTap(this, position);
  542. }
  543. @override
  544. onMouseDoubleTap(Position position) {
  545. mouseMode.onDoubleTap(this, position);
  546. }
  547. @override
  548. void onPanStart(Position position) {
  549. mouseMode.onPanStart(this, position);
  550. }
  551. @override
  552. void onPanUpdate(Position position) {
  553. mouseMode.onPanUpdate(this, position);
  554. }
  555. @override
  556. int get scrollOffsetFromBottom => buffer.scrollOffsetFromBottom;
  557. @override
  558. int get scrollOffsetFromTop => buffer.scrollOffsetFromTop;
  559. @override
  560. int get terminalHeight => viewHeight;
  561. @override
  562. int get terminalWidth => viewWidth;
  563. @override
  564. Selection? get selection => _selection;
  565. @override
  566. void raiseOnInput(String input) {
  567. backend?.write(input);
  568. }
  569. final _backendExited = Completer<int>();
  570. @override
  571. Future<int> get backendExited => _backendExited.future;
  572. var _isTerminated = false;
  573. @override
  574. void terminateBackend() {
  575. if (_isTerminated) {
  576. return;
  577. }
  578. _isTerminated = true;
  579. backend?.terminate();
  580. }
  581. @override
  582. bool get isTerminated => _isTerminated;
  583. @override
  584. void selectAll() {
  585. _selection.init(Position(0,0));
  586. _selection.update(Position(terminalWidth, bufferHeight));
  587. }
  588. }