terminal.dart 14 KB

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