terminal.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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;
  182. }
  183. void setOriginMode(bool enabled) {
  184. _originMode = enabled;
  185. buffer.setPosition(0, 0);
  186. }
  187. void setScreenMode(bool enabled) {
  188. _screenMode = true;
  189. }
  190. void setApplicationCursorKeys(bool enabled) {
  191. _applicationCursorKeys = enabled;
  192. }
  193. void setShowCursor(bool showCursor) {
  194. _showCursor = showCursor;
  195. }
  196. void setBlinkingCursor(bool enabled) {
  197. _blinkingCursor = enabled;
  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;
  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. for (var record in keytab.records) {
  251. if (record.key != key) {
  252. continue;
  253. }
  254. if (record.ctrl != null && record.ctrl != ctrl) {
  255. continue;
  256. }
  257. if (record.shift != null && record.shift != shift) {
  258. continue;
  259. }
  260. if (record.alt != null && record.alt != alt) {
  261. continue;
  262. }
  263. if (record.anyModifier == true &&
  264. (ctrl != true && alt != true && shift != true)) {
  265. continue;
  266. }
  267. if (record.anyModifier == false &&
  268. !(ctrl != true && alt != true && shift != true)) {
  269. continue;
  270. }
  271. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  272. continue;
  273. }
  274. if (record.newLine != null && record.newLine != newLineMode) {
  275. continue;
  276. }
  277. if (record.appCursorKeys != null &&
  278. record.appCursorKeys != applicationCursorKeys) {
  279. continue;
  280. }
  281. // TODO: support VT52
  282. if (record.ansi == false) {
  283. continue;
  284. }
  285. if (record.action.type == KeytabActionType.input) {
  286. debug.onMsg('input: ${record.action.value}');
  287. final input = keytabUnescape(record.action.value);
  288. onInput(input);
  289. return;
  290. }
  291. }
  292. if (ctrl) {
  293. if (key.index >= TerminalKey.keyA.index &&
  294. key.index <= TerminalKey.keyZ.index) {
  295. final input = key.index - TerminalKey.keyA.index + 1;
  296. onInput(String.fromCharCode(input));
  297. return;
  298. }
  299. }
  300. if (alt) {
  301. if (key.index >= TerminalKey.keyA.index &&
  302. key.index <= TerminalKey.keyZ.index) {
  303. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  304. onInput(String.fromCharCodes(input));
  305. return;
  306. }
  307. }
  308. }
  309. String? getSelectedText() {
  310. if (selection.isEmpty) {
  311. return null;
  312. }
  313. final builder = StringBuffer();
  314. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  315. if (row >= buffer.height) {
  316. break;
  317. }
  318. final line = buffer.lines[row];
  319. var xStart = 0;
  320. var xEnd = viewWidth - 1;
  321. if (row == selection.start!.y) {
  322. xStart = selection.start!.x;
  323. } else if (!line.isWrapped) {
  324. builder.write("\n");
  325. }
  326. if (row == selection.end!.y) {
  327. xEnd = selection.end!.x;
  328. }
  329. for (var col = xStart; col <= xEnd; col++) {
  330. if (col >= line.length) {
  331. break;
  332. }
  333. final cell = line.getCell(col);
  334. if (cell.width == 0) {
  335. continue;
  336. }
  337. var char = line.getCell(col).codePoint;
  338. if (char == null || char == 0x00) {
  339. const blank = 32;
  340. char = blank;
  341. }
  342. builder.writeCharCode(char);
  343. }
  344. }
  345. return builder.toString();
  346. }
  347. void paste(String data) {
  348. if (bracketedPasteMode) {
  349. data = '\x1b[200~$data\x1b[201~';
  350. }
  351. onInput(data);
  352. }
  353. int get _tabIndexFromCursor {
  354. var index = buffer.cursorX;
  355. if (buffer.cursorX == viewWidth) {
  356. index = 0;
  357. }
  358. return index;
  359. }
  360. void tabSetAtCursor() {
  361. tabs.setAt(_tabIndexFromCursor);
  362. }
  363. void tabClearAtCursor() {
  364. tabs.clearAt(_tabIndexFromCursor);
  365. }
  366. void tab() {
  367. while (buffer.cursorX < viewWidth) {
  368. buffer.write(' ');
  369. if (tabs.isSetAt(buffer.cursorX)) {
  370. break;
  371. }
  372. }
  373. }
  374. }