logger.dart 29 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 'dart:async';
6

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

9
import '../convert.dart';
10
import 'io.dart';
11
import 'terminal.dart' show Terminal, TerminalColor, OutputPreferences;
12
import 'utils.dart';
13

14
const int kDefaultStatusPadding = 59;
15

16 17 18 19 20 21 22 23 24
/// A factory for generating [Stopwatch] instances for [Status] instances.
class StopwatchFactory {
  /// const constructor so that subclasses may be const.
  const StopwatchFactory();

  /// Create a new [Stopwatch] instance.
  Stopwatch createStopwatch() => Stopwatch();
}

25
typedef VoidCallback = void Function();
26

27
abstract class Logger {
Devon Carew's avatar
Devon Carew committed
28
  bool get isVerbose => false;
29

30 31
  bool quiet = false;

32
  bool get supportsColor;
33

34 35
  bool get hasTerminal;

36
  Terminal get terminal;
37 38 39

  OutputPreferences get _outputPreferences;

40
  /// Display an error `message` to the user. Commands should use this if they
41
  /// fail in some way.
42
  ///
43 44 45
  /// The `message` argument is printed to the stderr in red by default.
  ///
  /// The `stackTrace` argument is the stack trace that will be printed if
46
  /// supplied.
47 48 49 50
  ///
  /// The `emphasis` argument will cause the output message be printed in bold text.
  ///
  /// The `color` argument will print the message in the supplied color instead
51 52
  /// of the default of red. Colors will not be printed if the output terminal
  /// doesn't support them.
53 54
  ///
  /// The `indent` argument specifies the number of spaces to indent the overall
55 56
  /// message. If wrapping is enabled in [outputPreferences], then the wrapped
  /// lines will be indented as well.
57 58
  ///
  /// If `hangingIndent` is specified, then any wrapped lines will be indented
59 60
  /// by this much more than the first line, if wrapping is enabled in
  /// [outputPreferences].
61 62 63
  ///
  /// If `wrap` is specified, then it overrides the
  /// `outputPreferences.wrapText` setting.
64 65
  void printError(
    String message, {
66 67 68 69 70 71
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
72
  });
73 74 75

  /// Display normal output of the command. This should be used for things like
  /// progress messages, success messages, or just normal command output.
76
  ///
77 78 79
  /// The `message` argument is printed to the stderr in red by default.
  ///
  /// The `stackTrace` argument is the stack trace that will be printed if
80
  /// supplied.
81 82
  ///
  /// If the `emphasis` argument is true, it will cause the output message be
83
  /// printed in bold text. Defaults to false.
84 85
  ///
  /// The `color` argument will print the message in the supplied color instead
86 87
  /// of the default of red. Colors will not be printed if the output terminal
  /// doesn't support them.
88 89
  ///
  /// If `newline` is true, then a newline will be added after printing the
90
  /// status. Defaults to true.
91 92
  ///
  /// The `indent` argument specifies the number of spaces to indent the overall
93 94
  /// message. If wrapping is enabled in [outputPreferences], then the wrapped
  /// lines will be indented as well.
95 96
  ///
  /// If `hangingIndent` is specified, then any wrapped lines will be indented
97 98
  /// by this much more than the first line, if wrapping is enabled in
  /// [outputPreferences].
99 100 101
  ///
  /// If `wrap` is specified, then it overrides the
  /// `outputPreferences.wrapText` setting.
102
  void printStatus(
103
    String message, {
104 105 106 107 108 109
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
110
  });
111 112 113 114

  /// Use this for verbose tracing output. Users can turn this output on in order
  /// to help diagnose issues with the toolchain or with their setup.
  void printTrace(String message);
Devon Carew's avatar
Devon Carew committed
115

116
  /// Start an indeterminate progress display.
117
  ///
118 119 120 121 122
  /// The `message` argument is the message to display to the user.
  ///
  /// The `progressId` argument provides an ID that can be used to identify
  /// this type of progress (e.g. `hot.reload`, `hot.restart`).
  ///
123 124 125
  /// The `progressIndicatorPadding` can optionally be used to specify the width
  /// of the space into which the `message` is placed before the progress
  /// indicator, if any. It is ignored if the message is longer.
126 127
  Status startProgress(
    String message, {
128
    String? progressId,
129
    int progressIndicatorPadding = kDefaultStatusPadding,
130
  });
131

132
  /// A [SilentStatus] or an [AnonymousSpinnerStatus] (depending on whether the
133
  /// terminal is fancy enough), already started.
134
  Status startSpinner({ VoidCallback? onFinish });
135

136
  /// Send an event to be emitted.
137 138
  ///
  /// Only surfaces a value in machine modes, Loggers may ignore this message in
139
  /// non-machine modes.
140
  void sendEvent(String name, [Map<String, dynamic>? args]) { }
141 142 143

