terminal.dart 8.27 KB
Newer Older
1 2 3 4 5 6
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import '../convert.dart';
8 9
import '../globals.dart';
import 'context.dart';
10
import 'io.dart' as io;
11
import 'platform.dart';
12
import 'utils.dart';
13

14
final AnsiTerminal _kAnsiTerminal = AnsiTerminal();
15 16

AnsiTerminal get terminal {
17
  return (context == null || context.get<AnsiTerminal>() == null)
18
      ? _kAnsiTerminal
19
      : context.get<AnsiTerminal>();
20 21
}

22 23 24 25 26 27 28 29 30 31
enum TerminalColor {
  red,
  green,
  blue,
  cyan,
  yellow,
  magenta,
  grey,
}

32 33
final OutputPreferences _kOutputPreferences = OutputPreferences();

34
OutputPreferences get outputPreferences => (context == null || context.get<OutputPreferences>() == null)
35
    ? _kOutputPreferences
36
    : context.get<OutputPreferences>();
37 38 39 40 41 42 43 44

/// A class that contains the context settings for command text output to the
/// console.
class OutputPreferences {
  OutputPreferences({
    bool wrapText,
    int wrapColumn,
    bool showColor,
45 46 47
  }) : wrapText = wrapText ?? io.stdio?.hasTerminal ?? const io.Stdio().hasTerminal,
       _overrideWrapColumn = wrapColumn,
       showColor = showColor ?? platform.stdoutSupportsAnsi ?? false;
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

  /// 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
  /// stdio to see, and if that's not set, it tries creating a new [io.Stdio]
  /// and asks it if there is a terminal.
  final bool wrapText;

  /// 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.
  /// To find out if we're writing to a terminal, it tries the context's stdio,
  /// and if that's not set, it tries creating a new [io.Stdio] and asks it, if
  /// that doesn't have an idea of the terminal width, then we just use a
65 66 67 68 69 70
  /// default of 100. It will be ignored if [wrapText] is false.
  final int _overrideWrapColumn;
  int get wrapColumn {
    return  _overrideWrapColumn ?? io.stdio?.terminalColumns
      ?? const io.Stdio().terminalColumns ?? kDefaultTerminalColumns;
  }
71 72 73 74 75 76 77 78 79 80 81 82

  /// 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]';
  }
}

83
class AnsiTerminal {
84
  static const String bold = '\u001B[1m';
85 86 87
  static const String resetAll = '\u001B[0m';
  static const String resetColor = '\u001B[39m';
  static const String resetBold = '\u001B[22m';
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  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,
  };
107

108 109
  static String colorCode(TerminalColor color) => _colorMap[color];

110 111
  bool get supportsColor => platform.stdoutSupportsAnsi ?? false;
  final RegExp _boldControls = RegExp('(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})');
112 113

  String bolden(String message) {
114 115
    assert(message != null);
    if (!supportsColor || message.isEmpty)
116
      return message;
117
    final StringBuffer buffer = StringBuffer();
118 119 120 121 122 123 124
    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');
    }
125 126 127 128 129 130 131
    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;
  }

132 133 134 135 136
  String color(String message, TerminalColor color) {
    assert(message != null);
    if (!supportsColor || color == null || message.isEmpty)
      return message;
    final StringBuffer buffer = StringBuffer();
137 138 139 140 141 142 143 144
    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');
    }
145 146 147 148 149 150 151 152
    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';
153 154

  set singleCharMode(bool value) {
155
    final Stream<List<int>> stdin = io.stdin;
156 157 158 159 160 161 162 163
    if (stdin is io.Stdin && stdin.hasTerminal) {
      // 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;
164 165 166 167 168 169 170 171 172
      }
    }
  }

  Stream<String> _broadcastStdInString;

  /// Return keystrokes from the console.
  ///
  /// Useful when the console is in [singleCharMode].
173
  Stream<String> get keystrokes {
174
    _broadcastStdInString ??= io.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream();
175 176 177
    return _broadcastStdInString;
  }

178 179
  /// Prompts the user to input a character within a given list. Re-prompts if
  /// entered character is not in the list.
180
  ///
181 182 183
  /// 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`.
184
  ///
185 186 187 188
  /// 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`.
189 190 191
  Future<String> promptForCharInput(
    List<String> acceptedCharacters, {
    String prompt,
192
    int defaultChoiceIndex,
193
    bool displayAcceptedCharacters = true,
194 195 196
  }) async {
    assert(acceptedCharacters != null);
    assert(acceptedCharacters.isNotEmpty);
197 198
    assert(prompt == null || prompt.isNotEmpty);
    assert(displayAcceptedCharacters != null);
199 200 201
    List<String> charactersToDisplay = acceptedCharacters;
    if (defaultChoiceIndex != null) {
      assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length);
202
      charactersToDisplay = List<String>.from(charactersToDisplay);
203 204 205
      charactersToDisplay[defaultChoiceIndex] = bolden(charactersToDisplay[defaultChoiceIndex]);
      acceptedCharacters.add('\n');
    }
206 207
    String choice;
    singleCharMode = true;
208 209
    while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) {
      if (prompt != null) {
210 211
        printStatus(prompt, emphasis: true, newline: false);
        if (displayAcceptedCharacters)
212
          printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
213 214
        printStatus(': ', emphasis: true, newline: false);
      }
215
      choice = await keystrokes.first;
216 217 218
      printStatus(choice);
    }
    singleCharMode = false;
219 220
    if (defaultChoiceIndex != null && choice == '\n')
      choice = acceptedCharacters[defaultChoiceIndex];
221 222 223
    return choice;
  }
}