terminal.dart 11 KB

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