  /// Clears all output.
  void clear();
144 145
}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/// A [Logger] that forwards all methods to another one.
///
/// Classes can derive from this to add functionality to an existing [Logger].
class DelegatingLogger implements Logger {
  @visibleForTesting
  @protected
  DelegatingLogger(this._delegate);

  final Logger _delegate;

  @override
  bool get quiet => _delegate.quiet;

  @override
  set quiet(bool value) => _delegate.quiet = value;

  @override
  bool get hasTerminal => _delegate.hasTerminal;

  @override
166
  Terminal get terminal => _delegate.terminal;
167 168 169 170 171 172 173 174

  @override
  OutputPreferences get _outputPreferences => _delegate._outputPreferences;

  @override
  bool get isVerbose => _delegate.isVerbose;

  @override
175 176 177 178 179 180 181 182
  void printError(String message, {
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
  }) {
183 184 185 186 187 188 189 190 191 192 193 194
    _delegate.printError(
      message,
      stackTrace: stackTrace,
      emphasis: emphasis,
      color: color,
      indent: indent,
      hangingIndent: hangingIndent,
      wrap: wrap,
    );
  }

  @override
195 196 197 198 199 200 201 202
  void printStatus(String message, {
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
  }) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    _delegate.printStatus(message,
      emphasis: emphasis,
      color: color,
      newline: newline,
      indent: indent,
      hangingIndent: hangingIndent,
      wrap: wrap,
    );
  }

  @override
  void printTrace(String message) {
    _delegate.printTrace(message);
  }

  @override
219
  void sendEvent(String name, [Map<String, dynamic>? args]) {
220 221 222 223
    _delegate.sendEvent(name, args);
  }

  @override
224 225 226 227
  Status startProgress(String message, {
    String? progressId,
    int progressIndicatorPadding = kDefaultStatusPadding,
  }) {
228 229 230 231 232 233
    return _delegate.startProgress(message,
      progressId: progressId,
      progressIndicatorPadding: progressIndicatorPadding,
    );
  }

234
  @override
235
  Status startSpinner({VoidCallback? onFinish}) {
236 237 238
    return _delegate.startSpinner(onFinish: onFinish);
  }

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  @override
  bool get supportsColor => _delegate.supportsColor;

  @override
  void clear() => _delegate.clear();
}

/// If [logger] is a [DelegatingLogger], walks the delegate chain and returns
/// the first delegate with the matching type.
///
/// Throws a [StateError] if no matching delegate is found.
@override
T asLogger<T extends Logger>(Logger logger) {
  final Logger original = logger;
  while (true) {
    if (logger is T) {
      return logger;
    } else if (logger is DelegatingLogger) {
257
      logger = logger._delegate;
258 259 260 261 262 263
    } else {
      throw StateError('$original has no ancestor delegate of type $T');
    }
  }
}

264
class StdoutLogger extends Logger {
265
  StdoutLogger({
266 267 268
    required this.terminal,
    required Stdio stdio,
    required OutputPreferences outputPreferences,
269
    StopwatchFactory stopwatchFactory = const StopwatchFactory(),
270 271
  })
    : _stdio = stdio,
272
      _outputPreferences = outputPreferences,
273
      _stopwatchFactory = stopwatchFactory;
274 275

  @override
276
  final Terminal terminal;
277 278 279
  @override
  final OutputPreferences _outputPreferences;
  final Stdio _stdio;
280
  final StopwatchFactory _stopwatchFactory;
281

282
  Status? _status;
283

284
  @override
Devon Carew's avatar
Devon Carew committed
285
  bool get isVerbose => false;
286

287
  @override
288
  bool get supportsColor => terminal.supportsColor;
289 290 291 292

