terminal_isolate.dart 14 KB

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