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

5
import '../convert.dart';
6
import 'io.dart' as io;
7
import 'logger.dart';
8
import 'platform.dart';
9

10 11 12 13 14 15 16 17 18 19
enum TerminalColor {
  red,
  green,
  blue,
  cyan,
  yellow,
  magenta,
  grey,
}

20 21 22 23
/// A class that contains the context settings for command text output to the
/// console.
class OutputPreferences {
  OutputPreferences({
24 25 26 27
    bool? wrapText,
    int? wrapColumn,
    bool? showColor,
    io.Stdio? stdio,
28
  }) : _stdio = stdio,
29
       wrapText = wrapText ?? stdio?.hasTerminal ?? false,
30
       _overrideWrapColumn = wrapColumn,
31
       showColor = showColor ?? false;
32

33
  /// A version of this class for use in tests.
34
  OutputPreferences.test({this.wrapText = false, int wrapColumn = kDefaultTerminalColumns, this.showColor = false})
35 36
    : _overrideWrapColumn = wrapColumn, _stdio = null;

37
  final io.Stdio? _stdio;
38

39 40 41 42 43
  /// 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
44
  /// stdio.
45 46
  final bool wrapText;

47 48 49 50
  /// 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;

51 52 53 54
  /// 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.
55
  final int? _overrideWrapColumn;
56
  int get wrapColumn {
57
    return _overrideWrapColumn ?? _stdio?.terminalColumns ?? kDefaultTerminalColumns;
58
  }
59 60 61 62 63 64 65 66 67 68 69 70

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

71 72
/// The command line terminal, if available.
abstract class Terminal {
73 74 75
  /// Create a new test [Terminal].
  ///
  /// If not specified, [supportsColor] defaults to `false`.
76
  factory Terminal.test({bool supportsColor, bool supportsEmoji}) = _TestTerminal;
77 78 79 80 81 82 83

  /// Whether the current terminal supports color escape codes.
  bool get supportsColor;

  /// Whether the current terminal can display emoji.
  bool get supportsEmoji;

84 85 86 87
  /// When we have a choice of styles (e.g. animated spinners), this selects the
  /// style to use.
  int get preferredStyle;

88 89 90 91 92 93
  /// Whether we are interacting with the flutter tool via the terminal.
  ///
  /// If not set, defaults to false.
  bool get usesTerminalUi;
  set usesTerminalUi(bool value);

94 95 96 97 98 99 100 101
  /// Whether there is a terminal attached to stdin.
  ///
  /// If true, this usually indicates that a user is using the CLI as
  /// opposed to using an IDE. This can be used to determine
  /// whether it is appropriate to show a terminal prompt,
  /// or whether an automatic selection should be made instead.
  bool get stdinHasTerminal;

102 103 104 105 106 107
  /// Warning mark to use in stdout or stderr.
  String get warningMark;

  /// Success mark to use in stdout.
  String get successMark;

108 109 110 111 112 113
  String bolden(String message);

  String color(String message, TerminalColor color);

  String clearScreen();

114
  bool get singleCharMode;
115 116 117 118
  set singleCharMode(bool value);

  /// Return keystrokes from the console.
  ///
119 120 121
  /// This is a single-subscription stream. This stream may be closed before
  /// the application exits.
  ///
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  /// Useful when the console is in [singleCharMode].
  Stream<String> get keystrokes;

  /// Prompts the user to input a character within a given list. Re-prompts if
  /// entered character is not in the list.
  ///
  /// 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`.
  ///
  /// 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`.
  ///
137 138 139
  /// The accepted characters must be a String with a length of 1, excluding any
  /// whitespace characters such as `\t`, `\n`, or ` `.
  ///
140 141 142
  /// If [usesTerminalUi] is false, throws a [StateError].
  Future<String> promptForCharInput(
    List<String> acceptedCharacters, {
143 144 145
    required Logger logger,
    String? prompt,
    int? defaultChoiceIndex,
146 147 148 149 150
    bool displayAcceptedCharacters = true,
  });
}

class AnsiTerminal implements Terminal {
151
  AnsiTerminal({
152 153
    required io.Stdio stdio,
    required Platform platform,
154
    DateTime? now, // Time used to determine preferredStyle. Defaults to 0001-01-01 00:00.
155
  })
156
    : _stdio = stdio,
157 158
      _platform = platform,
      _now = now ?? DateTime(1);
159 160 161

  final io.Stdio _stdio;
  final Platform _platform;
162
  final DateTime _now;
163

164
  static const String bold = '\u001B[1m';
165 166 167
  static const String resetAll = '\u001B[0m';
  static const String resetColor = '\u001B[39m';
  static const String resetBold = '\u001B[22m';
168 169 170 171 172 173 174 175
  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';
176
  static const String grey = '\u001b[90m';
177 178 179 180 181 182 183 184 185 186

  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,
  };
187

188
  static String colorCode(TerminalColor color) => _colorMap[color]!;
189

190
  @override
191
  bool get supportsColor => _platform.stdoutSupportsAnsi;
192

193 194 195 196
  // Assume unicode emojis are supported when not on Windows.
  // If we are on Windows, unicode emojis are supported in Windows Terminal,
  // which sets the WT_SESSION environment variable. See:
  // https://github.com/microsoft/terminal/blob/master/doc/user-docs/index.md#tips-and-tricks
197
  @override
198 199 200
  bool get supportsEmoji => !_platform.isWindows
    || _platform.environment.containsKey('WT_SESSION');

201 202 203 204 205 206 207 208 209
  @override
  int get preferredStyle {
    const int workdays = DateTime.friday;
    if (_now.weekday <= workdays) {
      return _now.weekday - 1;
    }
    return _now.hour + workdays;
  }

210 211 212
  final RegExp _boldControls = RegExp(
    '(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})',
  );
213

214
  @override
215 216
  bool usesTerminalUi = false;

217 218 219 220 221 222 223 224 225 226
  @override
  String get warningMark {
    return bolden(color('[!]', TerminalColor.red));
  }