  @override
  bool get hasTerminal => _stdio.stdinHasTerminal;

293
  @override
294 295
  void printError(
    String message, {
296 297 298 299 300 301
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
302
  }) {
303
    _status?.pause();
304 305 306 307 308 309
    message = wrapText(message,
      indent: indent,
      hangingIndent: hangingIndent,
      shouldWrap: wrap ?? _outputPreferences.wrapText,
      columnWidth: _outputPreferences.wrapColumn,
    );
310
    if (emphasis == true) {
311
      message = terminal.bolden(message);
312
    }
313
    message = terminal.color(message, color ?? TerminalColor.red);
314
    writeToStdErr('$message\n');
315
    if (stackTrace != null) {
316
      writeToStdErr('$stackTrace\n');
317
    }
318
    _status?.resume();
319 320
  }

321
  @override
322
  void printStatus(
323
    String message, {
324 325 326 327 328 329
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
330
  }) {
331
    _status?.pause();
332 333 334 335 336 337
    message = wrapText(message,
      indent: indent,
      hangingIndent: hangingIndent,
      shouldWrap: wrap ?? _outputPreferences.wrapText,
      columnWidth: _outputPreferences.wrapColumn,
    );
338
    if (emphasis == true) {
339
      message = terminal.bolden(message);
340 341
    }
    if (color != null) {
342
      message = terminal.color(message, color);
343 344
    }
    if (newline != false) {
345
      message = '$message\n';
346
    }
347
    writeToStdOut(message);
348
    _status?.resume();
349 350 351
  }

  @protected
352
  void writeToStdOut(String message) => _stdio.stdoutWrite(message);
353 354

  @protected
355
  void writeToStdErr(String message) => _stdio.stderrWrite(message);
356

357
  @override
358
  void printTrace(String message) { }
359

360
  @override
361 362
  Status startProgress(
    String message, {
363
    String? progressId,
364
    int progressIndicatorPadding = kDefaultStatusPadding,
365
  }) {
Devon Carew's avatar
Devon Carew committed
366 367
    if (_status != null) {
      // Ignore nested progresses; return a no-op status object.
368
      return SilentStatus(
369
        stopwatch: _stopwatchFactory.createStopwatch(),
370
      )..start();
371
    }
372
    if (supportsColor) {
373
      _status = SpinnerStatus(
374 375 376
        message: message,
        padding: progressIndicatorPadding,
        onFinish: _clearStatus,
377
        stdio: _stdio,
378
        stopwatch: _stopwatchFactory.createStopwatch(),
379
        terminal: terminal,
380
      )..start();
Devon Carew's avatar
Devon Carew committed
381
    } else {
382 383 384 385
      _status = SummaryStatus(
        message: message,
        padding: progressIndicatorPadding,
        onFinish: _clearStatus,
386
        stdio: _stdio,
387
        stopwatch: _stopwatchFactory.createStopwatch(),
388
      )..start();
389
    }
390
    return _status!;
391
  }
392

393
  @override
394
  Status startSpinner({ VoidCallback? onFinish }) {
395 396
    if (_status != null || !supportsColor) {
      return SilentStatus(
397 398 399 400
        onFinish: onFinish,
        stopwatch: _stopwatchFactory.createStopwatch(),
      )..start();
    }
401 402 403 404 405 406 407 408
    _status = AnonymousSpinnerStatus(
      onFinish: () {
        if (onFinish != null) {
          onFinish();
        }
        _clearStatus();
      },
      stdio: _stdio,
409
      stopwatch: _stopwatchFactory.createStopwatch(),
410
      terminal: terminal,
411
    )..start();
412
    return _status!;
413 414
  }

415 416 417
  void _clearStatus() {
    _status = null;
  }
418 419

  @override
420
  void sendEvent(String name, [Map<String, dynamic>? args]) { }
421 422 423 424

  @override
  void clear() {
    _status?.pause();
425
    writeToStdOut(terminal.clearScreen() + '\n');
426 427
    _status?.resume();
  }
428 429
}

430 431 432
/// A [StdoutLogger] which replaces Unicode characters that cannot be printed to
/// the Windows console with alternative symbols.
///
433 434 435 436 437
/// By default, Windows uses either "Consolas" or "Lucida Console" as fonts to
/// render text in the console. Both fonts only have a limited character set.
/// Unicode characters, that are not available in either of the two default
/// fonts, should be replaced by this class with printable symbols. Otherwise,
/// they will show up as the unrepresentable character symbol '�'.
438
class WindowsStdoutLogger extends StdoutLogger {
439
  WindowsStdoutLogger({
440 441 442
    required Terminal terminal,
    required Stdio stdio,
    required OutputPreferences outputPreferences,
443
    StopwatchFactory stopwatchFactory = const StopwatchFactory(),
444 445 446 447
  }) : super(
      terminal: terminal,
      stdio: stdio,
      outputPreferences: outputPreferences,
448
      stopwatchFactory: stopwatchFactory,
449 450
    );

451 452
  @override
  void writeToStdOut(String message) {
453
    final String windowsMessage = terminal.supportsEmoji
454 455
      ? message
      : message.replaceAll('🔥', '')
456
               .replaceAll('🖼️', '')
457
               .replaceAll('✗', 'X')
458
               .replaceAll('✓', '√')
459
               .replaceAll('🔨', '')
460 461
               .replaceAll('💪', '')
               .replaceAll('✏️', '');
462
    _stdio.stdoutWrite(windowsMessage);
463 464 465
  }
}

