terminal_isolate.dart 13 KB

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