terminal_isolate.dart 15 KB

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