terminal_isolate.dart 14 KB

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