466
class BufferLogger extends Logger {
467
  BufferLogger({
468 469
    required this.terminal,
    required OutputPreferences outputPreferences,
470
    StopwatchFactory stopwatchFactory = const StopwatchFactory(),
471
  }) : _outputPreferences = outputPreferences,
472
       _stopwatchFactory = stopwatchFactory;
473

474
  /// Create a [BufferLogger] with test preferences.
475
  BufferLogger.test({
476 477
    Terminal? terminal,
    OutputPreferences? outputPreferences,
478
  }) : terminal = terminal ?? Terminal.test(),
479 480 481 482
       _outputPreferences = outputPreferences ?? OutputPreferences.test(),
       _stopwatchFactory = const StopwatchFactory();


483 484 485 486
  @override
  final OutputPreferences _outputPreferences;

  @override
487
  final Terminal terminal;
488

489 490
  final StopwatchFactory _stopwatchFactory;

491
  @override
Devon Carew's avatar
Devon Carew committed
492 493
  bool get isVerbose => false;

494
  @override
495
  bool get supportsColor => terminal.supportsColor;
496

497 498 499
  final StringBuffer _error = StringBuffer();
  final StringBuffer _status = StringBuffer();
  final StringBuffer _trace = StringBuffer();
500
  final StringBuffer _events = StringBuffer();
501 502 503 504

  String get errorText => _error.toString();
  String get statusText => _status.toString();
  String get traceText => _trace.toString();
505
  String get eventText => _events.toString();
506

507 508 509
  @override
  bool get hasTerminal => false;

510
  @override
511 512
  void printError(
    String message, {
513 514 515 516 517 518
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
519
  }) {
520
    _error.writeln(terminal.color(
521 522 523 524 525 526
      wrapText(message,
        indent: indent,
        hangingIndent: hangingIndent,
        shouldWrap: wrap ?? _outputPreferences.wrapText,
        columnWidth: _outputPreferences.wrapColumn,
      ),
527 528
      color ?? TerminalColor.red,
    ));
529 530
  }

531
  @override
532
  void printStatus(
533
    String message, {
534 535 536 537 538 539
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
540
  }) {
541
    if (newline != false) {
542 543 544 545 546 547
      _status.writeln(wrapText(message,
        indent: indent,
        hangingIndent: hangingIndent,
        shouldWrap: wrap ?? _outputPreferences.wrapText,
        columnWidth: _outputPreferences.wrapColumn,
      ));
548
    } else {
549 550 551 552 553 554
      _status.write(wrapText(message,
        indent: indent,
        hangingIndent: hangingIndent,
        shouldWrap: wrap ?? _outputPreferences.wrapText,
        columnWidth: _outputPreferences.wrapColumn,
      ));
555
    }
556
  }
557 558

  @override
559
  void printTrace(String message) => _trace.writeln(message);
Devon Carew's avatar
Devon Carew committed
560

561
  @override
562 563
  Status startProgress(
    String message, {
564
    String? progressId,
565
    int progressIndicatorPadding = kDefaultStatusPadding,
566
  }) {
567
    assert(progressIndicatorPadding != null);
568
    printStatus(message);
569
    return SilentStatus(
570
      stopwatch: _stopwatchFactory.createStopwatch(),
571
    )..start();
572
  }
573

574
  @override
575
  Status startSpinner({VoidCallback? onFinish}) {
576 577 578 579 580 581
    return SilentStatus(
      stopwatch: _stopwatchFactory.createStopwatch(),
      onFinish: onFinish,
    )..start();
  }

582
  @override
583 584 585 586
  void clear() {
    _error.clear();
    _status.clear();
    _trace.clear();
587
    _events.clear();
588
  }
589 590

  @override
591 592
  void sendEvent(String name, [Map<String, dynamic>? args]) {
    _events.write(json.encode(<String, Object?>{
593 594 595 596
      'name': name,
      'args': args
    }));
  }
Devon Carew's avatar
Devon Carew committed
597 598
}

