terminal_isolate.dart 13 KB

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