terminal.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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/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. backend?.ackProcessed();
  192. refresh();
  193. }
  194. /// Writes data to the terminal. Special characters are interpreted.
  195. ///
  196. /// See also: [Buffer.writeChar]
  197. void writeChar(int codePoint) {
  198. _queue.addLast(codePoint);
  199. _processInput();
  200. refresh();
  201. }
  202. List<BufferLine> getVisibleLines() {
  203. return _buffer.getVisibleLines();
  204. }
  205. void _processInput() {
  206. while (_queue.isNotEmpty) {
  207. // if (_slowMotion) {
  208. // await Future.delayed(Duration(milliseconds: 100));
  209. // }
  210. const esc = 0x1b;
  211. final char = _queue.removeFirst();
  212. if (char == esc) {
  213. final finished = ansiHandler(_queue, this);
  214. // Terminal sequence in the queue is not completed, and no charater is
  215. // consumed.
  216. if (!finished) {
  217. _queue.addFirst(esc);
  218. break;
  219. }
  220. continue;
  221. }
  222. _processChar(char);
  223. }
  224. }
  225. void _processChar(int codePoint) {
  226. // If the character doesn't have special effect. Write it directly to the
  227. // buffer.
  228. if (codePoint > sbcMaxCodePoint) {
  229. debug.onChar(codePoint);
  230. _buffer.writeChar(codePoint);
  231. return;
  232. }
  233. // The character may have special effect.
  234. final sbcHandler = sbcHandlers[codePoint];
  235. if (sbcHandler != null) {
  236. debug.onSbc(codePoint);
  237. sbcHandler(codePoint, this);
  238. }
  239. }
  240. void refresh() {
  241. _dirty = true;
  242. notifyListeners();
  243. }
  244. void setSlowMotion(bool enabled) {
  245. _slowMotion = enabled;
  246. }
  247. void setOriginMode(bool enabled) {
  248. _originMode = enabled;
  249. buffer.setPosition(0, 0);
  250. }
  251. void setScreenMode(bool enabled) {
  252. _screenMode = true;
  253. }
  254. void setApplicationCursorKeys(bool enabled) {
  255. _applicationCursorKeys = enabled;
  256. }
  257. void setShowCursor(bool showCursor) {
  258. _showCursor = showCursor;
  259. }
  260. void setBlinkingCursor(bool enabled) {
  261. _blinkingCursor = enabled;
  262. }
  263. void setAutoWrapMode(bool enabled) {
  264. _autoWrapMode = enabled;
  265. }
  266. void setBracketedPasteMode(bool enabled) {
  267. _bracketedPasteMode = enabled;
  268. }
  269. void setInsertMode() {
  270. _replaceMode = false;
  271. }
  272. void setReplaceMode() {
  273. _replaceMode = true;
  274. }
  275. void setNewLineMode() {
  276. _lineFeedMode = false;
  277. }
  278. void setLineFeedMode() {
  279. _lineFeedMode = true;
  280. }
  281. void setMouseMode(MouseMode mode) {
  282. _mouseMode = mode;
  283. }
  284. void useMainBuffer() {
  285. _buffer = _mainBuffer;
  286. }
  287. void useAltBuffer() {
  288. _buffer = _altBuffer;
  289. }
  290. bool isUsingMainBuffer() {
  291. return _buffer == _mainBuffer;
  292. }
  293. bool isUsingAltBuffer() {
  294. return _buffer == _altBuffer;
  295. }
  296. /// Resize the terminal screen. [newWidth] and [newHeight] should be greater
  297. /// than 0. Text reflow is currently not implemented and will be avaliable in
  298. /// the future.
  299. void resize(int newWidth, int newHeight) {
  300. backend?.resize(newWidth, newHeight);
  301. newWidth = max(newWidth, 1);
  302. newHeight = max(newHeight, 1);
  303. final oldWidth = _viewWidth;
  304. final oldHeight = _viewHeight;
  305. _viewWidth = newWidth;
  306. _viewHeight = newHeight;
  307. //we need to resize both buffers so that they are ready when we switch between them
  308. _altBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  309. _mainBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  310. // maybe reflow should happen here.
  311. if (buffer == _altBuffer) {
  312. buffer.clearScrollback();
  313. }
  314. buffer.resetVerticalMargins();
  315. }
  316. void keyInput(
  317. TerminalKey key, {
  318. bool ctrl = false,
  319. bool alt = false,
  320. bool shift = false,
  321. bool mac = false,
  322. // bool meta,
  323. }) {
  324. debug.onMsg(key);
  325. for (var record in keytab.records) {
  326. if (record.key != key) {
  327. continue;
  328. }
  329. if (record.ctrl != null && record.ctrl != ctrl) {
  330. continue;
  331. }
  332. if (record.shift != null && record.shift != shift) {
  333. continue;
  334. }
  335. if (record.alt != null && record.alt != alt) {
  336. continue;
  337. }
  338. if (record.anyModifier == true &&
  339. (ctrl != true && alt != true && shift != true)) {
  340. continue;
  341. }
  342. if (record.anyModifier == false &&
  343. !(ctrl != true && alt != true && shift != true)) {
  344. continue;
  345. }
  346. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  347. continue;
  348. }
  349. if (record.newLine != null && record.newLine != newLineMode) {
  350. continue;
  351. }
  352. if (record.appCursorKeys != null &&
  353. record.appCursorKeys != applicationCursorKeys) {
  354. continue;
  355. }
  356. if (record.mac != null && record.mac != mac) {
  357. continue;
  358. }
  359. // TODO: support VT52
  360. if (record.ansi == false) {
  361. continue;
  362. }
  363. if (record.action.type == KeytabActionType.input) {
  364. debug.onMsg('input: ${record.action.value}');
  365. final input = keytabUnescape(record.action.value);
  366. backend?.write(input);
  367. return;
  368. }
  369. }
  370. if (ctrl) {
  371. if (key.index >= TerminalKey.keyA.index &&
  372. key.index <= TerminalKey.keyZ.index) {
  373. final input = key.index - TerminalKey.keyA.index + 1;
  374. backend?.write(String.fromCharCode(input));
  375. return;
  376. }
  377. }
  378. if (alt) {
  379. if (key.index >= TerminalKey.keyA.index &&
  380. key.index <= TerminalKey.keyZ.index) {
  381. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  382. backend?.write(String.fromCharCodes(input));
  383. return;
  384. }
  385. }
  386. }
  387. String? getSelectedText() {
  388. if (_selection.isEmpty) {
  389. return null;
  390. }
  391. final builder = StringBuffer();
  392. for (var row = _selection.start!.y; row <= _selection.end!.y; row++) {
  393. if (row >= buffer.height) {
  394. break;
  395. }
  396. final line = buffer.lines[row];
  397. var xStart = 0;
  398. var xEnd = viewWidth - 1;
  399. if (row == _selection.start!.y) {
  400. xStart = _selection.start!.x;
  401. } else if (!line.isWrapped) {
  402. builder.write("\n");
  403. }
  404. if (row == _selection.end!.y) {
  405. xEnd = _selection.end!.x;
  406. }
  407. for (var col = xStart; col <= xEnd; col++) {
  408. // if (col >= line.length) {
  409. // break;
  410. // }
  411. if (line.cellGetWidth(col) == 0) {
  412. continue;
  413. }
  414. var char = line.cellGetContent(col);
  415. if (char == 0x00) {
  416. const blank = 32;
  417. char = blank;
  418. }
  419. builder.writeCharCode(char);
  420. }
  421. }
  422. return builder.toString();
  423. }
  424. void paste(String data) {
  425. if (bracketedPasteMode) {
  426. data = '\x1b[200~$data\x1b[201~';
  427. }
  428. backend?.write(data);
  429. }
  430. void selectWord(int x, int y) {}
  431. int get _tabIndexFromCursor {
  432. var index = buffer.cursorX;
  433. if (buffer.cursorX == viewWidth) {
  434. index = 0;
  435. }
  436. return index;
  437. }
  438. void tabSetAtCursor() {
  439. tabs.setAt(_tabIndexFromCursor);
  440. }
  441. void tabClearAtCursor() {
  442. tabs.clearAt(_tabIndexFromCursor);
  443. }
  444. void tab() {
  445. while (buffer.cursorX < viewWidth) {
  446. buffer.write(' ');
  447. if (tabs.isSetAt(buffer.cursorX)) {
  448. break;
  449. }
  450. }
  451. }
  452. @override
  453. int get backgroundColor => theme.background;
  454. @override
  455. int get bufferHeight => buffer.height;
  456. @override
  457. void clearSelection() {
  458. selection?.clear();
  459. }
  460. @override
  461. int convertViewLineToRawLine(int viewLine) {
  462. if (viewHeight > buffer.height) {
  463. return viewLine;
  464. }
  465. return viewLine + (buffer.height - viewHeight);
  466. }
  467. @override
  468. BufferLine? get currentLine => buffer.currentLine;
  469. @override
  470. int get cursorColor => theme.cursor;
  471. @override
  472. String? get selectedText => getSelectedText();
  473. @override
  474. bool get isReady => true;
  475. @override
  476. void onMouseTap(Position position) {
  477. mouseMode.onTap(this, position);
  478. }
  479. @override
  480. void onPanStart(Position position) {
  481. mouseMode.onPanStart(this, position);
  482. }
  483. @override
  484. void onPanUpdate(Position position) {
  485. mouseMode.onPanUpdate(this, position);
  486. }
  487. @override
  488. int get scrollOffsetFromBottom => buffer.scrollOffsetFromBottom;
  489. @override
  490. int get scrollOffsetFromTop => buffer.scrollOffsetFromTop;
  491. @override
  492. int get terminalHeight => viewHeight;
  493. @override
  494. int get terminalWidth => viewWidth;
  495. @override
  496. Selection? get selection => _selection;
  497. @override
  498. void raiseOnInput(String input) {
  499. backend?.write(input);
  500. }
  501. final _backendExited = Completer<int>();
  502. @override
  503. Future<int> get backendExited => _backendExited.future;
  504. var _isTerminated = false;
  505. @override
  506. void terminateBackend() {
  507. if (_isTerminated) {
  508. return;
  509. }
  510. _isTerminated = true;
  511. backend?.terminate();
  512. }
  513. @override
  514. bool get isTerminated => _isTerminated;
  515. }