terminal.dart 12 KB

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