android_console.dart 2.37 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:async/async.dart';
import '../base/context.dart';
import '../base/io.dart';
import '../convert.dart';

/// Default factory that creates a real Android console connection.
final AndroidConsoleSocketFactory _kAndroidConsoleSocketFactory = (String host, int port) => Socket.connect( host,  port);

/// Currently active implementation of the AndroidConsoleFactory.
///
/// The default implementation will create real connections to a device.
/// Override this in tests with an implementation that returns mock responses.
AndroidConsoleSocketFactory get androidConsoleSocketFactory => context.get<AndroidConsoleSocketFactory>() ?? _kAndroidConsoleSocketFactory;

typedef AndroidConsoleSocketFactory = Future<Socket> Function(String host, int port);

/// Creates a console connection to an Android emulator that can be used to run
/// commands such as "avd name" which are not available to ADB.
///
/// See documentation at
/// https://developer.android.com/studio/run/emulator-console
class AndroidConsole {
  AndroidConsole(this._socket);

  Socket _socket;
  StreamQueue<String> _queue;

  Future<void> connect() async {
    assert(_socket != null);
    assert(_queue == null);

    _queue = StreamQueue<String>(_socket.asyncMap(ascii.decode));

    // Discard any initial connection text.
    await _readResponse();
  }

  Future<String> getAvdName() async {
45 46 47
    if (_queue == null) {
      return null;
    }
48 49 50 51 52
    _write('avd name\n');
    return _readResponse();
  }

  void destroy() {
53 54 55
    _socket?.destroy();
    _socket = null;
    _queue = null;
56 57 58
  }

  Future<String> _readResponse() async {
59 60 61
    if (_queue == null) {
      return null;
    }
62 63
    final StringBuffer output = StringBuffer();
    while (true) {
64 65 66 67
      if (!await _queue.hasNext) {
        destroy();
        return null;
      }
68 69
      final String text = await _queue.next;
      final String trimmedText = text.trim();
70
      if (trimmedText == 'OK') {
71
        break;
72
      }
73 74 75 76 77 78 79 80 81 82
      if (trimmedText.endsWith('\nOK')) {
        output.write(trimmedText.substring(0, trimmedText.length - 3));
        break;
      }
      output.write(text);
    }
    return output.toString().trim();
  }

  void _write(String text) {
83
    _socket?.add(ascii.encode(text));
84 85
  }
}