Просмотр исходного кода

Sample uses TerminalIsolate and a FakeBackend

devmil 4 лет назад
Родитель
Сommit
1c617ca3de
1 измененных файлов с 52 добавлено и 19 удалено
  1. 52 19
      example/lib/main.dart

+ 52 - 19
example/lib/main.dart

@@ -1,3 +1,5 @@
+import 'dart:async';
+
 import 'package:flutter/material.dart';
 import 'package:xterm/flutter.dart';
 import 'package:xterm/xterm.dart';
@@ -21,44 +23,75 @@ class MyApp extends StatelessWidget {
 }
 
 class MyHomePage extends StatefulWidget {
-  MyHomePage({Key key}) : super(key: key);
+  MyHomePage({Key? key}) : super(key: key);
 
   @override
   _MyHomePageState createState() => _MyHomePageState();
 }
 
-class _MyHomePageState extends State<MyHomePage> {
-  Terminal terminal;
+class FakeTerminalBackend implements TerminalBackend {
+  late Completer<int> _exitCodeCompleter;
+  // ignore: close_sinks
+  late StreamController<String> _outStream;
+
+  FakeTerminalBackend();
 
   @override
-  void initState() {
-    super.initState();
-    terminal = Terminal(
-      onInput: onInput,
-      maxLines: 10000,
-    );
-    terminal.write('xterm.dart demo');
-    terminal.write('\r\n');
-    terminal.write('\$ ');
+  Future<int> get exitCode => _exitCodeCompleter.future;
+
+  @override
+  void init() {
+    _exitCodeCompleter = Completer<int>();
+    _outStream = StreamController<String>();
+    _outStream.sink.add('xterm.dart demo');
+    _outStream.sink.add('\r\n');
+    _outStream.sink.add('\$ ');
+  }
+
+  @override
+  Stream<String> get out => _outStream.stream;
+
+  @override
+  void resize(int width, int height) {
+    // NOOP
   }
 
-  void onInput(String input) {
+  @override
+  void write(String input) {
+    if (input.length <= 0) {
+      return;
+    }
     // in a "real" terminal emulation you would connect onInput to the backend
     // (like a pty or ssh connection) that then handles the changes in the
     // terminal.
     // As we don't have a connected backend here we simulate the changes by
     // directly writing to the terminal.
     if (input == '\r') {
-      terminal.write('\r\n');
-      terminal.write('\$ ');
+      _outStream.sink.add('\r\n');
+      _outStream.sink.add('\$ ');
     } else if (input.codeUnitAt(0) == 127) {
-      terminal.buffer.eraseCharacters(1);
-      terminal.buffer.backspace();
-      terminal.refresh();
+      // Backspace handling
+      _outStream.sink.add('\b \b');
     } else {
-      terminal.write(input);
+      _outStream.sink.add(input);
     }
   }
+}
+
+class _MyHomePageState extends State<MyHomePage> {
+  late TerminalIsolate terminal;
+
+  @override
+  void initState() {
+    super.initState();
+    terminal = TerminalIsolate(
+      backend: FakeTerminalBackend(),
+      maxLines: 10000,
+    );
+    terminal.start();
+  }
+
+  void onInput(String input) {}
 
   @override
   Widget build(BuildContext context) {