terminal.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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_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. cursor = Cursor(
  43. fg: theme.foreground,
  44. bg: 0x00000000, // 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. if (_maxLines == null) return null;
  61. return max(viewHeight, _maxLines!);
  62. }
  63. int _viewWidth = 80;
  64. int _viewHeight = 25;
  65. int get viewWidth => _viewWidth;
  66. int get viewHeight => _viewHeight;
  67. int get visibleHeight => min(_viewHeight, buffer.height);
  68. int get invisibleHeight => buffer.height - visibleHeight;
  69. /// ### Insert/Replace Mode (IRM)
  70. ///
  71. /// The terminal displays received characters at the cursor position.
  72. /// Insert/Replace mode determines how the terminal adds characters to the
  73. /// screen. Insert mode displays the new character and moves previously
  74. /// displayed characters to the right. Replace mode adds characters by
  75. /// replacing the character at the cursor position.
  76. ///
  77. /// You can set or reset insert/replace mode as follows.
  78. bool _replaceMode = true;
  79. bool _screenMode = false; // DECSCNM (black on white background)
  80. bool _autoWrapMode = true;
  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 = Queue<int>();
  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. /// Writes data to the terminal. Terminal sequences and special characters are
  169. /// interpreted.
  170. ///
  171. /// See also: [Buffer.write]
  172. void write(String text) {
  173. _queue.addAll(text.runes);
  174. _processInput();
  175. refresh();
  176. }
  177. /// Writes data to the terminal. Special characters are interpreted.
  178. ///
  179. /// See also: [Buffer.writeChar]
  180. void writeChar(int codePoint) {
  181. _queue.addLast(codePoint);
  182. _processInput();
  183. refresh();
  184. }
  185. List<BufferLine> getVisibleLines() {
  186. return _buffer.getVisibleLines();
  187. }
  188. void _processInput() {
  189. while (_queue.isNotEmpty) {
  190. // if (_slowMotion) {
  191. // await Future.delayed(Duration(milliseconds: 100));
  192. // }
  193. const esc = 0x1b;
  194. final char = _queue.removeFirst();
  195. if (char == esc) {
  196. final finished = ansiHandler(_queue, this);
  197. // Terminal sequence in the queue is not completed, and no charater is
  198. // consumed.
  199. if (!finished) {
  200. _queue.addFirst(esc);
  201. break;
  202. }
  203. continue;
  204. }
  205. _processChar(char);
  206. }
  207. }
  208. void _processChar(int codePoint) {
  209. // If the character doesn't have special effect. Write it directly to the
  210. // buffer.
  211. if (codePoint > sbcMaxCodePoint) {
  212. debug.onChar(codePoint);
  213. _buffer.writeChar(codePoint);
  214. return;
  215. }
  216. // The character may have special effect.
  217. final sbcHandler = sbcHandlers[codePoint];
  218. if (sbcHandler != null) {
  219. debug.onSbc(codePoint);
  220. sbcHandler(codePoint, this);
  221. }
  222. }
  223. void refresh() {
  224. _dirty = true;
  225. notifyListeners();
  226. }
  227. void setSlowMotion(bool enabled) {
  228. _slowMotion = enabled;
  229. }
  230. void setOriginMode(bool enabled) {
  231. _originMode = enabled;
  232. buffer.setPosition(0, 0);
  233. }
  234. void setScreenMode(bool enabled) {
  235. _screenMode = true;
  236. }
  237. void setApplicationCursorKeys(bool enabled) {
  238. _applicationCursorKeys = enabled;
  239. }
  240. void setShowCursor(bool showCursor) {
  241. _showCursor = showCursor;
  242. }
  243. void setBlinkingCursor(bool enabled) {
  244. _blinkingCursor = enabled;
  245. }
  246. void setAutoWrapMode(bool enabled) {
  247. _autoWrapMode = enabled;
  248. }
  249. void setBracketedPasteMode(bool enabled) {
  250. _bracketedPasteMode = enabled;
  251. }
  252. void setInsertMode() {
  253. _replaceMode = false;
  254. }
  255. void setReplaceMode() {
  256. _replaceMode = true;
  257. }
  258. void setNewLineMode() {
  259. _lineFeedMode = false;
  260. }
  261. void setLineFeedMode() {
  262. _lineFeedMode = true;
  263. }
  264. void setMouseMode(MouseMode mode) {
  265. _mouseMode = mode;
  266. }
  267. void useMainBuffer() {
  268. _buffer = _mainBuffer;
  269. }
  270. void useAltBuffer() {
  271. _buffer = _altBuffer;
  272. }
  273. bool isUsingMainBuffer() {
  274. return _buffer == _mainBuffer;
  275. }
  276. bool isUsingAltBuffer() {
  277. return _buffer == _altBuffer;
  278. }
  279. /// Resize the terminal screen. [newWidth] and [newHeight] should be greater
  280. /// than 0. Text reflow is currently not implemented and will be avaliable in
  281. /// the future.
  282. void resize(int newWidth, int newHeight) {
  283. newWidth = max(newWidth, 1);
  284. newHeight = max(newHeight, 1);
  285. buffer.resize(newWidth, newHeight);
  286. // maybe reflow should happen here.
  287. _viewWidth = newWidth;
  288. _viewHeight = newHeight;
  289. if (buffer == _altBuffer) {
  290. buffer.clearScrollback();
  291. }
  292. buffer.resetVerticalMargins();
  293. }
  294. void keyInput(
  295. TerminalKey key, {
  296. bool ctrl = false,
  297. bool alt = false,
  298. bool shift = false,
  299. // bool meta,
  300. }) {
  301. debug.onMsg(key);
  302. for (var record in keytab.records) {
  303. if (record.key != key) {
  304. continue;
  305. }
  306. if (record.ctrl != null && record.ctrl != ctrl) {
  307. continue;
  308. }
  309. if (record.shift != null && record.shift != shift) {
  310. continue;
  311. }
  312. if (record.alt != null && record.alt != alt) {
  313. continue;
  314. }
  315. if (record.anyModifier == true &&
  316. (ctrl != true && alt != true && shift != true)) {
  317. continue;
  318. }
  319. if (record.anyModifier == false &&
  320. !(ctrl != true && alt != true && shift != true)) {
  321. continue;
  322. }
  323. if (record.appScreen != null && record.appScreen != isUsingAltBuffer()) {
  324. continue;
  325. }
  326. if (record.newLine != null && record.newLine != newLineMode) {
  327. continue;
  328. }
  329. if (record.appCursorKeys != null &&
  330. record.appCursorKeys != applicationCursorKeys) {
  331. continue;
  332. }
  333. // TODO: support VT52
  334. if (record.ansi == false) {
  335. continue;
  336. }
  337. if (record.action.type == KeytabActionType.input) {
  338. debug.onMsg('input: ${record.action.value}');
  339. final input = keytabUnescape(record.action.value);
  340. onInput(input);
  341. return;
  342. }
  343. }
  344. if (ctrl) {
  345. if (key.index >= TerminalKey.keyA.index &&
  346. key.index <= TerminalKey.keyZ.index) {
  347. final input = key.index - TerminalKey.keyA.index + 1;
  348. onInput(String.fromCharCode(input));
  349. return;
  350. }
  351. }
  352. if (alt) {
  353. if (key.index >= TerminalKey.keyA.index &&
  354. key.index <= TerminalKey.keyZ.index) {
  355. final input = [0x1b, key.index - TerminalKey.keyA.index + 65];
  356. onInput(String.fromCharCodes(input));
  357. return;
  358. }
  359. }
  360. }
  361. String? getSelectedText() {
  362. if (selection.isEmpty) {
  363. return null;
  364. }
  365. final builder = StringBuffer();
  366. for (var row = selection.start!.y; row <= selection.end!.y; row++) {
  367. if (row >= buffer.height) {
  368. break;
  369. }
  370. final line = buffer.lines[row];
  371. var xStart = 0;
  372. var xEnd = viewWidth - 1;
  373. if (row == selection.start!.y) {
  374. xStart = selection.start!.x;
  375. } else if (!line.isWrapped) {
  376. builder.write("\n");
  377. }
  378. if (row == selection.end!.y) {
  379. xEnd = selection.end!.x;
  380. }
  381. for (var col = xStart; col <= xEnd; col++) {
  382. // if (col >= line.length) {
  383. // break;
  384. // }
  385. if (line.cellGetWidth(col) == 0) {
  386. continue;
  387. }
  388. var char = line.cellGetContent(col);
  389. if (char == 0x00) {
  390. const blank = 32;
  391. char = blank;
  392. }
  393. builder.writeCharCode(char);
  394. }
  395. }
  396. return builder.toString();
  397. }
  398. void paste(String data) {
  399. if (bracketedPasteMode) {
  400. data = '\x1b[200~$data\x1b[201~';
  401. }
  402. onInput(data);
  403. }
  404. void selectWord(int x, int y) {}
  405. int get _tabIndexFromCursor {
  406. var index = buffer.cursorX;
  407. if (buffer.cursorX == viewWidth) {
  408. index = 0;
  409. }
  410. return index;
  411. }
  412. void tabSetAtCursor() {
  413. tabs.setAt(_tabIndexFromCursor);
  414. }
  415. void tabClearAtCursor() {
  416. tabs.clearAt(_tabIndexFromCursor);
  417. }
  418. void tab() {
  419. while (buffer.cursorX < viewWidth) {
  420. buffer.write(' ');
  421. if (tabs.isSetAt(buffer.cursorX)) {
  422. break;
  423. }
  424. }
  425. }
  426. }