terminal.dart 15 KB

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