terminal.dart 13 KB

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