terminal.dart 16 KB

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