terminal.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. bool _bracketedPasteMode = false;
  114. bool get bracketedPasteMode => _bracketedPasteMode;
  115. bool _showCursor = true;
  116. bool get showCursor => _showCursor;
  117. /// DECCKM – Cursor Keys Mode (DEC Private)
  118. ///
  119. /// This is a private parameter applicable to set mode (SM) and reset mode
  120. /// (RM) control sequences. This mode is only effective when the terminal is
  121. /// in keypad application mode (see DECKPAM) and the ANSI/VT52 mode (DECANM)
  122. /// is set (see DECANM). Under these conditions, if the cursor key mode is
  123. /// reset, the four cursor function keys will send ANSI cursor control
  124. /// commands. If cursor key mode is set, the four cursor function keys will
  125. /// send application functions.
  126. bool get applicationCursorKeys => _applicationCursorKeys;
  127. bool _applicationCursorKeys = false;
  128. bool _blinkingCursor = true;
  129. bool get blinkingCursor => _blinkingCursor;
  130. late Buffer _buffer;
  131. late Buffer _mainBuffer;
  132. late Buffer _altBuffer;
  133. /// Queue of input characters. addLast() to add, removeFirst() to consume.
  134. final _queue = Queue<int>();
  135. bool _slowMotion = false;
  136. bool get slowMotion => _slowMotion;
  137. MouseMode _mouseMode = MouseMode.none;
  138. MouseMode get mouseMode => _mouseMode;
  139. final TerminalTheme theme;
  140. final cellAttr = CellAttrTemplate();
  141. final keytab = Keytab.defaultKeytab();
  142. final selection = Selection();
  143. final tabs = Tabs();
  144. final debug = DebugHandler();
  145. final TerminalInputHandler onInput;
  146. final BellHandler onBell;
  147. final TitleChangeHandler onTitleChange;
  148. final IconChangeHandler onIconChange;
  149. final PlatformBehavior platform;
  150. Buffer get buffer {
  151. return _buffer;
  152. }
  153. int get cursorX => buffer.cursorX;
  154. int get cursorY => buffer.cursorY;
  155. int get scrollOffset => buffer.scrollOffsetFromBottom;
  156. void write(String text) {
  157. _queue.addAll(text.runes);
  158. _processInput();
  159. refresh();
  160. }
  161. void writeChar(int codePoint) {
  162. _queue.addLast(codePoint);
  163. _processInput();
  164. refresh();
  165. }
  166. List<BufferLine> getVisibleLines() {
  167. return _buffer.getVisibleLines();
  168. }
  169. void _processInput() {
  170. while (_queue.isNotEmpty) {
  171. // if (_slowMotion) {
  172. // await Future.delayed(Duration(milliseconds: 100));
  173. // }
  174. const esc = 0x1b;
  175. final char = _queue.removeFirst();
  176. if (char == esc) {
  177. ansiHandler(_queue, this);
  178. continue;
  179. }
  180. _processChar(char);
  181. }
  182. }
  183. void _processChar(int codePoint) {
  184. final sbcHandler = sbcHandlers[codePoint];
  185. if (sbcHandler != null) {
  186. debug.onSbc(codePoint);
  187. sbcHandler(codePoint, this);
  188. } else {
  189. debug.onChar(codePoint);
  190. _buffer.writeChar(codePoint);
  191. }
  192. }
  193. void refresh() {
  194. _dirty = true;
  195. notifyListeners();
  196. }
  197. void setSlowMotion(bool enabled) {
  198. _slowMotion = enabled;
  199. }
  200. void setOriginMode(bool enabled) {
  201. _originMode = enabled;
  202. buffer.setPosition(0, 0);
  203. }
  204. void setScreenMode(bool enabled) {
  205. _screenMode = true;
  206. }
  207. void setApplicationCursorKeys(bool enabled) {
  208. _applicationCursorKeys = enabled;
  209. }
  210. void setShowCursor(bool showCursor) {
  211. _showCursor = showCursor;
  212. }
  213. void setBlinkingCursor(bool enabled) {
  214. _blinkingCursor = enabled;
  215. }
  216. void setAutoWrapMode(bool enabled) {
  217. _autoWrapMode = enabled;
  218. }
  219. void setBracketedPasteMode(bool enabled) {
  220. _bracketedPasteMode = enabled;
  221. }
  222. void setInsertMode() {
  223. _replaceMode = false;
  224. }
  225. void setReplaceMode() {
  226. _replaceMode = true;
  227. }
  228. void setNewLineMode() {
  229. _lineFeedMode = false;
  230. }
  231. void setLineFeedMode() {
  232. _lineFeedMode = true;
  233. }
  234. void setMouseMode(MouseMode mode) {
  235. _mouseMode = mode;
  236. }
  237. void useMainBuffer() {
  238. _buffer = _mainBuffer;
  239. }
  240. void useAltBuffer() {
  241. _buffer = _altBuffer;
  242. }
  243. bool isUsingMainBuffer() {
  244. return _buffer == _mainBuffer;
  245. }
  246. bool isUsingAltBuffer() {
  247. return _buffer == _altBuffer;
  248. }
  249. void resize(int width, int heigth) {
  250. final cursorY = buffer.convertViewLineToRawLine(buffer.cursorY);
  251. _viewWidth = max(width, 1);
  252. _viewHeight = max(heigth, 1);
  253. buffer.setCursorY(buffer.convertRawLineToViewLine(cursorY));
  254. if (buffer == _altBuffer) {
  255. buffer.clearScrollback();
  256. }
  257. buffer.resetVerticalMargins();
  258. }
  259. void keyInput(
  260. TerminalKey key, {
  261. bool ctrl = false,
  262. bool alt = false,
  263. bool shift = false,
  264. // bool meta,
  265. }) {
  266. debug.onMsg(key);
  267. for (var record in keytab.records) {
  268. if (record.key != key) {
  269. continue;
  270. }
  271. if (record.ctrl != null && record.ctrl != ctrl) {
  272. continue;
  273. }
  274. if (record.shift != null && record.shift != shift) {
  275. continue;
  276. }
  277. if (record.alt != null && record.alt != alt) {
  278. continue;
  279. }
  280. if (record.anyModifier == true &&
  281. (ctrl != true && alt != true && shift != true)) {
  282. continue;
  283. }
  284. if (record.anyModifier == false &&
  285. !(ctrl != true && alt != true && shift != true)) {
  286. continue;
  287. }
  288. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  289. continue;
  290. }
  291. if (record.newLine != null && record.newLine != newLineMode) {
  292. continue;
  293. }
  294. if (record.appCursorKeys != null &&
  295. record.appCursorKeys != applicationCursorKeys) {
  296. continue;
  297. }
  298. // TODO: support VT52
  299. if (record.ansi == false) {
  300. continue;
  301. }
  302. if (record.action.type == KeytabActionType.input) {
  303. debug.onMsg('input: ${record.action.value}');
  304. final input = keytabUnescape(record.action.value);
  305. onInput(input);
  306. return;
  307. }
  308. }
  309. if (ctrl) {
  310. if (key.index >= TerminalKey.keyA.index &&
  311. key.index <= TerminalKey.keyZ.index) {
  312. final input = key.index - TerminalKey.keyA.index + 1;
  313. onInput(String.fromCharCode(input));
  314. return;
  315. }
  316. }
  317. if (alt) {
  318. if (key.index >= TerminalKey.keyA.index &&
  319. key.index <= TerminalKey.keyZ.index) {
  320. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  321. onInput(String.fromCharCodes(input));
  322. return;
  323. }
  324. }
  325. }
  326. String? getSelectedText() {
  327. if (selection.isEmpty) {
  328. return null;
  329. }
  330. final builder = StringBuffer();
  331. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  332. if (row >= buffer.height) {
  333. break;
  334. }
  335. final line = buffer.lines[row];
  336. var xStart = 0;
  337. var xEnd = viewWidth - 1;
  338. if (row == selection.start!.y) {
  339. xStart = selection.start!.x;
  340. } else if (!line.isWrapped) {
  341. builder.write("\n");
  342. }
  343. if (row == selection.end!.y) {
  344. xEnd = selection.end!.x;
  345. }
  346. for (var col = xStart; col <= xEnd; col++) {
  347. if (col >= line.length) {
  348. break;
  349. }
  350. final cell = line.getCell(col);
  351. if (cell.width == 0) {
  352. continue;
  353. }
  354. var char = line.getCell(col).codePoint;
  355. if (char == null || char == 0x00) {
  356. const blank = 32;
  357. char = blank;
  358. }
  359. builder.writeCharCode(char);
  360. }
  361. }
  362. return builder.toString();
  363. }
  364. void paste(String data) {
  365. if (bracketedPasteMode) {
  366. data = '\x1b[200~$data\x1b[201~';
  367. }
  368. onInput(data);
  369. }
  370. int get _tabIndexFromCursor {
  371. var index = buffer.cursorX;
  372. if (buffer.cursorX == viewWidth) {
  373. index = 0;
  374. }
  375. return index;
  376. }
  377. void tabSetAtCursor() {
  378. tabs.setAt(_tabIndexFromCursor);
  379. }
  380. void tabClearAtCursor() {
  381. tabs.clearAt(_tabIndexFromCursor);
  382. }
  383. void tab() {
  384. while (buffer.cursorX < viewWidth) {
  385. buffer.write(' ');
  386. if (tabs.isSetAt(buffer.cursorX)) {
  387. break;
  388. }
  389. }
  390. }
  391. }