terminal_isolate.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import 'dart:async';
  2. import 'dart:isolate';
  3. import 'package:xterm/buffer/line/line.dart';
  4. import 'package:xterm/input/keys.dart';
  5. import 'package:xterm/mouse/position.dart';
  6. import 'package:xterm/mouse/selection.dart';
  7. import 'package:xterm/terminal/platform.dart';
  8. import 'package:xterm/terminal/terminal.dart';
  9. import 'package:xterm/terminal/terminal_backend.dart';
  10. import 'package:xterm/terminal/terminal_search.dart';
  11. import 'package:xterm/terminal/terminal_ui_interaction.dart';
  12. import 'package:xterm/theme/terminal_theme.dart';
  13. import 'package:xterm/theme/terminal_themes.dart';
  14. import 'package:xterm/util/event_debouncer.dart';
  15. import 'package:xterm/util/observable.dart';
  16. enum _IsolateCommand {
  17. sendPort,
  18. init,
  19. write,
  20. refresh,
  21. clearSelection,
  22. selectAll,
  23. mouseTap,
  24. mouseDoubleTap,
  25. mousePanStart,
  26. mousePanUpdate,
  27. setScrollOffsetFromBottom,
  28. resize,
  29. onInput,
  30. keyInput,
  31. requestNewStateWhenDirty,
  32. paste,
  33. terminateBackend,
  34. updateComposingString
  35. }
  36. enum _IsolateEvent {
  37. titleChanged,
  38. iconChanged,
  39. bell,
  40. notifyChange,
  41. newState,
  42. exit,
  43. }
  44. /// main entry for the terminal isolate
  45. void terminalMain(SendPort port) async {
  46. final rp = ReceivePort();
  47. port.send(rp.sendPort);
  48. Terminal? _terminal;
  49. var _needNotify = true;
  50. await for (var msg in rp) {
  51. // process incoming commands
  52. final _IsolateCommand action = msg[0];
  53. switch (action) {
  54. case _IsolateCommand.sendPort:
  55. port = msg[1];
  56. break;
  57. case _IsolateCommand.init:
  58. final TerminalInitData initData = msg[1];
  59. _terminal = Terminal(
  60. backend: initData.backend,
  61. onTitleChange: (String title) {
  62. port.send([_IsolateEvent.titleChanged, title]);
  63. },
  64. onIconChange: (String icon) {
  65. port.send([_IsolateEvent.iconChanged, icon]);
  66. },
  67. onBell: () {
  68. port.send([_IsolateEvent.bell]);
  69. },
  70. platform: initData.platform,
  71. theme: initData.theme,
  72. maxLines: initData.maxLines);
  73. _terminal.addListener(() {
  74. if (_needNotify) {
  75. port.send([_IsolateEvent.notifyChange]);
  76. _needNotify = false;
  77. }
  78. });
  79. _terminal.backendExited
  80. .then((value) => port.send([_IsolateEvent.exit, value]));
  81. port.send([_IsolateEvent.notifyChange]);
  82. break;
  83. case _IsolateCommand.write:
  84. _terminal?.write(msg[1]);
  85. break;
  86. case _IsolateCommand.refresh:
  87. _terminal?.refresh();
  88. break;
  89. case _IsolateCommand.clearSelection:
  90. _terminal?.clearSelection();
  91. break;
  92. case _IsolateCommand.selectAll:
  93. _terminal?.selectAll();
  94. break;
  95. case _IsolateCommand.mouseTap:
  96. _terminal?.onMouseTap(msg[1]);
  97. break;
  98. case _IsolateCommand.mouseDoubleTap:
  99. _terminal?.onMouseDoubleTap(msg[1]);
  100. break;
  101. case _IsolateCommand.mousePanStart:
  102. _terminal?.onPanStart(msg[1]);
  103. break;
  104. case _IsolateCommand.mousePanUpdate:
  105. _terminal?.onPanUpdate(msg[1]);
  106. break;
  107. case _IsolateCommand.setScrollOffsetFromBottom:
  108. _terminal?.setScrollOffsetFromBottom(msg[1]);
  109. break;
  110. case _IsolateCommand.resize:
  111. _terminal?.resize(msg[1], msg[2], msg[3], msg[4]);
  112. break;
  113. case _IsolateCommand.onInput:
  114. _terminal?.backend?.write(msg[1]);
  115. break;
  116. case _IsolateCommand.keyInput:
  117. _terminal?.keyInput(msg[1],
  118. ctrl: msg[2], alt: msg[3], shift: msg[4], mac: msg[5]);
  119. break;
  120. case _IsolateCommand.requestNewStateWhenDirty:
  121. if (_terminal == null) {
  122. break;
  123. }
  124. if (_terminal.dirty) {
  125. final newState = TerminalState(
  126. _terminal.scrollOffsetFromBottom,
  127. _terminal.scrollOffsetFromTop,
  128. _terminal.buffer.height,
  129. _terminal.invisibleHeight,
  130. _terminal.viewHeight,
  131. _terminal.viewWidth,
  132. _terminal.selection!,
  133. _terminal.getSelectedText(),
  134. _terminal.theme.background,
  135. _terminal.cursorX,
  136. _terminal.cursorY,
  137. _terminal.showCursor,
  138. _terminal.theme.cursor,
  139. _terminal
  140. .getVisibleLines()
  141. .map((bl) => BufferLine.withDataFrom(bl))
  142. .toList(growable: false),
  143. _terminal.composingString,
  144. _terminal.userSearchResult,
  145. _terminal.userSearchPattern,
  146. );
  147. port.send([_IsolateEvent.newState, newState]);
  148. _needNotify = true;
  149. }
  150. break;
  151. case _IsolateCommand.paste:
  152. _terminal?.paste(msg[1]);
  153. break;
  154. case _IsolateCommand.terminateBackend:
  155. _terminal?.terminateBackend();
  156. break;
  157. case _IsolateCommand.updateComposingString:
  158. _terminal?.updateComposingString(msg[1]);
  159. break;
  160. }
  161. }
  162. }
  163. /// This class holds the initialization data needed for the Terminal.
  164. /// This data has to be passed from the UI Isolate where the TerminalIsolate
  165. /// class gets instantiated into the Isolate that will run the Terminal.
  166. class TerminalInitData {
  167. PlatformBehavior platform;
  168. TerminalTheme theme;
  169. int maxLines;
  170. TerminalBackend? backend;
  171. TerminalInitData(this.backend, this.platform, this.theme, this.maxLines);
  172. }
  173. /// This class holds a complete TerminalState as needed by the UI.
  174. /// The state held here is self-contained and has no dependencies to the source
  175. /// Terminal. Therefore it can be safely transferred across Isolate boundaries.
  176. class TerminalState {
  177. int scrollOffsetFromTop;
  178. int scrollOffsetFromBottom;
  179. int bufferHeight;
  180. int invisibleHeight;
  181. int viewHeight;
  182. int viewWidth;
  183. Selection selection;
  184. String? selectedText;
  185. int backgroundColor;
  186. int cursorX;
  187. int cursorY;
  188. bool showCursor;
  189. int cursorColor;
  190. List<BufferLine> visibleLines;
  191. bool consumed = false;
  192. String composingString;
  193. TerminalSearchResult searchResult;
  194. String? userSearchPattern;
  195. TerminalState(
  196. this.scrollOffsetFromBottom,
  197. this.scrollOffsetFromTop,
  198. this.bufferHeight,
  199. this.invisibleHeight,
  200. this.viewHeight,
  201. this.viewWidth,
  202. this.selection,
  203. this.selectedText,
  204. this.backgroundColor,
  205. this.cursorX,
  206. this.cursorY,
  207. this.showCursor,
  208. this.cursorColor,
  209. this.visibleLines,
  210. this.composingString,
  211. this.searchResult,
  212. this.userSearchPattern,
  213. );
  214. }
  215. void _defaultBellHandler() {}
  216. void _defaultTitleHandler(String _) {}
  217. void _defaultIconHandler(String _) {}
  218. /// The TerminalIsolate class hosts an Isolate that runs a Terminal.
  219. /// It handles all the communication with and from the Terminal and implements
  220. /// [TerminalUiInteraction] as well as the terminal and therefore can simply
  221. /// be exchanged with a Terminal.
  222. /// This class is the preferred use of a Terminal as the Terminal logic and all
  223. /// the communication with the backend are happening outside the UI thread.
  224. ///
  225. /// There is a special constraints in using this class:
  226. /// The given backend has to be built so that it can be passed into an Isolate.
  227. ///
  228. /// This means in particular that it is not allowed to have any closures in its
  229. /// object graph.
  230. /// It is a good idea to move as much instantiation as possible into the
  231. /// [TerminalBackend.init] method that gets called after the backend instance
  232. /// has been passed and is therefore allowed to instantiate parts of the object
  233. /// graph that do contain closures.
  234. class TerminalIsolate with Observable implements TerminalUiInteraction {
  235. final _receivePort = ReceivePort();
  236. SendPort? _sendPort;
  237. late Isolate _isolate;
  238. final TerminalBackend? backend;
  239. final BellHandler onBell;
  240. final TitleChangeHandler onTitleChange;
  241. final IconChangeHandler onIconChange;
  242. final PlatformBehavior _platform;
  243. @override
  244. final TerminalTheme theme;
  245. final int maxLines;
  246. final Duration minRefreshDelay;
  247. final EventDebouncer _refreshEventDebouncer;
  248. TerminalState? _lastState;
  249. TerminalState? get lastState {
  250. return _lastState;
  251. }
  252. TerminalIsolate({
  253. this.backend,
  254. this.onBell = _defaultBellHandler,
  255. this.onTitleChange = _defaultTitleHandler,
  256. this.onIconChange = _defaultIconHandler,
  257. PlatformBehavior platform = PlatformBehaviors.unix,
  258. this.theme = TerminalThemes.defaultTheme,
  259. this.minRefreshDelay = const Duration(milliseconds: 16),
  260. required this.maxLines,
  261. }) : _platform = platform,
  262. _refreshEventDebouncer = EventDebouncer(minRefreshDelay);
  263. @override
  264. int get scrollOffsetFromBottom => _lastState!.scrollOffsetFromBottom;
  265. @override
  266. int get scrollOffsetFromTop => _lastState!.scrollOffsetFromTop;
  267. @override
  268. int get bufferHeight => _lastState!.bufferHeight;
  269. @override
  270. int get terminalHeight => _lastState!.viewHeight;
  271. @override
  272. int get terminalWidth => _lastState!.viewWidth;
  273. @override
  274. int get invisibleHeight => _lastState!.invisibleHeight;
  275. @override
  276. Selection? get selection => _lastState?.selection;
  277. @override
  278. bool get showCursor => _lastState?.showCursor ?? true;
  279. @override
  280. List<BufferLine> getVisibleLines() {
  281. if (_lastState == null) {
  282. return List<BufferLine>.empty();
  283. }
  284. return _lastState!.visibleLines;
  285. }
  286. @override
  287. int get cursorY => _lastState?.cursorY ?? 0;
  288. @override
  289. int get cursorX => _lastState?.cursorX ?? 0;
  290. @override
  291. BufferLine? get currentLine {
  292. if (_lastState == null) {
  293. return null;
  294. }
  295. int visibleLineIndex =
  296. _lastState!.cursorY - _lastState!.scrollOffsetFromTop;
  297. if (visibleLineIndex < 0) {
  298. visibleLineIndex = _lastState!.cursorY;
  299. }
  300. return _lastState!.visibleLines[visibleLineIndex];
  301. }
  302. @override
  303. int get cursorColor => _lastState?.cursorColor ?? 0;
  304. @override
  305. int get backgroundColor => _lastState?.backgroundColor ?? 0;
  306. @override
  307. bool get dirty {
  308. if (_lastState == null) {
  309. return false;
  310. }
  311. if (_lastState!.consumed) {
  312. return false;
  313. }
  314. _lastState!.consumed = true;
  315. return true;
  316. }
  317. @override
  318. PlatformBehavior get platform => _platform;
  319. @override
  320. String? get selectedText => _lastState?.selectedText;
  321. @override
  322. bool get isReady => _lastState != null;
  323. Future<void> start() async {
  324. final initialRefreshCompleted = Completer<bool>();
  325. var firstReceivePort = ReceivePort();
  326. _isolate = await Isolate.spawn(terminalMain, firstReceivePort.sendPort);
  327. _sendPort = await firstReceivePort.first;
  328. firstReceivePort.close();
  329. _sendPort!.send([_IsolateCommand.sendPort, _receivePort.sendPort]);
  330. _receivePort.listen((message) {
  331. _IsolateEvent action = message[0];
  332. switch (action) {
  333. case _IsolateEvent.bell:
  334. this.onBell();
  335. break;
  336. case _IsolateEvent.titleChanged:
  337. this.onTitleChange(message[1]);
  338. break;
  339. case _IsolateEvent.iconChanged:
  340. this.onIconChange(message[1]);
  341. break;
  342. case _IsolateEvent.notifyChange:
  343. _refreshEventDebouncer.notifyEvent(() {
  344. poll();
  345. });
  346. break;
  347. case _IsolateEvent.newState:
  348. _lastState = message[1];
  349. if (!initialRefreshCompleted.isCompleted) {
  350. initialRefreshCompleted.complete(true);
  351. }
  352. this.notifyListeners();
  353. break;
  354. case _IsolateEvent.exit:
  355. _isTerminated = true;
  356. _backendExited.complete(message[1]);
  357. break;
  358. }
  359. });
  360. _sendPort!.send([
  361. _IsolateCommand.init,
  362. TerminalInitData(this.backend, this.platform, this.theme, this.maxLines)
  363. ]);
  364. await initialRefreshCompleted.future;
  365. }
  366. void stop() {
  367. terminateBackend();
  368. _isolate.kill();
  369. }
  370. void poll() {
  371. _sendPort?.send([_IsolateCommand.requestNewStateWhenDirty]);
  372. }
  373. void refresh() {
  374. _sendPort?.send([_IsolateCommand.refresh]);
  375. }
  376. void clearSelection() {
  377. _sendPort?.send([_IsolateCommand.clearSelection]);
  378. }
  379. @override
  380. void selectAll() {
  381. _sendPort?.send([_IsolateCommand.selectAll]);
  382. }
  383. @override
  384. void onMouseTap(Position position) {
  385. _sendPort?.send([_IsolateCommand.mouseTap, position]);
  386. }
  387. @override
  388. void onMouseDoubleTap(Position position) {
  389. _sendPort?.send([_IsolateCommand.mouseDoubleTap, position]);
  390. }
  391. @override
  392. void onPanStart(Position position) {
  393. _sendPort?.send([_IsolateCommand.mousePanStart, position]);
  394. }
  395. @override
  396. void onPanUpdate(Position position) {
  397. _sendPort?.send([_IsolateCommand.mousePanUpdate, position]);
  398. }
  399. @override
  400. void setScrollOffsetFromBottom(int offset) {
  401. _sendPort?.send([_IsolateCommand.setScrollOffsetFromBottom, offset]);
  402. }
  403. @override
  404. int convertViewLineToRawLine(int viewLine) {
  405. if (_lastState == null) {
  406. return 0;
  407. }
  408. if (_lastState!.viewHeight > _lastState!.bufferHeight) {
  409. return viewLine;
  410. }
  411. return viewLine + (_lastState!.bufferHeight - _lastState!.viewHeight);
  412. }
  413. @override
  414. void write(String text) {
  415. _sendPort?.send([_IsolateCommand.write, text]);
  416. }
  417. @override
  418. void paste(String data) {
  419. _sendPort?.send([_IsolateCommand.paste, data]);
  420. }
  421. @override
  422. void resize(
  423. int newWidth, int newHeight, int newPixelWidth, int newPixelHeight) {
  424. _sendPort?.send([
  425. _IsolateCommand.resize,
  426. newWidth,
  427. newHeight,
  428. newPixelWidth,
  429. newPixelHeight
  430. ]);
  431. }
  432. @override
  433. void raiseOnInput(String text) {
  434. _sendPort?.send([_IsolateCommand.onInput, text]);
  435. }
  436. @override
  437. void keyInput(
  438. TerminalKey key, {
  439. bool ctrl = false,
  440. bool alt = false,
  441. bool shift = false,
  442. bool mac = false,
  443. // bool meta,
  444. }) {
  445. _sendPort?.send([_IsolateCommand.keyInput, key, ctrl, alt, shift, mac]);
  446. }
  447. var _isTerminated = false;
  448. final _backendExited = Completer<int>();
  449. @override
  450. Future<int> get backendExited => _backendExited.future;
  451. @override
  452. void terminateBackend() {
  453. if (_isTerminated) {
  454. return;
  455. }
  456. _isTerminated = true;
  457. _sendPort?.send([_IsolateCommand.terminateBackend]);
  458. }
  459. @override
  460. bool get isTerminated => _isTerminated;
  461. @override
  462. String get composingString => _lastState?.composingString ?? '';
  463. @override
  464. void updateComposingString(String value) {
  465. _sendPort?.send([_IsolateCommand.updateComposingString, value]);
  466. }
  467. @override
  468. TerminalSearchResult get userSearchResult =>
  469. _lastState?.searchResult ?? TerminalSearchResult.empty();
  470. @override
  471. String? get userSearchPattern => _lastState?.userSearchPattern;
  472. }