terminal.dart 8.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7 8 9
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';

10
import '../convert.dart';
11
import '../globals.dart' as globals;
12
import 'context.dart';
13
import 'io.dart' as io;
14
import 'logger.dart';
15

16 17 18 19 20 21 22 23 24 25
enum TerminalColor {
  red,
  green,
  blue,
  cyan,
  yellow,
  magenta,
  grey,
}

26 27
/// Warning mark to use in stdout or stderr.
String get warningMark {
28
  return globals.terminal.bolden(globals.terminal.color('[!]', TerminalColor.red));
29 30 31 32
}

/// Success mark to use in stdout.
String get successMark {
33
  return globals.terminal.bolden(globals.terminal.color('✓', TerminalColor.green));
34 35
}

36 37 38 39
OutputPreferences get outputPreferences {
  return context?.get<OutputPreferences>() ?? _defaultOutputPreferences;
}
final OutputPreferences _defaultOutputPreferences = OutputPreferences();
40 41 42 43 44 45 46 47

/// A class that contains the context settings for command text output to the
/// console.
class OutputPreferences {
  OutputPreferences({
    bool wrapText,
    int wrapColumn,
    bool showColor,
48
  }) : wrapText = wrapText ?? globals.stdio.hasTerminal,
49
       _overrideWrapColumn = wrapColumn,
50
       showColor = showColor ?? globals.platform.stdoutSupportsAnsi ?? false;
51

52
  /// A version of this class for use in tests.
53 54
  OutputPreferences.test({this.wrapText = false, int wrapColumn = kDefaultTerminalColumns, this.showColor = false})
    : _overrideWrapColumn = wrapColumn;
55

56 57 58 59 60
  /// If [wrapText] is true, then any text sent to the context's [Logger]
  /// instance (e.g. from the [printError] or [printStatus] functions) will be
  /// wrapped (newlines added between words) to be no longer than the
  /// [wrapColumn] specifies. Defaults to true if there is a terminal. To
  /// determine if there's a terminal, [OutputPreferences] asks the context's
61
  /// stdio.
62 63
  final bool wrapText;

64 65 66 67
  /// The terminal width used by the [wrapText] function if there is no terminal
  /// attached to [io.Stdio], --wrap is on, and --wrap-columns was not specified.
  static const int kDefaultTerminalColumns = 100;

68 69 70 71
  /// The column at which output sent to the context's [Logger] instance
  /// (e.g. from the [printError] or [printStatus] functions) will be wrapped.
  /// Ignored if [wrapText] is false. Defaults to the width of the output
  /// terminal, or to [kDefaultTerminalColumns] if not writing to a terminal.
72 73
  final int _overrideWrapColumn;
  int get wrapColumn {
74
    return _overrideWrapColumn ?? globals.stdio.terminalColumns ?? kDefaultTerminalColumns;
75
  }
76 77 78 79 80 81 82 83 84 85 86 87

  /// Whether or not to output ANSI color codes when writing to the output
  /// terminal. Defaults to whatever [platform.stdoutSupportsAnsi] says if
  /// writing to a terminal, and false otherwise.
  final bool showColor;

  @override
  String toString() {
    return '$runtimeType[wrapText: $wrapText, wrapColumn: $wrapColumn, showColor: $showColor]';
  }
}

88
class AnsiTerminal {
89 90 91 92 93 94 95
  AnsiTerminal({@required io.Stdio stdio, @required Platform platform})
    : _stdio = stdio,
      _platform = platform;

  final io.Stdio _stdio;
  final Platform _platform;

96
  static const String bold = '\u001B[1m';
97 98 99
  static const String resetAll = '\u001B[0m';
  static const String resetColor = '\u001B[39m';
  static const String resetBold = '\u001B[22m';
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  static const String clear = '\u001B[2J\u001B[H';

  static const String red = '\u001b[31m';
  static const String green = '\u001b[32m';
  static const String blue = '\u001b[34m';
  static const String cyan = '\u001b[36m';
  static const String magenta = '\u001b[35m';
  static const String yellow = '\u001b[33m';
  static const String grey = '\u001b[1;30m';

