terminal_isolate.dart 14 KB

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