terminal_isolate.dart 16 KB

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