  static const Map<TerminalColor, String> _colorMap = <TerminalColor, String>{
    TerminalColor.red: red,
    TerminalColor.green: green,
    TerminalColor.blue: blue,
    TerminalColor.cyan: cyan,
    TerminalColor.magenta: magenta,
    TerminalColor.yellow: yellow,
    TerminalColor.grey: grey,
  };
119

120 121
  static String colorCode(TerminalColor color) => _colorMap[color];

122 123
  bool get supportsColor => _platform.stdoutSupportsAnsi ?? false;

124
  final RegExp _boldControls = RegExp('(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})');
125

126 127 128 129 130
  /// Whether we are interacting with the flutter tool via the terminal.
  ///
  /// If not set, defaults to false.
  bool usesTerminalUi = false;

131
  String bolden(String message) {
132
    assert(message != null);
133
    if (!supportsColor || message.isEmpty) {
134
      return message;
135
    }
136
    final StringBuffer buffer = StringBuffer();
137 138 139 140 141 142 143
    for (String line in message.split('\n')) {
      // If there were bolds or resetBolds in the string before, then nuke them:
      // they're redundant. This prevents previously embedded resets from
      // stopping the boldness.
      line = line.replaceAll(_boldControls, '');
      buffer.writeln('$bold$line$resetBold');
    }
144 145 146 147 148 149 150
    final String result = buffer.toString();
    // avoid introducing a new newline to the emboldened text
    return (!message.endsWith('\n') && result.endsWith('\n'))
        ? result.substring(0, result.length - 1)
        : result;
  }

151 152
  String color(String message, TerminalColor color) {
    assert(message != null);
153
    if (!supportsColor || color == null || message.isEmpty) {
154
      return message;
155
    }
156
    final StringBuffer buffer = StringBuffer();
157 158 159 160 161 162 163 164
    final String colorCodes = _colorMap[color];
    for (String line in message.split('\n')) {
      // If there were resets in the string before, then keep them, but
      // restart the color right after. This prevents embedded resets from
      // stopping the colors, and allows nesting of colors.
      line = line.replaceAll(resetColor, '$resetColor$colorCodes');
      buffer.writeln('$colorCodes$line$resetColor');
    }
165 166 167 168 169 170 171 172
    final String result = buffer.toString();
    // avoid introducing a new newline to the colored text
    return (!message.endsWith('\n') && result.endsWith('\n'))
        ? result.substring(0, result.length - 1)
        : result;
  }

  String clearScreen() => supportsColor ? clear : '\n\n';
173 174

  set singleCharMode(bool value) {
175
    if (!_stdio.stdinHasTerminal) {
176 177
      return;
    }
178
    final io.Stdin stdin = _stdio.stdin as io.Stdin;
179 180 181 182 183 184 185
    // The order of setting lineMode and echoMode is important on Windows.
    if (value) {
      stdin.echoMode = false;
      stdin.lineMode = false;
    } else {
      stdin.lineMode = true;
      stdin.echoMode = true;
186 187 188 189 190 191 192 193
    }
  }

  Stream<String> _broadcastStdInString;

  /// Return keystrokes from the console.
  ///
  /// Useful when the console is in [singleCharMode].
194
  Stream<String> get keystrokes {
195
    _broadcastStdInString ??= _stdio.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream();
196 197 198
    return _broadcastStdInString;
  }

199 200
  /// Prompts the user to input a character within a given list. Re-prompts if
  /// entered character is not in the list.
201
  ///
202 203 204
  /// The `prompt`, if non-null, is the text displayed prior to waiting for user
  /// input each time. If `prompt` is non-null and `displayAcceptedCharacters`
  /// is true, the accepted keys are printed next to the `prompt`.
205
  ///
206 207 208 209
  /// The returned value is the user's input; if `defaultChoiceIndex` is not
  /// null, and the user presses enter without any other input, the return value
  /// will be the character in `acceptedCharacters` at the index given by
  /// `defaultChoiceIndex`.
210 211
  ///
  /// If [usesTerminalUi] is false, throws a [StateError].
212 213
  Future<String> promptForCharInput(
    List<String> acceptedCharacters, {
214
    @required Logger logger,
215
    String prompt,
216
    int defaultChoiceIndex,
217
    bool displayAcceptedCharacters = true,
218 219 220
  }) async {
    assert(acceptedCharacters != null);
    assert(acceptedCharacters.isNotEmpty);
221 222
    assert(prompt == null || prompt.isNotEmpty);
    assert(displayAcceptedCharacters != null);
223 224 225
    if (!usesTerminalUi) {
      throw StateError('cannot prompt without a terminal ui');
    }
226 227 228
    List<String> charactersToDisplay = acceptedCharacters;
    if (defaultChoiceIndex != null) {
      assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length);
229
      charactersToDisplay = List<String>.from(charactersToDisplay);
230 231 232
      charactersToDisplay[defaultChoiceIndex] = bolden(charactersToDisplay[defaultChoiceIndex]);
      acceptedCharacters.add('\n');
    }
233 234
    String choice;
    singleCharMode = true;
235 236
    while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) {
      if (prompt != null) {
237
        logger.printStatus(prompt, emphasis: true, newline: false);
238
        if (displayAcceptedCharacters) {
239
          logger.printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
240
        }
241
        logger.printStatus(': ', emphasis: true, newline: false);
242
      }
243
      choice = await keystrokes.first;
244
      logger.printStatus(choice);
245 246
    }
    singleCharMode = false;
247
    if (defaultChoiceIndex != null && choice == '\n') {
248
      choice = acceptedCharacters[defaultChoiceIndex];
249
    }
250 251 252
    return choice;
  }
}