terminal_isolate.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. final TerminalBackend? backend;
  267. final BellHandler onBell;
  268. final TitleChangeHandler onTitleChange;
  269. final IconChangeHandler onIconChange;
  270. final PlatformBehavior _platform;
  271. @override
  272. final TerminalTheme theme;
  273. final int maxLines;
  274. final Duration minRefreshDelay;
  275. final EventDebouncer _refreshEventDebouncer;
  276. TerminalState? _lastState;
  277. TerminalState? get lastState {
  278. return _lastState;
  279. }
  280. TerminalIsolate({
  281. this.backend,
  282. this.onBell = _defaultBellHandler,
  283. this.onTitleChange = _defaultTitleHandler,
  284. this.onIconChange = _defaultIconHandler,
  285. PlatformBehavior platform = PlatformBehaviors.unix,
  286. this.theme = TerminalThemes.defaultTheme,
  287. this.minRefreshDelay = const Duration(milliseconds: 16),
  288. required this.maxLines,
  289. }) : _platform = platform,
  290. _refreshEventDebouncer = EventDebouncer(minRefreshDelay);
  291. @override
  292. int get scrollOffsetFromBottom => _lastState!.scrollOffsetFromBottom;
  293. @override
  294. int get scrollOffsetFromTop => _lastState!.scrollOffsetFromTop;
  295. @override
  296. int get bufferHeight => _lastState!.bufferHeight;
  297. @override
  298. int get terminalHeight => _lastState!.viewHeight;
  299. @override
  300. int get terminalWidth => _lastState!.viewWidth;
  301. @override
  302. int get invisibleHeight => _lastState!.invisibleHeight;
  303. @override
  304. Selection? get selection => _lastState?.selection;
  305. @override
  306. bool get showCursor => _lastState?.showCursor ?? true;
  307. @override
  308. List<BufferLine> getVisibleLines() {
  309. if (_lastState == null) {
  310. return List<BufferLine>.empty();
  311. }
  312. return _lastState!.visibleLines;
  313. }
  314. @override
  315. int get cursorY => _lastState?.cursorY ?? 0;
  316. @override
  317. int get cursorX => _lastState?.cursorX ?? 0;
  318. @override
  319. BufferLine? get currentLine {
  320. if (_lastState == null) {
  321. return null;
  322. }
  323. int visibleLineIndex =
  324. _lastState!.cursorY - _lastState!.scrollOffsetFromTop;
  325. if (visibleLineIndex < 0) {
  326. visibleLineIndex = _lastState!.cursorY;
  327. }
  328. return _lastState!.visibleLines[visibleLineIndex];
  329. }
  330. @override
  331. int get cursorColor => _lastState?.cursorColor ?? 0;
  332. @override
  333. int get backgroundColor => _lastState?.backgroundColor ?? 0;
  334. @override
  335. bool get dirty {
  336. if (_lastState == null) {
  337. return false;
  338. }
  339. if (_lastState!.consumed) {
  340. return false;
  341. }
  342. _lastState!.consumed = true;
  343. return true;
  344. }
  345. @override
  346. PlatformBehavior get platform => _platform;
  347. @override
  348. String? get selectedText => _lastState?.selectedText;
  349. @override
  350. bool get isReady => _lastState != null;
  351. Future<void> start() async {
  352. final initialRefreshCompleted = Completer<bool>();
  353. var firstReceivePort = ReceivePort();
  354. _isolate = await Isolate.spawn(terminalMain, firstReceivePort.sendPort);
  355. _sendPort = await firstReceivePort.first;
  356. firstReceivePort.close();
  357. _sendPort!.send([_IsolateCommand.sendPort, _receivePort.sendPort]);
  358. _receivePort.listen((message) {
  359. _IsolateEvent action = message[0];
  360. switch (action) {
  361. case _IsolateEvent.bell:
  362. this.onBell();
  363. break;
  364. case _IsolateEvent.titleChanged:
  365. this.onTitleChange(message[1]);
  366. break;
  367. case _IsolateEvent.iconChanged:
  368. this.onIconChange(message[1]);
  369. break;
  370. case _IsolateEvent.notifyChange:
  371. _refreshEventDebouncer.notifyEvent(() {
  372. poll();
  373. });
  374. break;
  375. case _IsolateEvent.newState:
  376. _lastState = message[1];
  377. if (!initialRefreshCompleted.isCompleted) {
  378. initialRefreshCompleted.complete(true);
  379. }
  380. this.notifyListeners();
  381. break;
  382. case _IsolateEvent.exit:
  383. _isTerminated = true;
  384. _backendExited.complete(message[1]);
  385. break;
  386. }
  387. });
  388. _sendPort!.send([
  389. _IsolateCommand.init,
  390. TerminalInitData(this.backend, this.platform, this.theme, this.maxLines)
  391. ]);
  392. await initialRefreshCompleted.future;
  393. }
  394. void stop() {
  395. terminateBackend();
  396. _isolate.kill();
  397. }
  398. void poll() {
  399. _sendPort?.send([_IsolateCommand.requestNewStateWhenDirty]);
  400. }
  401. void refresh() {
  402. _sendPort?.send([_IsolateCommand.refresh]);
  403. }
  404. void clearSelection() {
  405. _sendPort?.send([_IsolateCommand.clearSelection]);
  406. }
  407. @override
  408. void selectAll() {
  409. _sendPort?.send([_IsolateCommand.selectAll]);
  410. }
  411. @override
  412. void onMouseTap(Position position) {
  413. _sendPort?.send([_IsolateCommand.mouseTap, position]);
  414. }
  415. @override
  416. void onMouseDoubleTap(Position position) {
  417. _sendPort?.send([_IsolateCommand.mouseDoubleTap, position]);
  418. }
  419. @override
  420. void onPanStart(Position position) {
  421. _sendPort?.send([_IsolateCommand.mousePanStart, position]);
  422. }
  423. @override
  424. void onPanUpdate(Position position) {
  425. _sendPort?.send([_IsolateCommand.mousePanUpdate, position]);
  426. }
  427. @override
  428. void setScrollOffsetFromBottom(int offset) {
  429. _sendPort?.send([_IsolateCommand.setScrollOffsetFromBottom, offset]);
  430. }
  431. @override
  432. int convertViewLineToRawLine(int viewLine) {
  433. if (_lastState == null) {
  434. return 0;
  435. }
  436. if (_lastState!.viewHeight > _lastState!.bufferHeight) {
  437. return viewLine;
  438. }
  439. return viewLine + (_lastState!.bufferHeight - _lastState!.viewHeight);
  440. }
  441. @override
  442. void write(String text) {
  443. _sendPort?.send([_IsolateCommand.write, text]);
  444. }
  445. @override
  446. void paste(String data) {
  447. _sendPort?.send([_IsolateCommand.paste, data]);
  448. }
  449. @override
  450. void resize(
  451. int newWidth, int newHeight, int newPixelWidth, int newPixelHeight) {
  452. _sendPort?.send([
  453. _IsolateCommand.resize,
  454. newWidth,
  455. newHeight,
  456. newPixelWidth,
  457. newPixelHeight
  458. ]);
  459. }
  460. @override
  461. void raiseOnInput(String text) {
  462. _sendPort?.send([_IsolateCommand.onInput, text]);
  463. }
  464. @override
  465. void keyInput(
  466. TerminalKey key, {
  467. bool ctrl = false,
  468. bool alt = false,
  469. bool shift = false,
  470. bool mac = false,
  471. // bool meta,
  472. String? character,
  473. }) {
  474. _sendPort?.send(
  475. [_IsolateCommand.keyInput, key, ctrl, alt, shift, mac, character]);
  476. }
  477. var _isTerminated = false;
  478. final _backendExited = Completer<int>();
  479. @override
  480. Future<int> get backendExited => _backendExited.future;
  481. @override
  482. void terminateBackend() {
  483. if (_isTerminated) {
  484. return;
  485. }
  486. _isTerminated = true;
  487. _sendPort?.send([_IsolateCommand.terminateBackend]);
  488. }
  489. @override
  490. bool get isTerminated => _isTerminated;
  491. @override
  492. String get composingString => _lastState?.composingString ?? '';
  493. @override
  494. void updateComposingString(String value) {
  495. _sendPort?.send([_IsolateCommand.updateComposingString, value]);
  496. }
  497. @override
  498. TerminalSearchResult get userSearchResult =>
  499. _lastState?.searchResult ?? TerminalSearchResult.empty();
  500. @override
  501. int get numberOfSearchHits => userSearchResult.allHits.length;
  502. @override
  503. int? get currentSearchHit => userSearchResult.currentSearchHit;
  504. @override
  505. void set currentSearchHit(int? currentSearchHit) {
  506. _sendPort?.send([_IsolateCommand.updateCurrentSearchHit, currentSearchHit]);
  507. }
  508. @override
  509. TerminalSearchOptions get userSearchOptions =>
  510. _lastState?.userSearchOptions ?? TerminalSearchOptions();
  511. @override
  512. void set userSearchOptions(TerminalSearchOptions options) {
  513. _sendPort?.send([_IsolateCommand.updateSearchOptions, options]);
  514. }
  515. @override
  516. String? get userSearchPattern => _lastState?.userSearchPattern;
  517. @override
  518. void set userSearchPattern(String? newValue) {
  519. _sendPort?.send([_IsolateCommand.updateSearchPattern, newValue]);
  520. }
  521. @override
  522. bool get isUserSearchActive => _lastState?.isUserSearchActive ?? false;
  523. @override
  524. void set isUserSearchActive(bool isUserSearchActive) {
  525. _sendPort
  526. ?.send([_IsolateCommand.updateIsUserSearchActive, isUserSearchActive]);
  527. }
  528. }