terminal.dart 14 KB

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