terminal.dart 14 KB

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