terminal.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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. 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(
  300. int newWidth, int newHeight, int newPixelWidth, int newPixelHeight) {
  301. backend?.resizeFull(newWidth, newHeight, newPixelWidth, newPixelHeight);
  302. newWidth = max(newWidth, 1);
  303. newHeight = max(newHeight, 1);
  304. final oldWidth = _viewWidth;
  305. final oldHeight = _viewHeight;
  306. _viewWidth = newWidth;
  307. _viewHeight = newHeight;
  308. //we need to resize both buffers so that they are ready when we switch between them
  309. _altBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  310. _mainBuffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  311. // maybe reflow should happen here.
  312. if (buffer == _altBuffer) {
  313. buffer.clearScrollback();
  314. }
  315. buffer.resetVerticalMargins();
  316. }
  317. void keyInput(
  318. TerminalKey key, {
  319. bool ctrl = false,
  320. bool alt = false,
  321. bool shift = false,
  322. bool mac = false,
  323. // bool meta,
  324. }) {
  325. debug.onMsg(key);
  326. for (var record in keytab.records) {
  327. if (record.key != key) {
  328. continue;
  329. }
  330. if (record.ctrl != null && record.ctrl != ctrl) {
  331. continue;
  332. }
  333. if (record.shift != null && record.shift != shift) {
  334. continue;
  335. }
  336. if (record.alt != null && record.alt != alt) {
  337. continue;
  338. }
  339. if (record.anyModifier == true &&
  340. (ctrl != true && alt != true && shift != true)) {
  341. continue;
  342. }
  343. if (record.anyModifier == false &&
  344. !(ctrl != true && alt != true && shift != true)) {
  345. continue;
  346. }
  347. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  348. continue;
  349. }
  350. if (record.newLine != null && record.newLine != newLineMode) {
  351. continue;
  352. }
  353. if (record.appCursorKeys != null &&
  354. record.appCursorKeys != applicationCursorKeys) {
  355. continue;
  356. }
  357. if (record.mac != null && record.mac != mac) {
  358. continue;
  359. }
  360. // TODO: support VT52
  361. if (record.ansi == false) {
  362. continue;
  363. }
  364. if (record.action.type == KeytabActionType.input) {
  365. debug.onMsg('input: ${record.action.value}');
  366. final input = keytabUnescape(record.action.value);
  367. backend?.write(input);
  368. return;
  369. }
  370. }
  371. if (ctrl) {
  372. if (key.index >= TerminalKey.keyA.index &&
  373. key.index <= TerminalKey.keyZ.index) {
  374. final input = key.index - TerminalKey.keyA.index + 1;
  375. backend?.write(String.fromCharCode(input));
  376. return;
  377. }
  378. }
  379. if (alt) {
  380. if (key.index >= TerminalKey.keyA.index &&
  381. key.index <= TerminalKey.keyZ.index) {
  382. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  383. backend?.write(String.fromCharCodes(input));
  384. return;
  385. }
  386. }
  387. }
  388. String? getSelectedText() {
  389. if (_selection.isEmpty) {
  390. return null;
  391. }
  392. final builder = StringBuffer();
  393. for (var row = _selection.start!.y; row <= _selection.end!.y; row++) {
  394. if (row >= buffer.height) {
  395. break;
  396. }
  397. final line = buffer.lines[row];
  398. var xStart = 0;
  399. var xEnd = viewWidth - 1;
  400. if (row == _selection.start!.y) {
  401. xStart = _selection.start!.x;
  402. } else if (!line.isWrapped) {
  403. builder.write("\n");
  404. }
  405. if (row == _selection.end!.y) {
  406. xEnd = _selection.end!.x;
  407. }
  408. for (var col = xStart; col <= xEnd; col++) {
  409. // if (col >= line.length) {
  410. // break;
  411. // }
  412. if (line.cellGetWidth(col) == 0) {
  413. continue;
  414. }
  415. var char = line.cellGetContent(col);
  416. if (char == 0x00) {
  417. const blank = 32;
  418. char = blank;
  419. }
  420. builder.writeCharCode(char);
  421. }
  422. }
  423. return builder.toString();
  424. }
  425. void paste(String data) {
  426. if (bracketedPasteMode) {
  427. data = '\x1b[200~$data\x1b[201~';
  428. }
  429. backend?.write(data);
  430. }
  431. void selectWord(int x, int y) {}
  432. int get _tabIndexFromCursor {
  433. var index = buffer.cursorX;
  434. if (buffer.cursorX == viewWidth) {
  435. index = 0;
  436. }
  437. return index;
  438. }
  439. void tabSetAtCursor() {
  440. tabs.setAt(_tabIndexFromCursor);
  441. }
  442. void tabClearAtCursor() {
  443. tabs.clearAt(_tabIndexFromCursor);
  444. }
  445. void tab() {
  446. while (buffer.cursorX < viewWidth) {
  447. buffer.write(' ');
  448. if (tabs.isSetAt(buffer.cursorX)) {
  449. break;
  450. }
  451. }
  452. }
  453. @override
  454. int get backgroundColor => theme.background;
  455. @override
  456. int get bufferHeight => buffer.height;
  457. @override
  458. void clearSelection() {
  459. selection?.clear();
  460. }
  461. @override
  462. int convertViewLineToRawLine(int viewLine) {
  463. if (viewHeight > buffer.height) {
  464. return viewLine;
  465. }
  466. return viewLine + (buffer.height - viewHeight);
  467. }
  468. @override
  469. BufferLine? get currentLine => buffer.currentLine;
  470. @override
  471. int get cursorColor => theme.cursor;
  472. @override
  473. String? get selectedText => getSelectedText();
  474. @override
  475. bool get isReady => true;
  476. @override
  477. void onMouseTap(Position position) {
  478. mouseMode.onTap(this, position);
  479. }
  480. @override
  481. void onPanStart(Position position) {
  482. mouseMode.onPanStart(this, position);
  483. }
  484. @override
  485. void onPanUpdate(Position position) {
  486. mouseMode.onPanUpdate(this, position);
  487. }
  488. @override
  489. int get scrollOffsetFromBottom => buffer.scrollOffsetFromBottom;
  490. @override
  491. int get scrollOffsetFromTop => buffer.scrollOffsetFromTop;
  492. @override
  493. int get terminalHeight => viewHeight;
  494. @override
  495. int get terminalWidth => viewWidth;
  496. @override
  497. Selection? get selection => _selection;
  498. @override
  499. void raiseOnInput(String input) {
  500. backend?.write(input);
  501. }
  502. final _backendExited = Completer<int>();
  503. @override
  504. Future<int> get backendExited => _backendExited.future;
  505. var _isTerminated = false;
  506. @override
  507. void terminateBackend() {
  508. if (_isTerminated) {
  509. return;
  510. }
  511. _isTerminated = true;
  512. backend?.terminate();
  513. }
  514. @override
  515. bool get isTerminated => _isTerminated;
  516. }