terminal.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. final TerminalTheme theme;
  172. // final cellAttr = CellAttrTemplate();
  173. late final Cursor cursor;
  174. final keytab = Keytab.defaultKeytab();
  175. final _selection = Selection();
  176. final tabs = Tabs();
  177. final debug = DebugHandler();
  178. final TerminalBackend? backend;
  179. final BellHandler onBell;
  180. final TitleChangeHandler onTitleChange;
  181. final IconChangeHandler onIconChange;
  182. @override
  183. final PlatformBehavior platform;
  184. Buffer get buffer {
  185. return _buffer;
  186. }
  187. @override
  188. int get cursorX => buffer.cursorX;
  189. @override
  190. int get cursorY => buffer.cursorY;
  191. @override
  192. void setScrollOffsetFromBottom(int scrollOffset) {
  193. final oldOffset = _buffer.scrollOffsetFromBottom;
  194. _buffer.setScrollOffsetFromBottom(scrollOffset);
  195. if (oldOffset != scrollOffset) {
  196. _dirty = true;
  197. refresh();
  198. }
  199. }
  200. /// Writes data to the terminal. Terminal sequences and special characters are
  201. /// interpreted.
  202. ///
  203. /// See also: [Buffer.write]
  204. @override
  205. void write(String text) {
  206. _queue.addAll(text.runes);
  207. _processInput();
  208. backend?.ackProcessed();
  209. refresh();
  210. }
  211. /// Writes data to the terminal. Special characters are interpreted.
  212. ///
  213. /// See also: [Buffer.writeChar]
  214. void writeChar(int codePoint) {
  215. _queue.addLast(codePoint);
  216. _processInput();
  217. refresh();
  218. }
  219. @override
  220. List<BufferLine> getVisibleLines() {
  221. return _buffer.getVisibleLines();
  222. }
  223. void _processInput() {
  224. while (_queue.isNotEmpty) {
  225. // if (_slowMotion) {
  226. // await Future.delayed(Duration(milliseconds: 100));
  227. // }
  228. const esc = 0x1b;
  229. final char = _queue.removeFirst();
  230. if (char == esc) {
  231. final finished = ansiHandler(_queue, this);
  232. // Terminal sequence in the queue is not completed, and no charater is
  233. // consumed.
  234. if (!finished) {
  235. _queue.addFirst(esc);
  236. break;
  237. }
  238. continue;
  239. }
  240. _processChar(char);
  241. }
  242. }
  243. void _processChar(int codePoint) {
  244. // If the character doesn't have special effect. Write it directly to the
  245. // buffer.
  246. if (codePoint > sbcMaxCodePoint) {
  247. debug.onChar(codePoint);
  248. _buffer.writeChar(codePoint);
  249. return;
  250. }
  251. // The character may have special effect.
  252. final sbcHandler = sbcHandlers[codePoint];
  253. if (sbcHandler != null) {
  254. debug.onSbc(codePoint);
  255. sbcHandler(codePoint, this);
  256. }
  257. }
  258. @override
  259. void refresh() {
  260. _dirty = true;
  261. notifyListeners();
  262. }
  263. void setSlowMotion(bool enabled) {
  264. _slowMotion = enabled;
  265. }
  266. void setOriginMode(bool enabled) {
  267. _originMode = enabled;
  268. buffer.setPosition(0, 0);
  269. }
  270. void setScreenMode(bool enabled) {
  271. _screenMode = true;
  272. }
  273. void setApplicationCursorKeys(bool enabled) {
  274. _applicationCursorKeys = enabled;
  275. }
  276. void setShowCursor(bool showCursor) {
  277. _showCursor = showCursor;
  278. }
  279. void setBlinkingCursor(bool enabled) {
  280. _blinkingCursor = enabled;
  281. }
  282. void setAutoWrapMode(bool enabled) {
  283. _autoWrapMode = enabled;
  284. }
  285. void setBracketedPasteMode(bool enabled) {
  286. _bracketedPasteMode = enabled;
  287. }
  288. void setInsertMode() {
  289. _replaceMode = false;
  290. }
  291. void setReplaceMode() {
  292. _replaceMode = true;
  293. }
  294. void setNewLineMode() {
  295. _lineFeedMode = false;
  296. }
  297. void setLineFeedMode() {
  298. _lineFeedMode = true;
  299. }
  300. void setMouseMode(MouseMode mode) {
  301. _mouseMode = mode;
  302. }
  303. void useMainBuffer() {
  304. _buffer = _mainBuffer;
  305. }
  306. void useAltBuffer() {
  307. _buffer = _altBuffer;
  308. }
  309. bool isUsingMainBuffer() {
  310. return _buffer == _mainBuffer;
  311. }
  312. bool isUsingAltBuffer() {
  313. return _buffer == _altBuffer;
  314. }
  315. /// Resize the terminal screen. [newWidth] and [newHeight] should be greater
  316. /// than 0. Text reflow is currently not implemented and will be avaliable in
  317. /// the future.
  318. @override
  319. void resize(
  320. int newWidth, int newHeight, int newPixelWidth, int newPixelHeight) {
  321. backend?.resize(newWidth, newHeight, newPixelWidth, newPixelHeight);
  322. newWidth = max(newWidth, 1);
  323. newHeight = max(newHeight, 1);
  324. final oldWidth = _viewWidth;
  325. final oldHeight = _viewHeight;
  326. _viewWidth = newWidth;
  327. _viewHeight = newHeight;
  328. //we need to resize both buffers so that they are ready when we switch between them
  329. _altBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  330. _mainBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  331. if (buffer == _altBuffer) {
  332. buffer.clearScrollback();
  333. }
  334. _altBuffer.resetVerticalMargins();
  335. _mainBuffer.resetVerticalMargins();
  336. }
  337. @override
  338. void keyInput(
  339. TerminalKey key, {
  340. bool ctrl = false,
  341. bool alt = false,
  342. bool shift = false,
  343. bool mac = false,
  344. // bool meta,
  345. }) {
  346. debug.onMsg(key);
  347. for (var record in keytab.records) {
  348. if (record.key != key) {
  349. continue;
  350. }
  351. if (record.ctrl != null && record.ctrl != ctrl) {
  352. continue;
  353. }
  354. if (record.shift != null && record.shift != shift) {
  355. continue;
  356. }
  357. if (record.alt != null && record.alt != alt) {
  358. continue;
  359. }
  360. if (record.anyModifier == true &&
  361. (ctrl != true && alt != true && shift != true)) {
  362. continue;
  363. }
  364. if (record.anyModifier == false &&
  365. !(ctrl != true && alt != true && shift != true)) {
  366. continue;
  367. }
  368. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  369. continue;
  370. }
  371. if (record.newLine != null && record.newLine != newLineMode) {
  372. continue;
  373. }
  374. if (record.appCursorKeys != null &&
  375. record.appCursorKeys != applicationCursorKeys) {
  376. continue;
  377. }
  378. if (record.mac != null && record.mac != mac) {
  379. continue;
  380. }
  381. // TODO: support VT52
  382. if (record.ansi == false) {
  383. continue;
  384. }
  385. if (record.action.type == KeytabActionType.input) {
  386. debug.onMsg('input: ${record.action.value}');
  387. final input = keytabUnescape(record.action.value);
  388. backend?.write(input);
  389. return;
  390. }
  391. }
  392. if (ctrl) {
  393. if (key.index >= TerminalKey.keyA.index &&
  394. key.index <= TerminalKey.keyZ.index) {
  395. final input = key.index - TerminalKey.keyA.index + 1;
  396. backend?.write(String.fromCharCode(input));
  397. return;
  398. }
  399. }
  400. if (alt) {
  401. if (key.index >= TerminalKey.keyA.index &&
  402. key.index <= TerminalKey.keyZ.index) {
  403. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  404. backend?.write(String.fromCharCodes(input));
  405. return;
  406. }
  407. }
  408. }
  409. final wordSeparatorCodes = <String>[
  410. String.fromCharCode(0),
  411. ' ',
  412. '.',
  413. ':',
  414. '/'
  415. ];
  416. void selectWordOrRow(Position position) {
  417. if (position.y > buffer.lines.length) {
  418. return;
  419. }
  420. final row = position.y;
  421. final line = buffer.lines[row];
  422. final positionIsInSelection = _selection.contains(position);
  423. final completeLineIsSelected =
  424. _selection.start?.x == 0 && _selection.end?.x == terminalWidth;
  425. if (positionIsInSelection && !completeLineIsSelected) {
  426. // select area on an already existing selection extends it to the full line
  427. _selection.clear();
  428. _selection.init(Position(0, row));
  429. _selection.update(Position(terminalWidth, row));
  430. } else {
  431. // select the word that is under position
  432. var start = position.x;
  433. var end = position.x;
  434. do {
  435. if (start == 0) {
  436. break;
  437. }
  438. final content = line.cellGetContent(start - 1);
  439. if (wordSeparatorCodes.contains(String.fromCharCode(content))) {
  440. break;
  441. }
  442. start--;
  443. } while (true);
  444. do {
  445. if (end >= terminalWidth - 1) {
  446. break;
  447. }
  448. final content = line.cellGetContent(end + 1);
  449. if (wordSeparatorCodes.contains(String.fromCharCode(content))) {
  450. break;
  451. }
  452. end++;
  453. } while (true);
  454. _selection.clear();
  455. _selection.init(Position(start, row));
  456. _selection.update(Position(end, row));
  457. }
  458. }
  459. String? getSelectedText() {
  460. if (_selection.isEmpty) {
  461. return null;
  462. }
  463. final builder = StringBuffer();
  464. for (var row = _selection.start!.y; row <= _selection.end!.y; row++) {
  465. if (row >= buffer.height) {
  466. break;
  467. }
  468. final line = buffer.lines[row];
  469. var xStart = 0;
  470. var xEnd = viewWidth - 1;
  471. if (row == _selection.start!.y) {
  472. xStart = _selection.start!.x;
  473. } else if (!line.isWrapped) {
  474. builder.write("\n");
  475. }
  476. if (row == _selection.end!.y) {
  477. xEnd = _selection.end!.x;
  478. }
  479. for (var col = xStart; col <= xEnd; col++) {
  480. // if (col >= line.length) {
  481. // break;
  482. // }
  483. if (line.cellGetWidth(col) == 0) {
  484. continue;
  485. }
  486. var char = line.cellGetContent(col);
  487. if (char == 0x00) {
  488. const blank = 32;
  489. char = blank;
  490. }
  491. builder.writeCharCode(char);
  492. }
  493. }
  494. return builder.toString();
  495. }
  496. @override
  497. void paste(String data) {
  498. if (bracketedPasteMode) {
  499. data = '\x1b[200~$data\x1b[201~';
  500. }
  501. backend?.write(data);
  502. }
  503. int get _tabIndexFromCursor {
  504. var index = buffer.cursorX;
  505. if (buffer.cursorX == viewWidth) {
  506. index = 0;
  507. }
  508. return index;
  509. }
  510. void tabSetAtCursor() {
  511. tabs.setAt(_tabIndexFromCursor);
  512. }
  513. void tabClearAtCursor() {
  514. tabs.clearAt(_tabIndexFromCursor);
  515. }
  516. void tab() {
  517. while (buffer.cursorX < viewWidth) {
  518. buffer.write(' ');
  519. if (tabs.isSetAt(buffer.cursorX)) {
  520. break;
  521. }
  522. }
  523. }
  524. @override
  525. int get backgroundColor => theme.background;
  526. @override
  527. int get bufferHeight => buffer.height;
  528. @override
  529. void clearSelection() {
  530. selection?.clear();
  531. }
  532. @override
  533. int convertViewLineToRawLine(int viewLine) {
  534. if (viewHeight > buffer.height) {
  535. return viewLine;
  536. }
  537. return viewLine + (buffer.height - viewHeight);
  538. }
  539. @override
  540. BufferLine? get currentLine => buffer.currentLine;
  541. @override
  542. int get cursorColor => theme.cursor;
  543. @override
  544. String? get selectedText => getSelectedText();
  545. @override
  546. bool get isReady => true;
  547. @override
  548. void onMouseTap(Position position) {
  549. mouseMode.onTap(this, position);
  550. }
  551. @override
  552. onMouseDoubleTap(Position position) {
  553. mouseMode.onDoubleTap(this, position);
  554. }
  555. @override
  556. void onPanStart(Position position) {
  557. mouseMode.onPanStart(this, position);
  558. }
  559. @override
  560. void onPanUpdate(Position position) {
  561. mouseMode.onPanUpdate(this, position);
  562. }
  563. @override
  564. int get scrollOffsetFromBottom => buffer.scrollOffsetFromBottom;
  565. @override
  566. int get scrollOffsetFromTop => buffer.scrollOffsetFromTop;
  567. @override
  568. int get terminalHeight => viewHeight;
  569. @override
  570. int get terminalWidth => viewWidth;
  571. @override
  572. Selection? get selection => _selection;
  573. @override
  574. void raiseOnInput(String input) {
  575. backend?.write(input);
  576. }
  577. final _backendExited = Completer<int>();
  578. @override
  579. Future<int> get backendExited => _backendExited.future;
  580. var _isTerminated = false;
  581. @override
  582. void terminateBackend() {
  583. if (_isTerminated) {
  584. return;
  585. }
  586. _isTerminated = true;
  587. backend?.terminate();
  588. }
  589. @override
  590. bool get isTerminated => _isTerminated;
  591. @override
  592. void selectAll() {
  593. _selection.init(Position(0, 0));
  594. _selection.update(Position(terminalWidth, bufferHeight));
  595. }
  596. String _composingString = '';
  597. @override
  598. String get composingString => _composingString;
  599. @override
  600. void updateComposingString(String value) {
  601. _composingString = value;
  602. refresh();
  603. }
  604. TerminalSearchResult get searchHits => _userSearchTask.searchResult;
  605. }