terminal.dart 16 KB

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