terminal.dart 11 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. // _buffer.write('this is magic!');
  44. }
  45. bool _dirty = false;
  46. bool get dirty {
  47. if (_dirty) {
  48. _dirty = false;
  49. return true;
  50. } else {
  51. return false;
  52. }
  53. }
  54. int? _maxLines;
  55. int? get maxLines {
  56. if (_maxLines == null) return null;
  57. return max(viewHeight, _maxLines!);
  58. }
  59. int _viewWidth = 80;
  60. int _viewHeight = 25;
  61. int get viewWidth => _viewWidth;
  62. int get viewHeight => _viewHeight;
  63. int get visibleHeight => min(_viewHeight, buffer.height);
  64. int get invisibleHeight => buffer.height - visibleHeight;
  65. /// Insert/Replace Mode (IRM)
  66. ///
  67. /// The terminal displays received characters at the cursor position.
  68. /// Insert/Replace mode determines how the terminal adds characters to the
  69. /// screen. Insert mode displays the new character and moves previously
  70. /// displayed characters to the right. Replace mode adds characters by
  71. /// replacing the character at the cursor position.
  72. ///
  73. /// You can set or reset insert/replace mode as follows.
  74. bool _replaceMode = true;
  75. bool _lineFeed = true;
  76. bool _screenMode = false; // DECSCNM (black on white background)
  77. bool _autoWrapMode = true;
  78. bool _bracketedPasteMode = false;
  79. /// DECOM – Origin Mode (DEC Private)
  80. ///
  81. /// This is a private parameter applicable to set mode (SM) and reset mode
  82. /// (RM) control sequences. The reset state causes the origin to be at the
  83. /// upper-left character position on the screen. Line and column numbers are,
  84. /// therefore, independent of current margin settings. The cursor may be
  85. /// positioned outside the margins with a cursor position (CUP) or horizontal
  86. /// and vertical position (HVP) control.
  87. ///
  88. /// The set state causes the origin to be at the upper-left character position
  89. /// within the margins. Line and column numbers are therefore relative to the
  90. /// current margin settings. The cursor is not allowed to be positioned
  91. /// outside the margins.
  92. ///
  93. /// The cursor is moved to the new home position when this mode is set or
  94. /// reset.
  95. ///
  96. /// Lines and columns are numbered consecutively, with the origin being line
  97. /// 1, column 1.
  98. bool get originMode => _originMode;
  99. bool _originMode = false;
  100. bool get lineFeed => _lineFeed;
  101. bool get newLineMode => !_lineFeed;
  102. bool get bracketedPasteMode => _bracketedPasteMode;
  103. bool _showCursor = true;
  104. bool _applicationCursorKeys = false;
  105. bool _blinkingCursor = true;
  106. bool get showCursor => _showCursor;
  107. bool get applicationCursorKeys => _applicationCursorKeys;
  108. bool get blinkingCursor => _blinkingCursor;
  109. late Buffer _buffer;
  110. late Buffer _mainBuffer;
  111. late Buffer _altBuffer;
  112. /// Queue of input characters. addLast() to add, removeFirst() to consume.
  113. final _queue = Queue<int>();
  114. bool _slowMotion = false;
  115. bool get slowMotion => _slowMotion;
  116. MouseMode _mouseMode = MouseMode.none;
  117. MouseMode get mouseMode => _mouseMode;
  118. final TerminalTheme theme;
  119. final cellAttr = CellAttrTemplate();
  120. final keytab = Keytab.defaultKeytab();
  121. final selection = Selection();
  122. final tabs = Tabs();
  123. final debug = DebugHandler();
  124. final TerminalInputHandler onInput;
  125. final BellHandler onBell;
  126. final TitleChangeHandler onTitleChange;
  127. final IconChangeHandler onIconChange;
  128. final PlatformBehavior platform;
  129. Buffer get buffer {
  130. return _buffer;
  131. }
  132. int get cursorX => buffer.cursorX;
  133. int get cursorY => buffer.cursorY;
  134. int get scrollOffset => buffer.scrollOffsetFromBottom;
  135. void write(String text) async {
  136. _queue.addAll(text.runes);
  137. _processInput();
  138. }
  139. void writeBytes(Iterable<int> data) async {
  140. _queue.addAll(data);
  141. _processInput();
  142. }
  143. void writeChar(int codePoint) {
  144. _queue.addLast(codePoint);
  145. _processInput();
  146. }
  147. List<BufferLine> getVisibleLines() {
  148. return _buffer.getVisibleLines();
  149. }
  150. void _processInput() {
  151. while (_queue.isNotEmpty) {
  152. // if (_slowMotion) {
  153. // await Future.delayed(Duration(milliseconds: 100));
  154. // }
  155. const esc = 0x1b;
  156. final char = _queue.removeFirst();
  157. if (char == esc) {
  158. ansiHandler(_queue, this);
  159. refresh();
  160. continue;
  161. }
  162. _processChar(char);
  163. }
  164. }
  165. void _processChar(int codePoint) {
  166. final sbcHandler = sbcHandlers[codePoint];
  167. if (sbcHandler != null) {
  168. debug.onSbc(codePoint);
  169. sbcHandler(codePoint, this);
  170. } else {
  171. debug.onChar(codePoint);
  172. _buffer.writeChar(codePoint);
  173. }
  174. refresh();
  175. }
  176. void refresh() {
  177. _dirty = true;
  178. notifyListeners();
  179. }
  180. void setSlowMotion(bool enabled) {
  181. _slowMotion = enabled ?? _slowMotion;
  182. }
  183. void setOriginMode(bool enabled) {
  184. _originMode = enabled ?? _originMode;
  185. buffer.setPosition(0, 0);
  186. }
  187. void setScreenMode(bool enabled) {
  188. _screenMode = true;
  189. }
  190. void setApplicationCursorKeys(bool enabled) {
  191. _applicationCursorKeys = enabled ?? _applicationCursorKeys;
  192. }
  193. void setShowCursor(bool showCursor) {
  194. _showCursor = showCursor ?? _showCursor;
  195. }
  196. void setBlinkingCursor(bool enabled) {
  197. _blinkingCursor = enabled ?? _blinkingCursor;
  198. }
  199. void setAutoWrapMode(bool enabled) {
  200. _autoWrapMode = enabled;
  201. }
  202. void setBracketedPasteMode(bool enabled) {
  203. _bracketedPasteMode = enabled;
  204. }
  205. void setInsertMode() {
  206. _replaceMode = false;
  207. }
  208. void setReplaceMode() {
  209. _replaceMode = true;
  210. }
  211. void setNewLineMode() {
  212. _lineFeed = false;
  213. }
  214. void setLineFeedMode() {
  215. _lineFeed = true;
  216. }
  217. void setMouseMode(MouseMode mode) {
  218. _mouseMode = mode ?? _mouseMode;
  219. }
  220. void useMainBuffer() {
  221. _buffer = _mainBuffer;
  222. }
  223. void useAltBuffer() {
  224. _buffer = _altBuffer;
  225. }
  226. bool isUsingMainBuffer() {
  227. return _buffer == _mainBuffer;
  228. }
  229. bool isUsingAltBuffer() {
  230. return _buffer == _altBuffer;
  231. }
  232. void resize(int width, int heigth) {
  233. final cursorY = buffer.convertViewLineToRawLine(buffer.cursorY);
  234. _viewWidth = max(width, 1);
  235. _viewHeight = max(heigth, 1);
  236. buffer.setCursorY(buffer.convertRawLineToViewLine(cursorY));
  237. if (buffer == _altBuffer) {
  238. buffer.clearScrollback();
  239. }
  240. buffer.resetVerticalMargins();
  241. }
  242. void keyInput(
  243. TerminalKey key, {
  244. bool ctrl = false,
  245. bool alt = false,
  246. bool shift = false,
  247. // bool meta,
  248. }) {
  249. debug.onMsg(key);
  250. // keep a local reference to bypass nnbd checks.
  251. final onInput = this.onInput;
  252. if (onInput == null) {
  253. return;
  254. }
  255. for (var record in keytab.records) {
  256. if (record.key != key) {
  257. continue;
  258. }
  259. if (record.ctrl != null && record.ctrl != ctrl) {
  260. continue;
  261. }
  262. if (record.shift != null && record.shift != shift) {
  263. continue;
  264. }
  265. if (record.alt != null && record.alt != alt) {
  266. continue;
  267. }
  268. if (record.anyModifier == true &&
  269. (ctrl != true && alt != true && shift != true)) {
  270. continue;
  271. }
  272. if (record.anyModifier == false &&
  273. !(ctrl != true && alt != true && shift != true)) {
  274. continue;
  275. }
  276. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  277. continue;
  278. }
  279. if (record.newLine != null && record.newLine != newLineMode) {
  280. continue;
  281. }
  282. if (record.appCursorKeys != null &&
  283. record.appCursorKeys != applicationCursorKeys) {
  284. continue;
  285. }
  286. // TODO: support VT52
  287. if (record.ansi == false) {
  288. continue;
  289. }
  290. if (record.action.type == KeytabActionType.input) {
  291. debug.onMsg('input: ${record.action.value}');
  292. final input = keytabUnescape(record.action.value);
  293. onInput(input);
  294. return;
  295. }
  296. }
  297. if (ctrl) {
  298. if (key.index >= TerminalKey.keyA.index &&
  299. key.index <= TerminalKey.keyZ.index) {
  300. final input = key.index - TerminalKey.keyA.index + 1;
  301. onInput(String.fromCharCode(input));
  302. return;
  303. }
  304. }
  305. if (alt) {
  306. if (key.index >= TerminalKey.keyA.index &&
  307. key.index <= TerminalKey.keyZ.index) {
  308. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  309. onInput(String.fromCharCodes(input));
  310. return;
  311. }
  312. }
  313. }
  314. String? getSelectedText() {
  315. if (selection.isEmpty) {
  316. return null;
  317. }
  318. final builder = StringBuffer();
  319. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  320. if (row >= buffer.height) {
  321. break;
  322. }
  323. final line = buffer.lines[row];
  324. var xStart = 0;
  325. var xEnd = viewWidth - 1;
  326. if (row == selection.start!.y) {
  327. xStart = selection.start!.x;
  328. } else if (!line.isWrapped) {
  329. builder.write("\n");
  330. }
  331. if (row == selection.end!.y) {
  332. xEnd = selection.end!.x;
  333. }
  334. for (var col = xStart; col <= xEnd; col++) {
  335. if (col >= line.length) {
  336. break;
  337. }
  338. final cell = line.getCell(col);
  339. if (cell.width == 0) {
  340. continue;
  341. }
  342. var char = line.getCell(col).codePoint;
  343. if (char == null || char == 0x00) {
  344. const blank = 32;
  345. char = blank;
  346. }
  347. builder.writeCharCode(char);
  348. }
  349. }
  350. return builder.toString();
  351. }
  352. void paste(String data) {
  353. if (bracketedPasteMode) {
  354. data = '\x1b[200~$data\x1b[201~';
  355. }
  356. onInput(data);
  357. }
  358. int get _tabIndexFromCursor {
  359. var index = buffer.cursorX;
  360. if (buffer.cursorX == viewWidth) {
  361. index = 0;
  362. }
  363. return index;
  364. }
  365. void tabSetAtCursor() {
  366. tabs.setAt(_tabIndexFromCursor);
  367. }
  368. void tabClearAtCursor() {
  369. tabs.clearAt(_tabIndexFromCursor);
  370. }
  371. void tab() {
  372. while (buffer.cursorX < viewWidth) {
  373. buffer.write(' ');
  374. if (tabs.isSetAt(buffer.cursorX)) {
  375. break;
  376. }
  377. }
  378. }
  379. }