terminal.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. final sbcHandler = sbcHandlers[codePoint];
  191. if (sbcHandler != null) {
  192. debug.onSbc(codePoint);
  193. sbcHandler(codePoint, this);
  194. } else {
  195. debug.onChar(codePoint);
  196. _buffer.writeChar(codePoint);
  197. }
  198. }
  199. void refresh() {
  200. _dirty = true;
  201. notifyListeners();
  202. }
  203. void setSlowMotion(bool enabled) {
  204. _slowMotion = enabled;
  205. }
  206. void setOriginMode(bool enabled) {
  207. _originMode = enabled;
  208. buffer.setPosition(0, 0);
  209. }
  210. void setScreenMode(bool enabled) {
  211. _screenMode = true;
  212. }
  213. void setApplicationCursorKeys(bool enabled) {
  214. _applicationCursorKeys = enabled;
  215. }
  216. void setShowCursor(bool showCursor) {
  217. _showCursor = showCursor;
  218. }
  219. void setBlinkingCursor(bool enabled) {
  220. _blinkingCursor = enabled;
  221. }
  222. void setAutoWrapMode(bool enabled) {
  223. _autoWrapMode = enabled;
  224. }
  225. void setBracketedPasteMode(bool enabled) {
  226. _bracketedPasteMode = enabled;
  227. }
  228. void setInsertMode() {
  229. _replaceMode = false;
  230. }
  231. void setReplaceMode() {
  232. _replaceMode = true;
  233. }
  234. void setNewLineMode() {
  235. _lineFeedMode = false;
  236. }
  237. void setLineFeedMode() {
  238. _lineFeedMode = true;
  239. }
  240. void setMouseMode(MouseMode mode) {
  241. _mouseMode = mode;
  242. }
  243. void useMainBuffer() {
  244. _buffer = _mainBuffer;
  245. }
  246. void useAltBuffer() {
  247. _buffer = _altBuffer;
  248. }
  249. bool isUsingMainBuffer() {
  250. return _buffer == _mainBuffer;
  251. }
  252. bool isUsingAltBuffer() {
  253. return _buffer == _altBuffer;
  254. }
  255. void resize(int width, int heigth) {
  256. final cursorY = buffer.convertViewLineToRawLine(buffer.cursorY);
  257. _viewWidth = max(width, 1);
  258. _viewHeight = max(heigth, 1);
  259. buffer.setCursorY(buffer.convertRawLineToViewLine(cursorY));
  260. if (buffer == _altBuffer) {
  261. buffer.clearScrollback();
  262. }
  263. buffer.resetVerticalMargins();
  264. }
  265. void keyInput(
  266. TerminalKey key, {
  267. bool ctrl = false,
  268. bool alt = false,
  269. bool shift = false,
  270. // bool meta,
  271. }) {
  272. debug.onMsg(key);
  273. for (var record in keytab.records) {
  274. if (record.key != key) {
  275. continue;
  276. }
  277. if (record.ctrl != null && record.ctrl != ctrl) {
  278. continue;
  279. }
  280. if (record.shift != null && record.shift != shift) {
  281. continue;
  282. }
  283. if (record.alt != null && record.alt != alt) {
  284. continue;
  285. }
  286. if (record.anyModifier == true &&
  287. (ctrl != true && alt != true && shift != true)) {
  288. continue;
  289. }
  290. if (record.anyModifier == false &&
  291. !(ctrl != true && alt != true && shift != true)) {
  292. continue;
  293. }
  294. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  295. continue;
  296. }
  297. if (record.newLine != null && record.newLine != newLineMode) {
  298. continue;
  299. }
  300. if (record.appCursorKeys != null &&
  301. record.appCursorKeys != applicationCursorKeys) {
  302. continue;
  303. }
  304. // TODO: support VT52
  305. if (record.ansi == false) {
  306. continue;
  307. }
  308. if (record.action.type == KeytabActionType.input) {
  309. debug.onMsg('input: ${record.action.value}');
  310. final input = keytabUnescape(record.action.value);
  311. onInput(input);
  312. return;
  313. }
  314. }
  315. if (ctrl) {
  316. if (key.index >= TerminalKey.keyA.index &&
  317. key.index <= TerminalKey.keyZ.index) {
  318. final input = key.index - TerminalKey.keyA.index + 1;
  319. onInput(String.fromCharCode(input));
  320. return;
  321. }
  322. }
  323. if (alt) {
  324. if (key.index >= TerminalKey.keyA.index &&
  325. key.index <= TerminalKey.keyZ.index) {
  326. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  327. onInput(String.fromCharCodes(input));
  328. return;
  329. }
  330. }
  331. }
  332. String? getSelectedText() {
  333. if (selection.isEmpty) {
  334. return null;
  335. }
  336. final builder = StringBuffer();
  337. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  338. if (row >= buffer.height) {
  339. break;
  340. }
  341. final line = buffer.lines[row];
  342. var xStart = 0;
  343. var xEnd = viewWidth - 1;
  344. if (row == selection.start!.y) {
  345. xStart = selection.start!.x;
  346. } else if (!line.isWrapped) {
  347. builder.write("\n");
  348. }
  349. if (row == selection.end!.y) {
  350. xEnd = selection.end!.x;
  351. }
  352. for (var col = xStart; col <= xEnd; col++) {
  353. if (col >= line.length) {
  354. break;
  355. }
  356. final cell = line.getCell(col);
  357. if (cell.width == 0) {
  358. continue;
  359. }
  360. var char = line.getCell(col).codePoint;
  361. if (char == null || char == 0x00) {
  362. const blank = 32;
  363. char = blank;
  364. }
  365. builder.writeCharCode(char);
  366. }
  367. }
  368. return builder.toString();
  369. }
  370. void paste(String data) {
  371. if (bracketedPasteMode) {
  372. data = '\x1b[200~$data\x1b[201~';
  373. }
  374. onInput(data);
  375. }
  376. int get _tabIndexFromCursor {
  377. var index = buffer.cursorX;
  378. if (buffer.cursorX == viewWidth) {
  379. index = 0;
  380. }
  381. return index;
  382. }
  383. void tabSetAtCursor() {
  384. tabs.setAt(_tabIndexFromCursor);
  385. }
  386. void tabClearAtCursor() {
  387. tabs.clearAt(_tabIndexFromCursor);
  388. }
  389. void tab() {
  390. while (buffer.cursorX < viewWidth) {
  391. buffer.write(' ');
  392. if (tabs.isSetAt(buffer.cursorX)) {
  393. break;
  394. }
  395. }
  396. }
  397. }