599 600
class VerboseLogger extends DelegatingLogger {
  VerboseLogger(Logger parent, {
601 602
    StopwatchFactory stopwatchFactory = const StopwatchFactory()
  }) : _stopwatch = stopwatchFactory.createStopwatch(),
603 604
       _stopwatchFactory = stopwatchFactory,
       super(parent) {
605
    _stopwatch.start();
606
  }
Devon Carew's avatar
Devon Carew committed
607

608 609
  final Stopwatch _stopwatch;

610 611
  final StopwatchFactory _stopwatchFactory;

612
  @override
Devon Carew's avatar
Devon Carew committed
613 614
  bool get isVerbose => true;

615
  @override
616 617
  void printError(
    String message, {
618 619 620 621 622 623
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
624
  }) {
625 626
    _emit(
      _LogType.error,
627 628 629 630 631 632
      wrapText(message,
        indent: indent,
        hangingIndent: hangingIndent,
        shouldWrap: wrap ?? _outputPreferences.wrapText,
        columnWidth: _outputPreferences.wrapColumn,
      ),
633 634
      stackTrace,
    );
Devon Carew's avatar
Devon Carew committed
635 636
  }

637
  @override
638
  void printStatus(
639
    String message, {
640 641 642 643 644 645
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
646
  }) {
647 648 649 650 651 652
    _emit(_LogType.status, wrapText(message,
      indent: indent,
      hangingIndent: hangingIndent,
      shouldWrap: wrap ?? _outputPreferences.wrapText,
      columnWidth: _outputPreferences.wrapColumn,
    ));
Devon Carew's avatar
Devon Carew committed
653 654
  }

655
  @override
Devon Carew's avatar
Devon Carew committed
656
  void printTrace(String message) {
657
    _emit(_LogType.trace, message);
Devon Carew's avatar
Devon Carew committed
658 659
  }

660
  @override
661 662
  Status startProgress(
    String message, {
663
    String? progressId,
664
    int progressIndicatorPadding = kDefaultStatusPadding,
665
  }) {
666
    assert(progressIndicatorPadding != null);
667
    printStatus(message);
668
    final Stopwatch timer = _stopwatchFactory.createStopwatch()..start();
669
    return SilentStatus(
670 671
      // This is intentionally a different stopwatch than above.
      stopwatch: _stopwatchFactory.createStopwatch(),
672 673
      onFinish: () {
        String time;
674
        if (timer.elapsed.inSeconds > 2) {
675 676 677 678
          time = getElapsedAsSeconds(timer.elapsed);
        } else {
          time = getElapsedAsMilliseconds(timer.elapsed);
        }
679
        printTrace('$message (completed in $time)');
680 681
      },
    )..start();
682 683
  }

684
  void _emit(_LogType type, String message, [ StackTrace? stackTrace ]) {
685
    if (message.trim().isEmpty) {
686
      return;
687
    }
Devon Carew's avatar
Devon Carew committed
688

689 690
    final int millis = _stopwatch.elapsedMilliseconds;
    _stopwatch.reset();
Devon Carew's avatar
Devon Carew committed
691

692
    String prefix;
693
    const int prefixWidth = 8;
694 695 696 697
    if (millis == 0) {
      prefix = ''.padLeft(prefixWidth);
    } else {
      prefix = '+$millis ms'.padLeft(prefixWidth);
698
      if (millis >= 100) {
699
        prefix = terminal.bolden(prefix);
700
      }
701 702
    }
    prefix = '[$prefix] ';
Devon Carew's avatar
Devon Carew committed
703

704 705
    final String indent = ''.padLeft(prefix.length);
    final String indentMessage = message.replaceAll('\n', '\n$indent');
Devon Carew's avatar
Devon Carew committed
706 707

    if (type == _LogType.error) {
708
      super.printError(prefix + terminal.bolden(indentMessage));
709
      if (stackTrace != null) {
710
        super.printError(indent + stackTrace.toString().replaceAll('\n', '\n$indent'));
711
      }
Devon Carew's avatar
Devon Carew committed
712
    } else if (type == _LogType.status) {
713
      super.printStatus(prefix + terminal.bolden(indentMessage));
Devon Carew's avatar
Devon Carew committed
714
    } else {
715
      super.printStatus(prefix + indentMessage);
Devon Carew's avatar
Devon Carew committed
716 717
    }
  }
718 719

  @override
720
  void sendEvent(String name, [Map<String, dynamic>? args]) { }
Devon Carew's avatar
Devon Carew committed
721 722
}

723 724 725 726 727 728
class PrefixedErrorLogger extends DelegatingLogger {
  PrefixedErrorLogger(Logger parent) : super(parent);

