terminal.dart 18 KB

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