terminal_isolate.dart 16 KB

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