terminal_isolate.dart 13 KB

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