terminal_isolate.dart 17 KB

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