  @override
  String get successMark {
    return bolden(color('✓', TerminalColor.green));
  }

227
  @override
228
  String bolden(String message) {
229
    assert(message != null);
230
    if (!supportsColor || message.isEmpty) {
231
      return message;
232
    }
233
    final StringBuffer buffer = StringBuffer();
234 235 236 237 238 239 240
    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');
    }
241 242 243 244 245 246 247
    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;
  }

248
  @override
249 250
  String color(String message, TerminalColor color) {
    assert(message != null);
251
    if (!supportsColor || color == null || message.isEmpty) {
252
      return message;
253
    }
254
    final StringBuffer buffer = StringBuffer();
255
    final String colorCodes = _colorMap[color]!;
256 257 258 259 260 261 262
    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');
    }
263 264 265 266 267 268 269
    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;
  }

270
  @override
271
  String clearScreen() => supportsColor ? clear : '\n\n';
272

273 274 275 276 277 278 279 280
  @override
  bool get singleCharMode {
    if (!_stdio.stdinHasTerminal) {
      return false;
    }
    final io.Stdin stdin = _stdio.stdin as io.Stdin;
    return stdin.lineMode && stdin.echoMode;
  }
281
  @override
282
  set singleCharMode(bool value) {
283
    if (!_stdio.stdinHasTerminal) {
284 285
      return;
    }
286
    final io.Stdin stdin = _stdio.stdin as io.Stdin;
287 288 289 290 291 292 293
    // 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;
294 295 296
    }
  }

297 298 299
  @override
  bool get stdinHasTerminal => _stdio.stdinHasTerminal;

300
  Stream<String>? _broadcastStdInString;
301

302
  @override
303
  Stream<String> get keystrokes {
304
    return _broadcastStdInString ??= _stdio.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream();
305 306
  }

307
  @override
308 309
  Future<String> promptForCharInput(
    List<String> acceptedCharacters, {
310 311 312
    required Logger logger,
    String? prompt,
    int? defaultChoiceIndex,
313
    bool displayAcceptedCharacters = true,
314 315
  }) async {
    assert(acceptedCharacters.isNotEmpty);
316
    assert(prompt == null || prompt.isNotEmpty);
317 318 319
    if (!usesTerminalUi) {
      throw StateError('cannot prompt without a terminal ui');
    }
320 321 322
    List<String> charactersToDisplay = acceptedCharacters;
    if (defaultChoiceIndex != null) {
      assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length);
323
      charactersToDisplay = List<String>.of(charactersToDisplay);
324
      charactersToDisplay[defaultChoiceIndex] = bolden(charactersToDisplay[defaultChoiceIndex]);
325
      acceptedCharacters.add('');
326
    }
327
    String? choice;
328
    singleCharMode = true;
329 330
    while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) {
      if (prompt != null) {
331
        logger.printStatus(prompt, emphasis: true, newline: false);
332
        if (displayAcceptedCharacters) {
333
          logger.printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
334
        }
335
        // prompt ends with ': '
336
        logger.printStatus(': ', emphasis: true, newline: false);
337
      }
338
      choice = (await keystrokes.first).trim();
339
      logger.printStatus(choice);
340 341
    }
    singleCharMode = false;
342
    if (defaultChoiceIndex != null && choice == '') {
343
      choice = acceptedCharacters[defaultChoiceIndex];
344
    }
345 346 347
    return choice;
  }
}
348 349

class _TestTerminal implements Terminal {
350
  _TestTerminal({this.supportsColor = false, this.supportsEmoji = false});
351

352
  @override
353
  bool usesTerminalUi = false;
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

  @override
  String bolden(String message) => message;

  @override
  String clearScreen() => '\n\n';

  @override
  String color(String message, TerminalColor color) => message;

  @override
  Stream<String> get keystrokes => const Stream<String>.empty();

  @override
  Future<String> promptForCharInput(List<String> acceptedCharacters, {
369 370 371
    required Logger logger,
    String? prompt,
    int? defaultChoiceIndex,
372 373 374 375 376
    bool displayAcceptedCharacters = true,
  }) {
    throw UnsupportedError('promptForCharInput not supported in the test terminal.');
  }

377 378
  @override
  bool get singleCharMode => false;
379 380 381 382
  @override
  set singleCharMode(bool value) { }

  @override
383
  final bool supportsColor;
384 385

  @override
386
  final bool supportsEmoji;
387

388 389 390
  @override
  int get preferredStyle => 0;

391 392
  @override
  bool get stdinHasTerminal => false;
393 394 395 396 397 398

  @override
  String get successMark => '✓';

  @override
  String get warningMark => '[!]';
399
}