terminal.dart 13 KB

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