terminal_isolate.dart 16 KB

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