terminal.dart 19 KB

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