terminal.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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/mouse/selection.dart';
  6. import 'package:xterm/input/keys.dart';
  7. import 'package:xterm/input/keytab/keytab.dart';
  8. import 'package:xterm/input/keytab/keytab_escape.dart';
  9. import 'package:xterm/input/keytab/keytab_record.dart';
  10. import 'package:xterm/mouse/mouse_mode.dart';
  11. import 'package:xterm/terminal/ansi.dart';
  12. import 'package:xterm/terminal/cursor.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_color.dart';
  17. import 'package:xterm/theme/terminal_theme.dart';
  18. import 'package:xterm/theme/terminal_themes.dart';
  19. import 'package:xterm/util/debug_handler.dart';
  20. import 'package:xterm/util/observable.dart';
  21. typedef TerminalInputHandler = void Function(String);
  22. typedef BellHandler = void Function();
  23. typedef TitleChangeHandler = void Function(String);
  24. typedef IconChangeHandler = void Function(String);
  25. void _defaultInputHandler(String _) {}
  26. void _defaultBellHandler() {}
  27. void _defaultTitleHandler(String _) {}
  28. void _defaultIconHandler(String _) {}
  29. class Terminal with Observable {
  30. Terminal({
  31. this.onInput = _defaultInputHandler,
  32. this.onBell = _defaultBellHandler,
  33. this.onTitleChange = _defaultTitleHandler,
  34. this.onIconChange = _defaultIconHandler,
  35. this.platform = PlatformBehaviors.unix,
  36. this.theme = TerminalThemes.defaultTheme,
  37. required int maxLines,
  38. }) : _maxLines = maxLines {
  39. _mainBuffer = Buffer(this);
  40. _altBuffer = Buffer(this);
  41. _buffer = _mainBuffer;
  42. cursor = Cursor(
  43. fg: theme.foreground,
  44. bg: TerminalColor.transparent, // transparent
  45. flags: 0x00, // no flags
  46. );
  47. tabs.reset();
  48. }
  49. bool _dirty = false;
  50. bool get dirty {
  51. if (_dirty) {
  52. _dirty = false;
  53. return true;
  54. } else {
  55. return false;
  56. }
  57. }
  58. int _maxLines;
  59. int get maxLines {
  60. return max(viewHeight, _maxLines);
  61. }
  62. int _viewWidth = 80;
  63. int _viewHeight = 25;
  64. int get viewWidth => _viewWidth;
  65. int get viewHeight => _viewHeight;
  66. int get visibleHeight => min(_viewHeight, buffer.height);
  67. int get invisibleHeight => buffer.height - visibleHeight;
  68. /// ### Insert/Replace Mode (IRM)
  69. ///
  70. /// The terminal displays received characters at the cursor position.
  71. /// Insert/Replace mode determines how the terminal adds characters to the
  72. /// screen. Insert mode displays the new character and moves previously
  73. /// displayed characters to the right. Replace mode adds characters by
  74. /// replacing the character at the cursor position.
  75. ///
  76. /// You can set or reset insert/replace mode as follows.
  77. bool _replaceMode = true;
  78. bool _screenMode = false; // DECSCNM (black on white background)
  79. bool _autoWrapMode = true;
  80. bool get autoWrapMode => _autoWrapMode;
  81. /// ### DECOM – Origin Mode (DEC Private)
  82. ///
  83. /// This is a private parameter applicable to set mode (SM) and reset mode
  84. /// (RM) control sequences. The reset state causes the origin to be at the
  85. /// upper-left character position on the screen. Line and column numbers are,
  86. /// therefore, independent of current margin settings. The cursor may be
  87. /// positioned outside the margins with a cursor position (CUP) or horizontal
  88. /// and vertical position (HVP) control.
  89. ///
  90. /// The set state causes the origin to be at the upper-left character position
  91. /// within the margins. Line and column numbers are therefore relative to the
  92. /// current margin settings. The cursor is not allowed to be positioned
  93. /// outside the margins.
  94. ///
  95. /// The cursor is moved to the new home position when this mode is set or
  96. /// reset.
  97. ///
  98. /// Lines and columns are numbered consecutively, with the origin being line
  99. /// 1, column 1.
  100. bool get originMode => _originMode;
  101. bool _originMode = false;
  102. /// ### LNM – Line Feed/New Line Mode
  103. ///
  104. /// This is a parameter applicable to set mode (SM) and reset mode (RM)
  105. /// control sequences. The reset state causes the interpretation of the line
  106. /// feed (LF), defined in ANSI Standard X3.4-1977, to imply only vertical
  107. /// movement of the active position and causes the RETURN key (CR) to send the
  108. /// single code CR. The set state causes the LF to imply movement to the first
  109. /// position of the following line and causes the RETURN key to send the two
  110. /// codes (CR, LF). This is the New Line (NL) option.
  111. ///
  112. /// This mode does not affect the index (IND), or next line (NEL) format
  113. /// effectors.
  114. bool get lineFeedMode => _lineFeedMode;
  115. bool _lineFeedMode = true;
  116. /// See: [lineFeedMode]
  117. bool get newLineMode => !_lineFeedMode;
  118. /// ### Bracketed Paste Mode
  119. ///
  120. /// When bracketed paste mode is set, pasted text is bracketed with control
  121. /// sequences so that the program can differentiate pasted text from typed-in
  122. /// text. When bracketed paste mode is set, the program will receive: `ESC
  123. /// [200 ~`, followed by the pasted text, followed by `ESC [ 201 ~`.
  124. bool get bracketedPasteMode => _bracketedPasteMode;
  125. bool _bracketedPasteMode = false;
  126. bool _showCursor = true;
  127. bool get showCursor => _showCursor;
  128. /// DECCKM – Cursor Keys Mode (DEC Private)
  129. ///
  130. /// This is a private parameter applicable to set mode (SM) and reset mode
  131. /// (RM) control sequences. This mode is only effective when the terminal is
  132. /// in keypad application mode (see DECKPAM) and the ANSI/VT52 mode (DECANM)
  133. /// is set (see DECANM). Under these conditions, if the cursor key mode is
  134. /// reset, the four cursor function keys will send ANSI cursor control
  135. /// commands. If cursor key mode is set, the four cursor function keys will
  136. /// send application functions.
  137. bool get applicationCursorKeys => _applicationCursorKeys;
  138. bool _applicationCursorKeys = false;
  139. bool _blinkingCursor = true;
  140. bool get blinkingCursor => _blinkingCursor;
  141. late Buffer _buffer;
  142. late Buffer _mainBuffer;
  143. late Buffer _altBuffer;
  144. /// Queue of input characters. addLast() to add, removeFirst() to consume.
  145. final _queue = ListQueue<int>(81920);
  146. bool _slowMotion = false;
  147. bool get slowMotion => _slowMotion;
  148. MouseMode _mouseMode = MouseMode.none;
  149. MouseMode get mouseMode => _mouseMode;
  150. final TerminalTheme theme;
  151. // final cellAttr = CellAttrTemplate();
  152. late final Cursor cursor;
  153. final keytab = Keytab.defaultKeytab();
  154. final selection = Selection();
  155. final tabs = Tabs();
  156. final debug = DebugHandler();
  157. final TerminalInputHandler onInput;
  158. final BellHandler onBell;
  159. final TitleChangeHandler onTitleChange;
  160. final IconChangeHandler onIconChange;
  161. final PlatformBehavior platform;
  162. Buffer get buffer {
  163. return _buffer;
  164. }
  165. int get cursorX => buffer.cursorX;
  166. int get cursorY => buffer.cursorY;
  167. int get scrollOffset => buffer.scrollOffsetFromBottom;
  168. void setScrollOffsetFromBottom(int scrollOffset) {
  169. final oldOffset = _buffer.scrollOffsetFromBottom;
  170. _buffer.setScrollOffsetFromBottom(scrollOffset);
  171. if (oldOffset != scrollOffset) {
  172. _dirty = true;
  173. refresh();
  174. }
  175. }
  176. /// Writes data to the terminal. Terminal sequences and special characters are
  177. /// interpreted.
  178. ///
  179. /// See also: [Buffer.write]
  180. void write(String text) {
  181. _queue.addAll(text.runes);
  182. _processInput();
  183. refresh();
  184. }
  185. /// Writes data to the terminal. Special characters are interpreted.
  186. ///
  187. /// See also: [Buffer.writeChar]
  188. void writeChar(int codePoint) {
  189. _queue.addLast(codePoint);
  190. _processInput();
  191. refresh();
  192. }
  193. List<BufferLine> getVisibleLines() {
  194. return _buffer.getVisibleLines();
  195. }
  196. void _processInput() {
  197. while (_queue.isNotEmpty) {
  198. // if (_slowMotion) {
  199. // await Future.delayed(Duration(milliseconds: 100));
  200. // }
  201. const esc = 0x1b;
  202. final char = _queue.removeFirst();
  203. if (char == esc) {
  204. final finished = ansiHandler(_queue, this);
  205. // Terminal sequence in the queue is not completed, and no charater is
  206. // consumed.
  207. if (!finished) {
  208. _queue.addFirst(esc);
  209. break;
  210. }
  211. continue;
  212. }
  213. _processChar(char);
  214. }
  215. }
  216. void _processChar(int codePoint) {
  217. // If the character doesn't have special effect. Write it directly to the
  218. // buffer.
  219. if (codePoint > sbcMaxCodePoint) {
  220. debug.onChar(codePoint);
  221. _buffer.writeChar(codePoint);
  222. return;
  223. }
  224. // The character may have special effect.
  225. final sbcHandler = sbcHandlers[codePoint];
  226. if (sbcHandler != null) {
  227. debug.onSbc(codePoint);
  228. sbcHandler(codePoint, this);
  229. }
  230. }
  231. void refresh() {
  232. _dirty = true;
  233. notifyListeners();
  234. }
  235. void setSlowMotion(bool enabled) {
  236. _slowMotion = enabled;
  237. }
  238. void setOriginMode(bool enabled) {
  239. _originMode = enabled;
  240. buffer.setPosition(0, 0);
  241. }
  242. void setScreenMode(bool enabled) {
  243. _screenMode = true;
  244. }
  245. void setApplicationCursorKeys(bool enabled) {
  246. _applicationCursorKeys = enabled;
  247. }
  248. void setShowCursor(bool showCursor) {
  249. _showCursor = showCursor;
  250. }
  251. void setBlinkingCursor(bool enabled) {
  252. _blinkingCursor = enabled;
  253. }
  254. void setAutoWrapMode(bool enabled) {
  255. _autoWrapMode = enabled;
  256. }
  257. void setBracketedPasteMode(bool enabled) {
  258. _bracketedPasteMode = enabled;
  259. }
  260. void setInsertMode() {
  261. _replaceMode = false;
  262. }
  263. void setReplaceMode() {
  264. _replaceMode = true;
  265. }
  266. void setNewLineMode() {
  267. _lineFeedMode = false;
  268. }
  269. void setLineFeedMode() {
  270. _lineFeedMode = true;
  271. }
  272. void setMouseMode(MouseMode mode) {
  273. _mouseMode = mode;
  274. }
  275. void useMainBuffer() {
  276. _buffer = _mainBuffer;
  277. }
  278. void useAltBuffer() {
  279. _buffer = _altBuffer;
  280. }
  281. bool isUsingMainBuffer() {
  282. return _buffer == _mainBuffer;
  283. }
  284. bool isUsingAltBuffer() {
  285. return _buffer == _altBuffer;
  286. }
  287. /// Resize the terminal screen. [newWidth] and [newHeight] should be greater
  288. /// than 0. Text reflow is currently not implemented and will be avaliable in
  289. /// the future.
  290. void resize(int newWidth, int newHeight) {
  291. newWidth = max(newWidth, 1);
  292. newHeight = max(newHeight, 1);
  293. final oldWidth = _viewWidth;
  294. final oldHeight = _viewHeight;
  295. _viewWidth = newWidth;
  296. _viewHeight = newHeight;
  297. buffer.resize(oldWidth, oldHeight, newWidth, newHeight);
  298. // maybe reflow should happen here.
  299. if (buffer == _altBuffer) {
  300. buffer.clearScrollback();
  301. }
  302. buffer.resetVerticalMargins();
  303. }
  304. void keyInput(
  305. TerminalKey key, {
  306. bool ctrl = false,
  307. bool alt = false,
  308. bool shift = false,
  309. bool mac = false,
  310. // bool meta,
  311. }) {
  312. debug.onMsg(key);
  313. for (var record in keytab.records) {
  314. if (record.key != key) {
  315. continue;
  316. }
  317. if (record.ctrl != null && record.ctrl != ctrl) {
  318. continue;
  319. }
  320. if (record.shift != null && record.shift != shift) {
  321. continue;
  322. }
  323. if (record.alt != null && record.alt != alt) {
  324. continue;
  325. }
  326. if (record.anyModifier == true &&
  327. (ctrl != true && alt != true && shift != true)) {
  328. continue;
  329. }
  330. if (record.anyModifier == false &&
  331. !(ctrl != true && alt != true && shift != true)) {
  332. continue;
  333. }
  334. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  335. continue;
  336. }
  337. if (record.newLine != null && record.newLine != newLineMode) {
  338. continue;
  339. }
  340. if (record.appCursorKeys != null &&
  341. record.appCursorKeys != applicationCursorKeys) {
  342. continue;
  343. }
  344. if (record.mac != null && record.mac != mac) {
  345. continue;
  346. }
  347. // TODO: support VT52
  348. if (record.ansi == false) {
  349. continue;
  350. }
  351. if (record.action.type == KeytabActionType.input) {
  352. debug.onMsg('input: ${record.action.value}');
  353. final input = keytabUnescape(record.action.value);
  354. onInput(input);
  355. return;
  356. }
  357. }
  358. if (ctrl) {
  359. if (key.index >= TerminalKey.keyA.index &&
  360. key.index <= TerminalKey.keyZ.index) {
  361. final input = key.index - TerminalKey.keyA.index + 1;
  362. onInput(String.fromCharCode(input));
  363. return;
  364. }
  365. }
  366. if (alt) {
  367. if (key.index >= TerminalKey.keyA.index &&
  368. key.index <= TerminalKey.keyZ.index) {
  369. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  370. onInput(String.fromCharCodes(input));
  371. return;
  372. }
  373. }
  374. }
  375. String? getSelectedText() {
  376. if (selection.isEmpty) {
  377. return null;
  378. }
  379. final builder = StringBuffer();
  380. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  381. if (row >= buffer.height) {
  382. break;
  383. }
  384. final line = buffer.lines[row];
  385. var xStart = 0;
  386. var xEnd = viewWidth - 1;
  387. if (row == selection.start!.y) {
  388. xStart = selection.start!.x;
  389. } else if (!line.isWrapped) {
  390. builder.write("\n");
  391. }
  392. if (row == selection.end!.y) {
  393. xEnd = selection.end!.x;
  394. }
  395. for (var col = xStart; col <= xEnd; col++) {
  396. // if (col >= line.length) {
  397. // break;
  398. // }
  399. if (line.cellGetWidth(col) == 0) {
  400. continue;
  401. }
  402. var char = line.cellGetContent(col);
  403. if (char == 0x00) {
  404. const blank = 32;
  405. char = blank;
  406. }
  407. builder.writeCharCode(char);
  408. }
  409. }
  410. return builder.toString();
  411. }
  412. void paste(String data) {
  413. if (bracketedPasteMode) {
  414. data = '\x1b[200~$data\x1b[201~';
  415. }
  416. onInput(data);
  417. }
  418. void selectWord(int x, int y) {}
  419. int get _tabIndexFromCursor {
  420. var index = buffer.cursorX;
  421. if (buffer.cursorX == viewWidth) {
  422. index = 0;
  423. }
  424. return index;
  425. }
  426. void tabSetAtCursor() {
  427. tabs.setAt(_tabIndexFromCursor);
  428. }
  429. void tabClearAtCursor() {
  430. tabs.clearAt(_tabIndexFromCursor);
  431. }
  432. void tab() {
  433. while (buffer.cursorX < viewWidth) {
  434. buffer.write(' ');
  435. if (tabs.isSetAt(buffer.cursorX)) {
  436. break;
  437. }
  438. }
  439. }
  440. }