  @override
  void printError(
    String message, {
729 730 731 732 733 734
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
735
  }) {
736
    if (message.trim().isNotEmpty == true) {
737 738 739 740 741 742 743 744 745 746 747 748 749 750
      message = 'ERROR: $message';
    }
    super.printError(
      message,
      stackTrace: stackTrace,
      emphasis: emphasis,
      color: color,
      indent: indent,
      hangingIndent: hangingIndent,
      wrap: wrap,
    );
  }
}

751
enum _LogType { error, status, trace }
752

753 754
typedef SlowWarningCallback = String Function();

755 756 757
/// A [Status] class begins when start is called, and may produce progress
/// information asynchronously.
///
758
/// The [SilentStatus] class never has any output.
759
///
760 761 762
/// The [SpinnerStatus] subclass shows a message with a spinner, and replaces it
/// with timing information when stopped. When canceled, the information isn't
/// shown. In either case, a newline is printed.
763
///
764
/// The [AnonymousSpinnerStatus] subclass just shows a spinner.
765
///
766 767 768
/// The [SummaryStatus] subclass shows only a static message (without an
/// indicator), then updates it when the operation ends.
///
769 770
/// Generally, consider `logger.startProgress` instead of directly creating
/// a [Status] or one of its subclasses.
771
abstract class Status {
772 773
  Status({
    this.onFinish,
774
    required Stopwatch stopwatch,
775
  }) : _stopwatch = stopwatch;
776

777
  final VoidCallback? onFinish;
778

779
  @protected
780
  final Stopwatch _stopwatch;
781 782 783

  @protected
  String get elapsedTime {
784
    if (_stopwatch.elapsed.inSeconds > 2) {
785
      return getElapsedAsSeconds(_stopwatch.elapsed);
786
    }
787 788
    return getElapsedAsMilliseconds(_stopwatch.elapsed);
  }
789

790
  /// Call to start spinning.
791
  void start() {
792 793
    assert(!_stopwatch.isRunning);
    _stopwatch.start();
794 795
  }

796
  /// Call to stop spinning after success.
797
  void stop() {
798
    finish();
799 800
  }

801
  /// Call to cancel the spinner after failure or cancellation.
802
  void cancel() {
803 804 805 806 807 808 809 810 811 812 813 814 815
    finish();
  }

  /// Call to clear the current line but not end the progress.
  void pause() { }

  /// Call to resume after a pause.
  void resume() { }

  @protected
  void finish() {
    assert(_stopwatch.isRunning);
    _stopwatch.stop();
816
    onFinish?.call();
817 818 819
  }
}

820 821 822
/// A [SilentStatus] shows nothing.
class SilentStatus extends Status {
  SilentStatus({
823 824
    required Stopwatch stopwatch,
    VoidCallback? onFinish,
825 826
  }) : super(
    onFinish: onFinish,
827
    stopwatch: stopwatch,
828
  );
829 830 831

  @override
  void finish() {
832
    onFinish?.call();
833
  }
834 835
}

836 837
const int _kTimePadding = 8; // should fit "99,999ms"

838 839 840 841 842
/// Constructor writes [message] to [stdout].  On [cancel] or [stop], will call
/// [onFinish]. On [stop], will additionally print out summary information.
class SummaryStatus extends Status {
  SummaryStatus({
    this.message = '',
843
    required Stopwatch stopwatch,
844
    this.padding = kDefaultStatusPadding,
845 846 847
    VoidCallback? onFinish,
    required Stdio stdio,
  }) : _stdio = stdio,
848 849 850 851
       super(
         onFinish: onFinish,
         stopwatch: stopwatch,
        );
852 853 854

  final String message;
  final int padding;
855
  final Stdio _stdio;
856 857 858 859 860 861 862 863 864

  bool _messageShowingOnCurrentLine = false;

  @override
  void start() {
    _printMessage();
    super.start();
  }

865
  void _writeToStdOut(String message) => _stdio.stdoutWrite(message);
866

867 868
  void _printMessage() {
    assert(!_messageShowingOnCurrentLine);
869
    _writeToStdOut('${message.padRight(padding)}     ');
870 871 872 873 874
    _messageShowingOnCurrentLine = true;
  }

  @override
  void stop() {
875
    if (!_messageShowingOnCurrentLine) {
876
      _printMessage();
877
    }
878
    super.stop();
879 880
    assert(_messageShowingOnCurrentLine);
    _writeToStdOut(elapsedTime.padLeft(_kTimePadding));
881
    _writeToStdOut('\n');
882 883 884 885 886
  }

  @override
  void cancel() {
    super.cancel();
887
    if (_messageShowingOnCurrentLine) {
888
      _writeToStdOut('\n');
889
    }
890 891 892 893 894
  }

