terminal.dart 19 KB

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