  @override
  void pause() {
    super.pause();
895 896 897 898
    if (_messageShowingOnCurrentLine) {
      _writeToStdOut('\n');
      _messageShowingOnCurrentLine = false;
    }
899 900 901
  }
}

902 903 904 905 906
/// A kind of animated [Status] that has no message.
///
/// Call [pause] before outputting any text while this is running.
class AnonymousSpinnerStatus extends Status {
  AnonymousSpinnerStatus({
907
    VoidCallback? onFinish,
908
    required Stopwatch stopwatch,
909
    required Stdio stdio,
910
    required Terminal terminal,
911
  }) : _stdio = stdio,
912
       _terminal = terminal,
913
       _animation = _selectAnimation(terminal),
914 915 916 917
       super(
         onFinish: onFinish,
         stopwatch: stopwatch,
        );
918

919
  final Stdio _stdio;
920
  final Terminal _terminal;
921

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  static const String _backspaceChar = '\b';
  static const String _clearChar = ' ';

  static const List<String> _emojiAnimations = <String>[
    '⣾⣽⣻⢿⡿⣟⣯⣷', // counter-clockwise
    '⣾⣷⣯⣟⡿⢿⣻⣽', // clockwise
    '⣾⣷⣯⣟⡿⢿⣻⣽⣷⣾⣽⣻⢿⡿⣟⣯⣷', // bouncing clockwise and counter-clockwise
    '⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽', // snaking
    '⣾⣽⣻⢿⣿⣷⣯⣟⡿⣿', // alternating rain
    '⣀⣠⣤⣦⣶⣾⣿⡿⠿⠻⠛⠋⠉⠙⠛⠟⠿⢿⣿⣷⣶⣴⣤⣄', // crawl up and down, large
    '⠙⠚⠖⠦⢤⣠⣄⡤⠴⠲⠓⠋', // crawl up and down, small
    '⣀⡠⠤⠔⠒⠊⠉⠑⠒⠢⠤⢄', // crawl up and down, tiny
    '⡀⣄⣦⢷⠻⠙⠈⠀⠁⠋⠟⡾⣴⣠⢀⠀', // slide up and down
    '⠙⠸⢰⣠⣄⡆⠇⠋', // clockwise line
    '⠁⠈⠐⠠⢀⡀⠄⠂', // clockwise dot
    '⢇⢣⢱⡸⡜⡎', // vertical wobble up
    '⡇⡎⡜⡸⢸⢱⢣⢇', // vertical wobble down
    '⡀⣀⣐⣒⣖⣶⣾⣿⢿⠿⠯⠭⠩⠉⠁⠀', // swirl
    '⠁⠐⠄⢀⢈⢂⢠⣀⣁⣐⣄⣌⣆⣤⣥⣴⣼⣶⣷⣿⣾⣶⣦⣤⣠⣀⡀⠀⠀', // snowing and melting
    '⠁⠋⠞⡴⣠⢀⠀⠈⠙⠻⢷⣦⣄⡀⠀⠉⠛⠲⢤⢀⠀', // falling water
    '⠄⡢⢑⠈⠀⢀⣠⣤⡶⠞⠋⠁⠀⠈⠙⠳⣆⡀⠀⠆⡷⣹⢈⠀⠐⠪⢅⡀⠀', // fireworks
    '⠐⢐⢒⣒⣲⣶⣷⣿⡿⡷⡧⠧⠇⠃⠁⠀⡀⡠⡡⡱⣱⣳⣷⣿⢿⢯⢧⠧⠣⠃⠂⠀⠈⠨⠸⠺⡺⡾⡿⣿⡿⡷⡗⡇⡅⡄⠄⠀⡀⡐⣐⣒⣓⣳⣻⣿⣾⣼⡼⡸⡘⡈⠈⠀', // fade
    '⢸⡯⠭⠅⢸⣇⣀⡀⢸⣇⣸⡇⠈⢹⡏⠁⠈⢹⡏⠁⢸⣯⣭⡅⢸⡯⢕⡂⠀⠀', // text crawl
  ];

  static const List<String> _asciiAnimations = <String>[
    r'-\|/',
  ];

  static List<String> _selectAnimation(Terminal terminal) {
    final List<String> animations = terminal.supportsEmoji ? _emojiAnimations : _asciiAnimations;
    return animations[terminal.preferredStyle % animations.length]
      .runes
      .map<String>((int scalar) => String.fromCharCode(scalar))
      .toList();
  }
958

959
  final List<String> _animation;
960

961 962 963
  Timer? timer;
  int ticks = 0;
  int _lastAnimationFrameLength = 0;
964

965
  String get _currentAnimationFrame => _animation[ticks % _animation.length];
966
  int get _currentLineLength => _lastAnimationFrameLength;
967

968 969 970 971 972 973 974 975 976
  void _writeToStdOut(String message) => _stdio.stdoutWrite(message);

  void _clear(int length) {
    _writeToStdOut(
      '${_backspaceChar * length}'
      '${_clearChar * length}'
      '${_backspaceChar * length}'
    );
  }
977 978 979 980

  @override
  void start() {
    super.start();
981
    assert(timer == null);
982 983 984 985
    _startSpinner();
  }

  void _startSpinner() {
986
    timer = Timer.periodic(const Duration(milliseconds: 100), _callback);
987
    _callback(timer!);
988 989
  }

990 991 992 993
  void _callback(Timer timer) {
    assert(this.timer == timer);
    assert(timer != null);
    assert(timer.isActive);
994
    _writeToStdOut(_backspaceChar * _lastAnimationFrameLength);
995
    ticks += 1;
996 997 998
    final String newFrame = _currentAnimationFrame;
    _lastAnimationFrameLength = newFrame.runes.length;
    _writeToStdOut(newFrame);
999 1000
  }

1001
  @override
1002 1003
  void pause() {
    assert(timer != null);
1004
    assert(timer!.isActive);
1005 1006 1007 1008 1009 1010
    if (_terminal.supportsColor) {
      _writeToStdOut('\r\x1B[K'); // go to start of line and clear line
    } else {
      _clear(_currentLineLength);
    }
    _lastAnimationFrameLength = 0;
1011
    timer?.cancel();
1012 1013 1014 1015 1016
  }

  @override
  void resume() {
    assert(timer != null);
1017
    assert(!timer!.isActive);
1018
    _startSpinner();
1019 1020
  }

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  @override
  void finish() {
    assert(timer != null);
    assert(timer!.isActive);
    timer?.cancel();
    timer = null;
    _clear(_lastAnimationFrameLength);
    _lastAnimationFrameLength = 0;
    super.finish();
  }
}
1032

1033 1034 1035 1036
/// An animated version of [Status].
///
/// The constructor writes [message] to [stdout] with padding, then starts an
/// indeterminate progress indicator animation.
1037 1038 1039
///
/// On [cancel] or [stop], will call [onFinish]. On [stop], will
/// additionally print out summary information.
1040 1041 1042 1043 1044
///
/// Call [pause] before outputting any text while this is running.
class SpinnerStatus extends AnonymousSpinnerStatus {
  SpinnerStatus({
    required this.message,
1045
    this.padding = kDefaultStatusPadding,
1046
    VoidCallback? onFinish,
1047
    required Stopwatch stopwatch,
1048
    required Stdio stdio,
1049 1050
    required Terminal terminal,
  }) : super(
1051 1052
         onFinish: onFinish,
         stopwatch: stopwatch,
1053
         stdio: stdio,
1054
         terminal: terminal,
1055
        );
1056

1057
  final String message;
1058 1059
  final int padding;

1060
  static final String _margin = AnonymousSpinnerStatus._clearChar * (5 + _kTimePadding - 1);
1061

1062
  int _totalMessageLength = 0;
1063

1064 1065 1066
  @override
  int get _currentLineLength => _totalMessageLength + super._currentLineLength;

1067 1068
  @override
  void start() {
1069
    _printStatus();
1070
    super.start();
1071
  }
1072

1073
  void _printStatus() {
1074 1075
    final String line = '${message.padRight(padding)}$_margin';
    _totalMessageLength = line.length;
1076
    _writeToStdOut(line);
1077 1078
  }

1079
  @override
1080 1081 1082
  void pause() {
    super.pause();
    _totalMessageLength = 0;
1083
  }
1084

1085
  @override
1086 1087 1088
  void resume() {
    _printStatus();
    super.resume();
1089 1090 1091
  }

  @override
1092 1093 1094 1095 1096 1097
  void stop() {
    super.stop(); // calls finish, which clears the spinner
    assert(_totalMessageLength > _kTimePadding);
    _writeToStdOut(AnonymousSpinnerStatus._backspaceChar * (_kTimePadding - 1));
    _writeToStdOut(elapsedTime.padLeft(_kTimePadding));
    _writeToStdOut('\n');
1098 1099 1100
  }

  @override
1101 1102 1103 1104
  void cancel() {
    super.cancel(); // calls finish, which clears the spinner
    assert(_totalMessageLength > 0);
    _writeToStdOut('\n');
1105 1106
  }
}