From 63aa5b3647dbd912a02f7545fc0101003cb3adc4 Mon Sep 17 00:00:00 2001 From: Jacob Richman Date: Wed, 1 May 2019 11:20:12 -0700 Subject: [PATCH] Refactor core uses of FlutterError. (#30983) Make FlutterError objects more structured so they can be displayed better in debugging tools such as Dart DevTools. --- .../test_async_utils_guarded_expectation.txt | 18 +- ...test_async_utils_unguarded_expectation.txt | 14 +- .../image_loading/lib/main.dart | 2 +- .../lib/src/animation/listener_helpers.dart | 22 +- .../lib/src/foundation/assertions.dart | 563 ++++++-- .../flutter/lib/src/foundation/binding.dart | 2 +- .../lib/src/foundation/change_notifier.dart | 11 +- .../lib/src/foundation/diagnostics.dart | 1259 +++++++++++++---- .../flutter/lib/src/gestures/binding.dart | 19 +- .../lib/src/gestures/pointer_router.dart | 9 +- .../src/gestures/pointer_signal_resolver.dart | 7 +- .../flutter/lib/src/gestures/recognizer.dart | 11 +- .../lib/src/material/refresh_indicator.dart | 2 +- .../lib/src/painting/image_provider.dart | 30 +- .../lib/src/painting/image_stream.dart | 16 +- packages/flutter/lib/src/rendering/box.dart | 161 +-- .../rendering/debug_overflow_indicator.dart | 49 +- packages/flutter/lib/src/rendering/flex.dart | 106 +- packages/flutter/lib/src/rendering/layer.dart | 12 +- .../flutter/lib/src/rendering/object.dart | 77 +- .../flutter/lib/src/rendering/sliver.dart | 116 +- .../flutter/lib/src/scheduler/binding.dart | 34 +- .../lib/src/services/platform_channel.dart | 4 +- .../lib/src/services/platform_messages.dart | 4 +- packages/flutter/lib/src/widgets/binding.dart | 2 +- .../flutter/lib/src/widgets/framework.dart | 117 +- packages/flutter/lib/src/widgets/image.dart | 2 +- .../lib/src/widgets/layout_builder.dart | 6 +- packages/flutter/lib/src/widgets/sliver.dart | 3 +- .../lib/src/widgets/widget_inspector.dart | 122 +- .../test/foundation/assertions_test.dart | 268 +++- .../test/foundation/diagnostics_test.dart | 605 +++++++- .../test/foundation/error_reporting_test.dart | 41 +- .../foundation/service_extensions_test.dart | 2 +- .../material/paginated_data_table_test.dart | 11 +- .../debug_overflow_indicator_test.dart | 5 +- .../widgets/global_keys_duplicated_test.dart | 2 +- .../test/widgets/physical_model_test.dart | 5 +- .../test/widgets/semantics_clipping_test.dart | 10 +- packages/flutter_test/lib/src/binding.dart | 30 +- packages/flutter_test/lib/src/matchers.dart | 2 +- .../lib/src/stack_manipulation.dart | 16 +- .../lib/src/test_async_utils.dart | 101 +- packages/flutter_test/test/matchers_test.dart | 3 +- .../test/stack_manipulation_test.dart | 10 +- .../test/test_async_utils_test.dart | 129 +- .../test/commands/test_test.dart | 14 +- 47 files changed, 3103 insertions(+), 951 deletions(-) diff --git a/dev/automated_tests/flutter_test/test_async_utils_guarded_expectation.txt b/dev/automated_tests/flutter_test/test_async_utils_guarded_expectation.txt index 6cb6a93b63..6eee274d11 100644 --- a/dev/automated_tests/flutter_test/test_async_utils_guarded_expectation.txt +++ b/dev/automated_tests/flutter_test/test_async_utils_guarded_expectation.txt @@ -1,11 +1,19 @@ <> ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ The following assertion was thrown running a test: -Guarded function conflict\. You must use "await" with all Future-returning test APIs\. -The guarded "guardedHelper" function was called from .*dev/automated_tests/flutter_test/test_async_utils_guarded_test\.dart on line [0-9]+\. -Then, the "expect" function was called from .*dev/automated_tests/flutter_test/test_async_utils_guarded_test\.dart on line [0-9]+\. -The first function \(guardedHelper\) had not yet finished executing at the time that the second function \(expect\) was called\. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called\. Typically, this is achieved by putting an "await" statement in front of the call to the first\. -If you are confident that all test APIs are being called using "await", and this expect\(\) call is not being called at the top level but is itself being called from some sort of callback registered before the guardedHelper method was called, then consider using expectSync\(\) instead\. +Guarded function conflict\. +You must use "await" with all Future-returning test APIs\. +The guarded "guardedHelper" function was called from +.*dev/automated_tests/flutter_test/test_async_utils_guarded_test\.dart[ \n]on[ \n]line[ \n][0-9]+\. +Then, the "expect" function was called from +.*dev/automated_tests/flutter_test/test_async_utils_guarded_test\.dart[ \n]on[ \n]line[ \n][0-9]+\. +The first function \(guardedHelper\) had not yet finished executing at the time that the second +function \(expect\) was called\. Since both are guarded, and the second was not a nested call inside +the first, the first must complete its execution before the second can be called\. Typically, this is +achieved by putting an "await" statement in front of the call to the first\. +If you are confident that all test APIs are being called using "await", and this expect\(\) call is +not being called at the top level but is itself being called from some sort of callback registered +before the guardedHelper method was called, then consider using expectSync\(\) instead\. When the first function \(guardedHelper\) was called, this was the stack: <> diff --git a/dev/automated_tests/flutter_test/test_async_utils_unguarded_expectation.txt b/dev/automated_tests/flutter_test/test_async_utils_unguarded_expectation.txt index bbacef485c..c5b94b9bbe 100644 --- a/dev/automated_tests/flutter_test/test_async_utils_unguarded_expectation.txt +++ b/dev/automated_tests/flutter_test/test_async_utils_unguarded_expectation.txt @@ -2,10 +2,16 @@ <> ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ The following assertion was thrown running a test: -Guarded function conflict\. You must use "await" with all Future-returning test APIs\. -The guarded method "pump" from class WidgetTester was called from .*dev/automated_tests/flutter_test/test_async_utils_unguarded_test.dart on line [0-9]+\. -Then, it was called again from .*dev/automated_tests/flutter_test/test_async_utils_unguarded_test.dart on line [0-9]+\. -The first method had not yet finished executing at the time that the second method was called\. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called\. Typically, this is achieved by putting an "await" statement in front of the call to the first\. +Guarded function conflict\. +You must use "await" with all Future-returning test APIs\. +The guarded method "pump" from class WidgetTester was called from +.*dev/automated_tests/flutter_test/test_async_utils_unguarded_test.dart[ \n]on[ \n]line[ \n][0-9]+\. +Then, it was called again from +.*dev/automated_tests/flutter_test/test_async_utils_unguarded_test.dart[ \n]on[ \n]line[ \n][0-9]+\. +The first method had not yet finished executing at the time that the second method was called\. Since +both are guarded, and the second was not a nested call inside the first, the first must complete its +execution before the second can be called\. Typically, this is achieved by putting an "await" +statement in front of the call to the first\. When the first method was called, this was the stack: <> diff --git a/dev/integration_tests/image_loading/lib/main.dart b/dev/integration_tests/image_loading/lib/main.dart index a1a3e8e9c2..ac4cb5d373 100644 --- a/dev/integration_tests/image_loading/lib/main.dart +++ b/dev/integration_tests/image_loading/lib/main.dart @@ -16,7 +16,7 @@ void main() { handleUncaughtError:(Zone zone, ZoneDelegate delegate, Zone parent, Object error, StackTrace stackTrace) { FlutterError.reportError(FlutterErrorDetails( exception: error, - context: 'In the Zone handleUncaughtError handler', + context: ErrorDescription('In the Zone handleUncaughtError handler'), silent: false, )); }); diff --git a/packages/flutter/lib/src/animation/listener_helpers.dart b/packages/flutter/lib/src/animation/listener_helpers.dart index 751f5c98df..2236ac5d3b 100644 --- a/packages/flutter/lib/src/animation/listener_helpers.dart +++ b/packages/flutter/lib/src/animation/listener_helpers.dart @@ -129,10 +129,13 @@ mixin AnimationLocalListenersMixin { exception: exception, stack: stack, library: 'animation library', - context: 'while notifying listeners for $runtimeType', - informationCollector: (StringBuffer information) { - information.writeln('The $runtimeType notifying listeners was:'); - information.write(' $this'); + context: ErrorDescription('while notifying listeners for $runtimeType'), + informationCollector: () sync* { + yield DiagnosticsProperty( + 'The $runtimeType notifying listeners was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ); }, )); } @@ -195,10 +198,13 @@ mixin AnimationLocalStatusListenersMixin { exception: exception, stack: stack, library: 'animation library', - context: 'while notifying status listeners for $runtimeType', - informationCollector: (StringBuffer information) { - information.writeln('The $runtimeType notifying status listeners was:'); - information.write(' $this'); + context: ErrorDescription('while notifying status listeners for $runtimeType'), + informationCollector: () sync* { + yield DiagnosticsProperty( + 'The $runtimeType notifying status listeners was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ); }, )); } diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index 14998557e3..0438a910c0 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -2,20 +2,183 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:meta/meta.dart'; + import 'basic_types.dart'; +import 'diagnostics.dart'; import 'print.dart'; /// Signature for [FlutterError.onError] handler. typedef FlutterExceptionHandler = void Function(FlutterErrorDetails details); /// Signature for [FlutterErrorDetails.informationCollector] callback -/// and other callbacks that collect information into a string buffer. -typedef InformationCollector = void Function(StringBuffer information); +/// and other callbacks that collect information describing an error. +typedef InformationCollector = Iterable Function(); + +abstract class _ErrorDiagnostic extends DiagnosticsProperty> { + /// This constructor provides a reliable hook for a kernel transformer to find + /// error messages that need to be rewritten to include object references for + /// interactive display of errors. + _ErrorDiagnostic( + String message, { + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.flat, + DiagnosticLevel level = DiagnosticLevel.info, + }) : assert(message != null), + super( + null, + [message], + showName: false, + showSeparator: false, + defaultValue: null, + style: style, + level: level, + ); + + /// In debug builds, a kernel transformer rewrites calls to the default + /// constructors for [ErrorSummary], [ErrorDetails], and [ErrorHint] to use + /// this constructor. + // + // ```dart + // _ErrorDiagnostic('Element $element must be $color') + // ``` + // Desugars to: + // ```dart + // _ErrorDiagnostic.fromParts(['Element ', element, ' must be ', color]) + // ``` + // + // Slightly more complex case: + // ```dart + // _ErrorDiagnostic('Element ${element.runtimeType} must be $color') + // ``` + // Desugars to: + //```dart + // _ErrorDiagnostic.fromParts([ + // 'Element ', + // DiagnosticsProperty(null, element, description: element.runtimeType?.toString()), + // ' must be ', + // color, + // ]) + // ``` + _ErrorDiagnostic._fromParts( + List messageParts, { + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.flat, + DiagnosticLevel level = DiagnosticLevel.info, + }) : assert(messageParts != null), + super( + null, + messageParts, + showName: false, + showSeparator: false, + defaultValue: null, + style: style, + level: level, + ); + + @override + String valueToString({ TextTreeConfiguration parentConfiguration }) { + return value.join(''); + } +} + +/// An explanation of the problem and its cause, any information that may help +/// track down the problem, background information, etc. +/// +/// Use [ErrorDescription] for any part of an error message where neither +/// [ErrorSummary] or [ErrorHint] is appropriate. +/// +/// See also: +/// +/// * [ErrorSummary], which provides a short (one line) description of the +/// problem that was detected. +/// * [ErrorHint], which provides specific, non-obvious advice that may be +/// applicable. +/// * [FlutterError], which is the most common place to use an +/// [ErrorDescription]. +class ErrorDescription extends _ErrorDiagnostic { + /// A lint enforces that this constructor can only be called with a string + /// literal to match the limitations of the Dart Kernel transformer that + /// optionally extracts out objects referenced using string interpolation in + /// the message passed in. + /// + /// The message will display with the same text regardless of whether the + /// kernel transformer is used. The kernel transformer is required so that + /// debugging tools can provide interactive displays of objects described by + /// the error. + ErrorDescription(String message) : super(message, level: DiagnosticLevel.info); + + /// Calls to the default constructor may be rewritten to use this constructor + /// in debug mode using a kernel transformer. + ErrorDescription._fromParts(List messageParts) : super._fromParts(messageParts, level: DiagnosticLevel.info); +} + +/// A short (one line) description of the problem that was detected. +/// +/// Error summaries from the same source location should have little variance, +/// so that they can be recognized as related. For example, they shouldn't +/// include hash codes. +/// +/// A [FlutterError] must start with an [ErrorSummary] and may not contain +/// multiple summaries. +/// +/// See also: +/// +/// * [ErrorDescription], which provides an explanation of the problem and its +/// cause, any information that may help track down the problem, background +/// information, etc. +/// * [ErrorHint], which provides specific, non-obvious advice that may be +/// applicable. +/// * [FlutterError], which is the most common place to use an [ErrorSummary]. +class ErrorSummary extends _ErrorDiagnostic { + /// A lint enforces that this constructor can only be called with a string + /// literal to match the limitations of the Dart Kernel transformer that + /// optionally extracts out objects referenced using string interpolation in + /// the message passed in. + /// + /// The message will display with the same text regardless of whether the + /// kernel transformer is used. The kernel transformer is required so that + /// debugging tools can provide interactive displays of objects described by + /// the error. + ErrorSummary(String message) : super(message, level: DiagnosticLevel.summary); + + /// Calls to the default constructor may be rewritten to use this constructor + /// in debug mode using a kernel transformer. + ErrorSummary._fromParts(List messageParts) : super._fromParts(messageParts, level: DiagnosticLevel.summary); +} + +/// An [ErrorHint] provides specific, non-obvious advice that may be applicable. +/// +/// If your message provides obvious advice that is always applicable it is an +/// [ErrorDescription] not a hint. +/// +/// See also: +/// +/// * [ErrorSummary], which provides a short (one line) description of the +/// problem that was detected. +/// * [ErrorDescription], which provides an explanation of the problem and its +/// cause, any information that may help track down the problem, background +/// information, etc. +/// * [FlutterError], which is the most common place to use an [ErrorHint]. +class ErrorHint extends _ErrorDiagnostic { + /// A lint enforces that this constructor can only be called with a string + /// literal to match the limitations of the Dart Kernel transformer that + /// optionally extracts out objects referenced using string interpolation in + /// the message passed in. + /// + /// The message will display with the same text regardless of whether the + /// kernel transformer is used. The kernel transformer is required so that + /// debugging tools can provide interactive displays of objects described by + /// the error. + ErrorHint(String message) : super(message, level:DiagnosticLevel.hint); + + /// Calls to the default constructor may be rewritten to use this constructor + /// in debug mode using a kernel transformer. + ErrorHint._fromParts(List messageParts) : super._fromParts(messageParts, level:DiagnosticLevel.hint); +} /// Class for information provided to [FlutterExceptionHandler] callbacks. /// /// See [FlutterError.onError]. -class FlutterErrorDetails { +class FlutterErrorDetails extends Diagnosticable { /// Creates a [FlutterErrorDetails] object with the given arguments setting /// the object's properties. /// @@ -64,7 +227,7 @@ class FlutterErrorDetails { /// following the word "thrown", as in "thrown while obtaining the image from /// the network" (for the context "while obtaining the image from the /// network"). - final String context; + final DiagnosticsNode context; /// A callback which filters the [stack] trace. Receives an iterable of /// strings representing the frames encoded in the way that @@ -120,7 +283,7 @@ class FlutterErrorDetails { // some code snippets. This leads to ugly messages. To avoid this, we move // the assertion message up to before the code snippets, separated by a // newline, if we recognise that format is being used. - final String message = exception.message; + final Object message = exception.message; final String fullMessage = exception.toString(); if (message is String && message != fullMessage) { if (fullMessage.length > message.length) { @@ -128,7 +291,14 @@ class FlutterErrorDetails { if (position == fullMessage.length - message.length && position > 2 && fullMessage.substring(position - 2, position) == ': ') { - longMessage = '${message.trimRight()}\n${fullMessage.substring(0, position - 2)}'; + // Add a linebreak so that the filename at the start of the + // assertion message is always on its own line. + String body = fullMessage.substring(0, position - 2); + final int splitPoint = body.indexOf(' Failed assertion:'); + if (splitPoint >= 0) { + body = '${body.substring(0, splitPoint)}\n${body.substring(splitPoint + 1)}'; + } + longMessage = '${message.trimRight()}\n$body'; } } } @@ -146,53 +316,124 @@ class FlutterErrorDetails { return longMessage; } + Diagnosticable _exceptionToDiagnosticable() { + if (exception is FlutterError) { + return exception; + } + if (exception is AssertionError && exception.message is FlutterError) { + return exception.message; + } + return null; + } + + /// Returns a short (one line) description of the problem that was detected. + /// + /// If the exception contains an [ErrorSummary] that summary is used, + /// otherwise the summary is inferred from the string representation of the + /// exception. + DiagnosticsNode get summary { + final Diagnosticable diagnosticable = _exceptionToDiagnosticable(); + DiagnosticsNode summary; + if (diagnosticable != null) { + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + debugFillProperties(builder); + summary = builder.properties.firstWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.summary, orElse: () => null); + } + return summary ?? ErrorSummary('${exceptionAsString().split("\n")[0].trimLeft()}'); + } + @override - String toString() { - final StringBuffer buffer = StringBuffer(); - if ((library != null && library != '') || (context != null && context != '')) { - if (library != null && library != '') { - buffer.write('Error caught by $library'); - if (context != null && context != '') - buffer.write(', '); - } else { - buffer.writeln('Exception '); - } - if (context != null && context != '') - buffer.write('thrown $context'); - buffer.writeln('.'); + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + final DiagnosticsNode verb = ErrorDescription('thrown${ context != null ? ErrorDescription(" $context") : ""}'); + final Diagnosticable diagnosticable = _exceptionToDiagnosticable(); + if (exception is NullThrownError) { + properties.add(ErrorDescription('The null value was $verb.')); + } else if (exception is num) { + properties.add(ErrorDescription('The number $exception was $verb.')); } else { - buffer.write('An error was caught.'); - } - buffer.writeln(exceptionAsString()); - if (informationCollector != null) - informationCollector(buffer); - if (stack != null) { - Iterable stackLines = stack.toString().trimRight().split('\n'); - if (stackFilter != null) { - stackLines = stackFilter(stackLines); + DiagnosticsNode errorName; + if (exception is AssertionError) { + errorName = ErrorDescription('assertion'); + } else if (exception is String) { + errorName = ErrorDescription('message'); + } else if (exception is Error || exception is Exception) { + errorName = ErrorDescription('${exception.runtimeType}'); } else { - stackLines = FlutterError.defaultStackFilter(stackLines); + errorName = ErrorDescription('${exception.runtimeType} object'); + } + properties.add(ErrorDescription('The following $errorName was $verb:')); + if (diagnosticable != null) { + diagnosticable.debugFillProperties(properties); + } else { + // Many exception classes put their type at the head of their message. + // This is redundant with the way we display exceptions, so attempt to + // strip out that header when we see it. + final String prefix = '${exception.runtimeType}: '; + String message = exceptionAsString(); + if (message.startsWith(prefix)) + message = message.substring(prefix.length); + properties.add(ErrorDescription('$message')); } - buffer.writeAll(stackLines, '\n'); } - return buffer.toString().trimRight(); + + final Iterable stackLines = (stack != null) ? stack.toString().trimRight().split('\n') : null; + if (exception is AssertionError && diagnosticable == null) { + bool ourFault = true; + if (stackLines != null) { + final List stackList = stackLines.take(2).toList(); + if (stackList.length >= 2) { + // TODO(ianh): This has bitrotted and is no longer matching. https://github.com/flutter/flutter/issues/4021 + final RegExp throwPattern = RegExp( + r'^#0 +_AssertionError._throwNew \(dart:.+\)$'); + final RegExp assertPattern = RegExp( + r'^#1 +[^(]+ \((.+?):([0-9]+)(?::[0-9]+)?\)$'); + if (throwPattern.hasMatch(stackList[0])) { + final Match assertMatch = assertPattern.firstMatch(stackList[1]); + if (assertMatch != null) { + assert(assertMatch.groupCount == 2); + final RegExp ourLibraryPattern = RegExp(r'^package:flutter/'); + ourFault = ourLibraryPattern.hasMatch(assertMatch.group(1)); + } + } + } + } + if (ourFault) { + properties.add(DiagnosticsNode.message('')); + properties.add(ErrorHint( + 'Either the assertion indicates an error in the framework itself, or we should ' + 'provide substantially more information in this error message to help you determine ' + 'and fix the underlying cause.\n' + 'In either case, please report this assertion by filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md' + )); + } + } + if (stack != null) { + properties.add(DiagnosticsNode.message('')); + properties.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', stack, stackFilter: stackFilter)); + } + if (informationCollector != null) { + properties.add(DiagnosticsNode.message('')); + informationCollector().forEach(properties.add); + } + } + + @override + String toStringShort() { + return library != null ? 'Exception Caught By $library' : 'Exception Caught'; + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) { + return toDiagnosticsNode(style: DiagnosticsTreeStyle.error).toStringDeep(minLevel: minLevel); } } /// Error class used to report Flutter-specific assertion failures and /// contract violations. -class FlutterError extends AssertionError { - /// Creates a [FlutterError]. - /// - /// See [message] for details on the format that the message should - /// take. - /// - /// Include as much detail as possible in the full error message, - /// including specifics about the state of the app that might be - /// relevant to debugging the error. - FlutterError(String message) : super(message); - - /// The message associated with this error. +class FlutterError extends Error with DiagnosticableTreeMixin implements AssertionError { + /// Create an error message from a string. /// /// The message may have newlines in it. The first line should be a terse /// description of the error, e.g. "Incorrect GlobalKey usage" or "setState() @@ -207,11 +448,97 @@ class FlutterError extends AssertionError { /// /// All sentences in the error should be correctly punctuated (i.e., /// do end the error message with a period). - @override - String get message => super.message; + /// + /// This constructor defers to the [new FlutterError.fromParts] constructor. + /// The first line is wrapped in an implied [ErrorSummary], and subsequent + /// lines are wrapped in implied [ErrorDescription]s. Consider using the + /// [new FlutterError.fromParts] constructor to provide more detail, e.g. + /// using [ErrorHint]s or other [DiagnosticsNode]s. + factory FlutterError(String message) { + final List lines = message.split('\n'); + final List parts = []; + parts.add(ErrorSummary(lines.first)); + if (lines.length > 1) { + parts.addAll(lines.skip(1).map((String line) => ErrorDescription(line))); + } + return FlutterError.fromParts(parts); + } + /// Create an error message from a list of [DiagnosticsNode]s. + /// + /// By convention, there should be exactly one [FlutterSummary] in the list, + /// and it should be the first entry. + /// + /// Other entries are typically [ErrorDescription]s (for material that is + /// always applicable for this error) and [ErrorHint]s (for material that may + /// be sometimes useful, but may not always apply). Other [DiagnosticsNode] + /// subclasses, such as [DiagnosticsStackTrace], may + /// also be used. + FlutterError.fromParts(this.diagnostics) : assert(diagnostics.isNotEmpty, FlutterError.fromParts([ErrorSummary('Empty FlutterError')])) { + assert( + diagnostics.first.level == DiagnosticLevel.summary, + FlutterError.fromParts([ + ErrorSummary('FlutterError is missing a summary.'), + ErrorDescription( + 'All FlutterError objects should start with a short (one line) ' + 'summary description of the problem that was detected.' + ), + DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace), + ErrorDescription( + '\nThis error should still help you solve your problem, ' + 'however please also report this malformed error in the ' + 'framework by filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md' + ), + ], + )); + assert(() { + final Iterable summaries = diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.summary); + if (summaries.length > 1) { + final List message = [ + ErrorSummary('FlutterError contained multiple error summaries.'), + ErrorDescription( + 'All FlutterError objects should have only a single short ' + '(one line) summary description of the problem that was ' + 'detected.' + ), + ]; + message.add(DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace)); + message.add(ErrorDescription('\nThe malformed error has ${summaries.length} summaries.')); + int i = 1; + for (DiagnosticsNode summary in summaries) { + message.add(DiagnosticsProperty('Summary $i', summary, expandableValue : true)); + i += 1; + } + message.add(ErrorDescription( + '\nThis error should still help you solve your problem, ' + 'however please also report this malformed error in the ' + 'framework by filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md' + )); + throw FlutterError.fromParts(message); + } + return true; + }()); + } + + /// The information associated with this error, in structured form. + /// + /// The first node is typically an [ErrorSummary] giving a short description + /// of the problem, suitable for an index of errors, a log, etc. + /// + /// Subsequent nodes should give information specific to this error. Typically + /// these will be [ErrorDescription]s or [ErrorHint]s, but they could be other + /// objects also. For instance, an error relating to a timer could include a + /// stack trace of when the timer was scheduled using the + /// [DiagnosticsStackTrace] class. + final List diagnostics; + + /// The message associated with this error. + /// + /// This is generated by serializing the [diagnostics]. @override - String toString() => message; + String get message => toString(); /// Called whenever the Flutter framework catches an error. /// @@ -267,79 +594,15 @@ class FlutterError extends AssertionError { if (!reportError && !forceReport) return; if (_errorCount == 0 || forceReport) { - final String header = '\u2550\u2550\u2561 EXCEPTION CAUGHT BY ${details.library} \u255E'.toUpperCase(); - final String footer = '\u2550' * wrapWidth; - debugPrint('$header${"\u2550" * (footer.length - header.length)}'); - final String verb = 'thrown${ details.context != null ? " ${details.context}" : ""}'; - if (details.exception is NullThrownError) { - debugPrint('The null value was $verb.', wrapWidth: wrapWidth); - } else if (details.exception is num) { - debugPrint('The number ${details.exception} was $verb.', wrapWidth: wrapWidth); - } else { - String errorName; - if (details.exception is AssertionError) { - errorName = 'assertion'; - } else if (details.exception is String) { - errorName = 'message'; - } else if (details.exception is Error || details.exception is Exception) { - errorName = '${details.exception.runtimeType}'; - } else { - errorName = '${details.exception.runtimeType} object'; - } - // Many exception classes put their type at the head of their message. - // This is redundant with the way we display exceptions, so attempt to - // strip out that header when we see it. - final String prefix = '${details.exception.runtimeType}: '; - String message = details.exceptionAsString(); - if (message.startsWith(prefix)) - message = message.substring(prefix.length); - debugPrint('The following $errorName was $verb:\n$message', wrapWidth: wrapWidth); - } - Iterable stackLines = (details.stack != null) ? details.stack.toString().trimRight().split('\n') : null; - if ((details.exception is AssertionError) && (details.exception is! FlutterError)) { - bool ourFault = true; - if (stackLines != null) { - final List stackList = stackLines.take(2).toList(); - if (stackList.length >= 2) { - // TODO(ianh): This has bitrotted and is no longer matching. https://github.com/flutter/flutter/issues/4021 - final RegExp throwPattern = RegExp(r'^#0 +_AssertionError._throwNew \(dart:.+\)$'); - final RegExp assertPattern = RegExp(r'^#1 +[^(]+ \((.+?):([0-9]+)(?::[0-9]+)?\)$'); - if (throwPattern.hasMatch(stackList[0])) { - final Match assertMatch = assertPattern.firstMatch(stackList[1]); - if (assertMatch != null) { - assert(assertMatch.groupCount == 2); - final RegExp ourLibraryPattern = RegExp(r'^package:flutter/'); - ourFault = ourLibraryPattern.hasMatch(assertMatch.group(1)); - } - } - } - } - if (ourFault) { - debugPrint('\nEither the assertion indicates an error in the framework itself, or we should ' - 'provide substantially more information in this error message to help you determine ' - 'and fix the underlying cause.', wrapWidth: wrapWidth); - debugPrint('In either case, please report this assertion by filing a bug on GitHub:', wrapWidth: wrapWidth); - debugPrint(' https://github.com/flutter/flutter/issues/new?template=BUG.md'); - } - } - if (details.stack != null) { - debugPrint('\nWhen the exception was thrown, this was the stack:', wrapWidth: wrapWidth); - if (details.stackFilter != null) { - stackLines = details.stackFilter(stackLines); - } else { - stackLines = defaultStackFilter(stackLines); - } - for (String line in stackLines) - debugPrint(line, wrapWidth: wrapWidth); - } - if (details.informationCollector != null) { - final StringBuffer information = StringBuffer(); - details.informationCollector(information); - debugPrint('\n${information.toString().trimRight()}', wrapWidth: wrapWidth); - } - debugPrint(footer); + debugPrint( + TextTreeRenderer( + wrapWidth: wrapWidth, + wrapWidthProperties: wrapWidth, + maxDescendentsTruncatableNode: 5, + ).render(details.toDiagnosticsNode(style: DiagnosticsTreeStyle.error)).trimRight() + ); } else { - debugPrint('Another exception was thrown: ${details.exceptionAsString().split("\n")[0].trimLeft()}'); + debugPrint('Another exception was thrown: ${details.summary}'); } _errorCount += 1; } @@ -405,6 +668,21 @@ class FlutterError extends AssertionError { return result; } + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + diagnostics?.forEach(properties.add); + } + + @override + String toStringShort() => 'FlutterError'; + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) { + // Avoid wrapping lines. + final TextTreeRenderer renderer = TextTreeRenderer(wrapWidth: 4000000000); + return diagnostics.map((DiagnosticsNode node) => renderer.render(node).trimRight()).join('\n'); + } + /// Calls [onError] with the given details, unless it is null. static void reportError(FlutterErrorDetails details) { assert(details != null); @@ -431,3 +709,52 @@ void debugPrintStack({ String label, int maxFrames }) { lines = lines.take(maxFrames); debugPrint(FlutterError.defaultStackFilter(lines).join('\n')); } + +/// Diagnostic with a [StackTrace] [value] suitable for displaying stacktraces +/// as part of a [FlutterError] object. +/// +/// See also: +/// +/// * [FlutterErrorBuilder.addStackTrace], which is the typical way [StackTrace] +/// objects are added to a [FlutterError]. +class DiagnosticsStackTrace extends DiagnosticsBlock { + /// Creates a diagnostic for a stack trace. + /// + /// [name] describes a name the stacktrace is given, e.g. + /// `When the exception was thrown, this was the stack`. + /// [stackFilter] provides an optional filter to use to filter which frames + /// are included. If no filter is specified, [FlutterError.defaultStackFilter] + /// is used. + /// [showSeparator] indicates whether to include a ':' after the [name]. + DiagnosticsStackTrace( + String name, + StackTrace stack, { + IterableFilter stackFilter, + bool showSeparator = true, + }) : super( + name: name, + value: stack, + properties: (stackFilter ?? FlutterError.defaultStackFilter)(stack.toString().trimRight().split('\n')) + .map(_createStackFrame) + .toList(), + style: DiagnosticsTreeStyle.flat, + showSeparator: showSeparator, + allowTruncate: true, + ); + + /// Creates a diagnostic describing a single frame from a StackTrace. + DiagnosticsStackTrace.singleFrame( + String name, { + @required String frame, + bool showSeparator = true, + }) : super( + name: name, + properties: [_createStackFrame(frame)], + style: DiagnosticsTreeStyle.whitespace, + showSeparator: showSeparator, + ); + + static DiagnosticsNode _createStackFrame(String frame) { + return DiagnosticsNode.message(frame, allowWrap: false); + } +} diff --git a/packages/flutter/lib/src/foundation/binding.dart b/packages/flutter/lib/src/foundation/binding.dart index 57284741bf..a5e9f6e505 100644 --- a/packages/flutter/lib/src/foundation/binding.dart +++ b/packages/flutter/lib/src/foundation/binding.dart @@ -522,7 +522,7 @@ abstract class BindingBase { FlutterError.reportError(FlutterErrorDetails( exception: caughtException, stack: caughtStack, - context: 'during a service extension callback for "$method"', + context: ErrorDescription('during a service extension callback for "$method"'), )); return developer.ServiceExtensionResponse.error( developer.ServiceExtensionResponse.extensionError, diff --git a/packages/flutter/lib/src/foundation/change_notifier.dart b/packages/flutter/lib/src/foundation/change_notifier.dart index 47de62c028..1e51dd1560 100644 --- a/packages/flutter/lib/src/foundation/change_notifier.dart +++ b/packages/flutter/lib/src/foundation/change_notifier.dart @@ -209,10 +209,13 @@ class ChangeNotifier implements Listenable { exception: exception, stack: stack, library: 'foundation library', - context: 'while dispatching notifications for $runtimeType', - informationCollector: (StringBuffer information) { - information.writeln('The $runtimeType sending notification was:'); - information.write(' $this'); + context: ErrorDescription('while dispatching notifications for $runtimeType'), + informationCollector: () sync* { + yield DiagnosticsProperty( + 'The $runtimeType sending notification was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ); }, )); } diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index c4752bff93..79389543c6 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:math' as math; + import 'package:meta/meta.dart'; -import 'print.dart'; +import 'assertions.dart'; // Examples can assume: // int rows, columns; @@ -56,6 +58,17 @@ enum DiagnosticLevel { /// message in ALL CAPS. warning, + /// Diagnostics that provide a hint about best practices. + /// + /// For example, a diagnostic describing best practices for fixing an error. + hint, + + /// Diagnostics that summarize other diagnostics present. + /// + /// For example, use this level for a short one or two line summary + /// describing other diagnostics present. + summary, + /// Diagnostics that indicate errors or unexpected conditions. /// /// For example, use for property values where computing the value throws an @@ -107,6 +120,14 @@ enum DiagnosticsTreeStyle { /// style of the [RenderObject] tree. transition, + /// Style for displaying content describing an error. + /// + /// See also: + /// + /// * [FlutterError], which uses this style for the root node in a tree + /// describing an error. + error, + /// Render the tree just using whitespace without connecting parents to /// children using lines. /// @@ -115,8 +136,38 @@ enum DiagnosticsTreeStyle { /// * [SliverGeometry], which uses this style. whitespace, + /// Render the tree without indenting children at all. + /// + /// See also: + /// + /// * [DiagnosticsStackTrace], which uses this style. + flat, + /// Render the tree on a single line without showing children. singleLine, + + /// Render the tree using a style appropriate for properties that are part + /// of an error message. + /// + /// The name is placed on one line with the value and properties placed on + /// the following line. + /// + /// See also: + /// * [singleLine], which displays the same information but keeps the + /// property and value on the same line. + errorProperty, + + /// Render only the immediate properties of a node instead of the full tree. + /// + /// See also: + /// + /// * [DebugOverflowIndicator], which uses this style to display just the + /// immediate children of a node. + shallow, + + /// Render only the children of a node truncating before the tree becomes too + /// large. + truncateChildren, } /// Configuration specifying how a particular [DiagnosticsTreeStyle] should be @@ -144,8 +195,10 @@ class TextTreeConfiguration { this.lineBreakProperties = true, this.afterName = ':', this.afterDescriptionIfBody = '', + this.afterDescription = '', this.beforeProperties = '', this.afterProperties = '', + this.mandatoryAfterProperties = '', this.propertySeparator = '', this.bodyIndent = '', this.footer = '', @@ -153,6 +206,9 @@ class TextTreeConfiguration { this.addBlankLineIfNoChildren = true, this.isNameOnOwnLine = false, this.isBlankLineBetweenPropertiesAndChildren = true, + this.beforeName = '', + this.suffixLineOne = '', + this.manditoryFooter = '', }) : assert(prefixLineOne != null), assert(prefixOtherLines != null), assert(prefixLastChildLineOne != null), @@ -164,6 +220,7 @@ class TextTreeConfiguration { assert(lineBreakProperties != null), assert(afterName != null), assert(afterDescriptionIfBody != null), + assert(afterDescription != null), assert(beforeProperties != null), assert(afterProperties != null), assert(propertySeparator != null), @@ -178,6 +235,9 @@ class TextTreeConfiguration { /// Prefix to add to the first line to display a child with this style. final String prefixLineOne; + /// Suffix to add to end of the first line to make its length match the footer. + final String suffixLineOne; + /// Prefix to add to other lines to display a child with this style. /// /// [prefixOtherLines] should typically be one character shorter than @@ -226,6 +286,13 @@ class TextTreeConfiguration { /// properties on one line. final bool lineBreakProperties; + + /// Text added immediately before the name of the node. + /// + /// See [errorTextConfiguration] for an example of using this to achieve a + /// custom line art style. + final String beforeName; + /// Text added immediately after the name of the node. /// /// See [transitionTextConfiguration] for an example of using a value other @@ -233,9 +300,13 @@ class TextTreeConfiguration { final String afterName; /// Text to add immediately after the description line of a node with - /// properties and/or children. + /// properties and/or children if the node has a body. final String afterDescriptionIfBody; + /// Text to add immediately after the description line of a node with + /// properties and/or children. + final String afterDescription; + /// Optional string to add before the properties of a node. /// /// Only displayed if the node has properties. @@ -248,6 +319,13 @@ class TextTreeConfiguration { /// See documentation for [beforeProperties]. final String afterProperties; + /// Mandatory string to add after the properties of a node regardless of + /// whether the node has any properties. + /// + /// See [headerLineTextConfiguration] for an example of using this field to + /// add a colon at the end of the header line. + final String mandatoryAfterProperties; + /// Property separator to add between properties. /// /// See [singleLineTextConfiguration] for an example of using this field @@ -280,6 +358,9 @@ class TextTreeConfiguration { /// around the node. [footer] is indented the same amount as [prefixOtherLines]. final String footer; + /// Footer to add even for root nodes. + final String manditoryFooter; + /// Add a blank line between properties and children if both are present. final bool isBlankLineBetweenPropertiesAndChildren; } @@ -314,7 +395,7 @@ class TextTreeConfiguration { /// /// See also: /// -/// * [DiagnosticsTreeStyle.sparse] +/// * [DiagnosticsTreeStyle.sparse], uses this style for ASCII art display. final TextTreeConfiguration sparseTextConfiguration = TextTreeConfiguration( prefixLineOne: '├─', prefixOtherLines: ' ', @@ -392,7 +473,7 @@ final TextTreeConfiguration dashedTextConfiguration = TextTreeConfiguration( /// /// See also: /// -/// * [DiagnosticsTreeStyle.dense] +/// * [DiagnosticsTreeStyle.dense], uses this style for ASCII art display. final TextTreeConfiguration denseTextConfiguration = TextTreeConfiguration( propertySeparator: ', ', beforeProperties: '(', @@ -431,12 +512,12 @@ final TextTreeConfiguration denseTextConfiguration = TextTreeConfiguration( /// /// /// See also: /// -/// * [DiagnosticsTreeStyle.transition] +/// * [DiagnosticsTreeStyle.transition], uses this style for ASCII art display. final TextTreeConfiguration transitionTextConfiguration = TextTreeConfiguration( prefixLineOne: '╞═╦══ ', prefixLastChildLineOne: '╘═╦══ ', prefixOtherLines: ' ║ ', - footer: ' ╚═══════════\n', + footer: ' ╚═══════════', linkCharacter: '│', // Subtree boundaries are clear due to the border around the node so omit the // property prefix. @@ -458,6 +539,70 @@ final TextTreeConfiguration transitionTextConfiguration = TextTreeConfiguration( isBlankLineBetweenPropertiesAndChildren: false, ); +/// Configuration that draws a box around a node ignoring the connection to the +/// parents. +/// +/// If nested in a tree, this node is best displayed in the property box rather +/// than as a traditional child. +/// +/// Used to draw a decorative box around detailed descriptions of an exception. +/// +/// Example: +/// ``` +/// ══╡ : ╞═════════════════════════════════════ +/// +/// ... +/// ├─: +/// ╎ │ +/// ╎ │ +/// ╎ │ ... +/// ╎ │ +/// ╎ │ +/// ╎ └─: +/// ╎ +/// ╎ +/// ╎ ... +/// ╎ +/// ╎ +/// ╎╌: +/// ╎ │ +/// ╎ │ +/// ╎ │ ... +/// ╎ │ +/// ╎ │ +/// ╎ └─: +/// ╎ +/// ╎ +/// ╎ ... +/// ╎ +/// ╎ +/// └╌: ' +/// ════════════════════════════════════════════════════════════════ +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.error], uses this style for ASCII art display. +final TextTreeConfiguration errorTextConfiguration = TextTreeConfiguration( + prefixLineOne: '╞═╦', + prefixLastChildLineOne: '╘═╦', + prefixOtherLines: ' ║ ', + footer: ' ╚═══════════', + linkCharacter: '│', + // Subtree boundaries are clear due to the border around the node so omit the + // property prefix. + propertyPrefixIfChildren: '', + propertyPrefixNoChildren: '', + prefixOtherLinesRootNode: '', + beforeName: '══╡ ', + suffixLineOne: ' ╞══', + manditoryFooter: '═════', + // No need to add a blank line as the footer makes the boundary of this + // subtree unambiguous. + addBlankLineIfNoChildren: false, + isBlankLineBetweenPropertiesAndChildren: false, +); + /// Whitespace only configuration where children are consistently indented /// two spaces. /// @@ -478,7 +623,7 @@ final TextTreeConfiguration transitionTextConfiguration = TextTreeConfiguration( /// /// See also: /// -/// * [DiagnosticsTreeStyle.whitespace] +/// * [DiagnosticsTreeStyle.whitespace], uses this style for ASCII art display. final TextTreeConfiguration whitespaceTextConfiguration = TextTreeConfiguration( prefixLineOne: '', prefixLastChildLineOne: '', @@ -495,6 +640,40 @@ final TextTreeConfiguration whitespaceTextConfiguration = TextTreeConfiguration( isBlankLineBetweenPropertiesAndChildren: false, ); +/// Whitespace only configuration where children are not indented. +/// +/// Use this style when indentation is not needed to disambiguate parents from +/// children as in the case of a [DiagnosticsStackTrace]. +/// +/// Example: +/// ``` +/// +/// : : +/// +/// +/// : : +/// +/// +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.flat], uses this style for ASCII art display. +final TextTreeConfiguration flatTextConfiguration = TextTreeConfiguration( + prefixLineOne: '', + prefixLastChildLineOne: '', + prefixOtherLines: '', + prefixOtherLinesRootNode: '', + bodyIndent: '', + propertyPrefixIfChildren: '', + propertyPrefixNoChildren: '', + linkCharacter: '', + addBlankLineIfNoChildren: false, + // Add a colon after the description and before the properties to link the + // properties to the description line. + afterDescriptionIfBody: ':', + isBlankLineBetweenPropertiesAndChildren: false, +); /// Render a node as a single line omitting children. /// /// Example: @@ -502,7 +681,7 @@ final TextTreeConfiguration whitespaceTextConfiguration = TextTreeConfiguration( /// /// See also: /// -/// * [DiagnosticsTreeStyle.singleLine] +/// * [DiagnosticsTreeStyle.singleLine], uses this style for ASCII art display. final TextTreeConfiguration singleLineTextConfiguration = TextTreeConfiguration( propertySeparator: ', ', beforeProperties: '(', @@ -514,12 +693,74 @@ final TextTreeConfiguration singleLineTextConfiguration = TextTreeConfiguration( lineBreakProperties: false, addBlankLineIfNoChildren: false, showChildren: false, - propertyPrefixIfChildren: '', - propertyPrefixNoChildren: '', + propertyPrefixIfChildren: ' ', + propertyPrefixNoChildren: ' ', linkCharacter: '', prefixOtherLinesRootNode: '', ); +/// Render the name on a line followed by the body and properties on the next +/// line omitting the children. +/// +/// Example: +/// ``` +/// : +/// (, , ..., ) +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.errorProperty], uses this style for ASCII art +/// display. +final TextTreeConfiguration errorPropertyTextConfiguration = TextTreeConfiguration( + propertySeparator: ', ', + beforeProperties: '(', + afterProperties: ')', + prefixLineOne: '', + prefixOtherLines: '', + prefixLastChildLineOne: '', + lineBreak: '\n', + lineBreakProperties: false, + addBlankLineIfNoChildren: false, + showChildren: false, + propertyPrefixIfChildren: ' ', + propertyPrefixNoChildren: ' ', + linkCharacter: '', + prefixOtherLinesRootNode: '', + afterName: ':', + isNameOnOwnLine: true, +); + +/// Render a node on multiple lines omitting children. +/// +/// Example: +/// `: +/// +/// +/// ` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.shallow] +final TextTreeConfiguration shallowTextConfiguration = TextTreeConfiguration( + prefixLineOne: '', + prefixLastChildLineOne: '', + prefixOtherLines: ' ', + prefixOtherLinesRootNode: ' ', + bodyIndent: '', + propertyPrefixIfChildren: '', + propertyPrefixNoChildren: '', + linkCharacter: ' ', + addBlankLineIfNoChildren: false, + // Add a colon after the description and before the properties to link the + // properties to the description line. + afterDescriptionIfBody: ':', + isBlankLineBetweenPropertiesAndChildren: false, + showChildren: false, +); + +enum _WordWrapParseMode { inSpace, inWord, atBreak } + /// Builder that builds a String with specified prefixes for the first and /// subsequent lines. /// @@ -528,7 +769,11 @@ final TextTreeConfiguration singleLineTextConfiguration = TextTreeConfiguration( /// prefixed by [prefixLineOne] and subsequent lines prefixed by /// [prefixOtherLines]. class _PrefixedStringBuilder { - _PrefixedStringBuilder(this.prefixLineOne, this.prefixOtherLines); + _PrefixedStringBuilder({ + @required this.prefixLineOne, + @required String prefixOtherLines, + this.wrapWidth}) : + _prefixOtherLines = prefixOtherLines; /// Prefix to add to the first line. final String prefixLineOne; @@ -537,89 +782,262 @@ class _PrefixedStringBuilder { /// /// The prefix can be modified while the string is being built in which case /// subsequent lines will be added with the modified prefix. - String prefixOtherLines; + String get prefixOtherLines => _nextPrefixOtherLines ?? _prefixOtherLines; + String _prefixOtherLines; + set prefixOtherLines(String prefix) { + _prefixOtherLines = prefix; + _nextPrefixOtherLines = null; + } + String _nextPrefixOtherLines; + void incrementPrefixOtherLines(String suffix, {@required bool updateCurrentLine}) { + if (_currentLine.isEmpty || updateCurrentLine) { + _prefixOtherLines = prefixOtherLines + suffix; + _nextPrefixOtherLines = null; + } else { + _nextPrefixOtherLines = prefixOtherLines + suffix; + } + } + + final int wrapWidth; + + /// Buffer containing lines that have already been completely laid out. final StringBuffer _buffer = StringBuffer(); - bool _atLineStart = true; - bool _hasMultipleLines = false; + /// Buffer containing the current line that has not yet been wrapped. + final StringBuffer _currentLine = StringBuffer(); + /// List of pairs of integers indicating the start and end of each block of + /// text within _currentLine that can be wrapped. + final List _wrappableRanges = []; /// Whether the string being built already has more than 1 line. - bool get hasMultipleLines => _hasMultipleLines; + bool get requiresMultipleLines => _numLines > 1 || (_numLines == 1 && _currentLine.isNotEmpty) || + (_currentLine.length + _getCurrentPrefix(true).length > wrapWidth); + + bool get isCurrentLineEmpty => _currentLine.isEmpty; + + int _numLines = 0; + + void _finalizeLine(bool addTrailingLineBreak) { + final bool firstLine = _buffer.isEmpty; + final String text = _currentLine.toString(); + _currentLine.clear(); + + if (_wrappableRanges.isEmpty) { + // Fast path. There were no wrappable spans of text. + _writeLine( + text, + includeLineBreak: addTrailingLineBreak, + firstLine: firstLine, + ); + return; + } + final Iterable lines = _wordWrapLine( + text, + _wrappableRanges, + wrapWidth, + startOffset: firstLine ? prefixLineOne.length : _prefixOtherLines.length, + otherLineOffset: firstLine ? _prefixOtherLines.length : _prefixOtherLines.length, + ); + int i = 0; + final int length = lines.length; + for (String line in lines) { + i++; + _writeLine( + line, + includeLineBreak: addTrailingLineBreak || i < length, + firstLine: firstLine, + ); + } + _wrappableRanges.clear(); + } + + /// Wraps the given string at the given width. + /// + /// Wrapping occurs at space characters (U+0020). + /// + /// This is not suitable for use with arbitrary Unicode text. For example, it + /// doesn't implement UAX #14, can't handle ideographic text, doesn't hyphenate, + /// and so forth. It is only intended for formatting error messages. + /// + /// This method wraps a sequence of text where only some spans of text can be + /// used as wrap boundaries. + static Iterable _wordWrapLine(String message, List wrapRanges, int width, { int startOffset = 0, int otherLineOffset = 0}) sync* { + if (message.length + startOffset < width) { + // Nothing to do. The line doesn't wrap. + yield message; + return; + } + int startForLengthCalculations = -startOffset; + bool addPrefix = false; + int index = 0; + _WordWrapParseMode mode = _WordWrapParseMode.inSpace; + int lastWordStart; + int lastWordEnd; + int start = 0; + + int currentChunk = 0; + + // This helper is called with increasing indexes. + bool noWrap(int index) { + while (true) { + if (currentChunk >= wrapRanges.length) + return true; + + if (index < wrapRanges[currentChunk + 1]) + break; // Found nearest chunk. + currentChunk+= 2; + } + return index < wrapRanges[currentChunk]; + } + while (true) { + switch (mode) { + case _WordWrapParseMode.inSpace: // at start of break point (or start of line); can't break until next break + while ((index < message.length) && (message[index] == ' ')) + index += 1; + lastWordStart = index; + mode = _WordWrapParseMode.inWord; + break; + case _WordWrapParseMode.inWord: // looking for a good break point. Treat all text + while ((index < message.length) && (message[index] != ' ' || noWrap(index))) + index += 1; + mode = _WordWrapParseMode.atBreak; + break; + case _WordWrapParseMode.atBreak: // at start of break point + if ((index - startForLengthCalculations > width) || (index == message.length)) { + // we are over the width line, so break + if ((index - startForLengthCalculations <= width) || (lastWordEnd == null)) { + // we should use this point, because either it doesn't actually go over the + // end (last line), or it does, but there was no earlier break point + lastWordEnd = index; + } + final String line = message.substring(start, lastWordEnd); + yield line; + addPrefix = true; + if (lastWordEnd >= message.length) + return; + // just yielded a line + if (lastWordEnd == index) { + // we broke at current position + // eat all the wrappable spaces, then set our start point + // Even if some of the spaces are not wrappable that is ok. + while ((index < message.length) && (message[index] == ' ')) + index += 1; + start = index; + mode = _WordWrapParseMode.inWord; + } else { + // we broke at the previous break point, and we're at the start of a new one + assert(lastWordStart > lastWordEnd); + start = lastWordStart; + mode = _WordWrapParseMode.atBreak; + } + startForLengthCalculations = start - otherLineOffset; + assert(addPrefix); + lastWordEnd = null; + } else { + // save this break point, we're not yet over the line width + lastWordEnd = index; + // skip to the end of this break point + mode = _WordWrapParseMode.inSpace; + } + break; + } + } + } /// Write text ensuring the specified prefixes for the first and subsequent /// lines. - void write(String s) { + /// + /// If [allowWrap] is true, the text may be wrapped to stay within the + /// allow `wrapWidth`. + void write(String s, {bool allowWrap = false}) { if (s.isEmpty) return; - if (s == '\n') { - // Edge case to avoid adding trailing whitespace when the caller did - // not explicitly add trailing whitespace. - if (_buffer.isEmpty) { - _buffer.write(prefixLineOne.trimRight()); - } else if (_atLineStart) { - _buffer.write(prefixOtherLines.trimRight()); - _hasMultipleLines = true; + final List lines = s.split('\n'); + for (int i = 0; i < lines.length; i += 1) { + if (i > 0) { + _finalizeLine(true); + _updatePrefix(); + } + final String line = lines[i]; + if (line.isNotEmpty) { + if (allowWrap && wrapWidth != null) { + final int wrapStart = _currentLine.length; + final int wrapEnd = wrapStart + line.length; + if (_wrappableRanges.isNotEmpty && _wrappableRanges.last == wrapStart) { + // Extend last range. + _wrappableRanges.last = wrapEnd; + } else { + _wrappableRanges..add(wrapStart)..add(wrapEnd); + } + } + _currentLine.write(line); } - _buffer.write('\n'); - _atLineStart = true; - return; } - - if (_buffer.isEmpty) { - _buffer.write(prefixLineOne); - } else if (_atLineStart) { - _buffer.write(prefixOtherLines); - _hasMultipleLines = true; + } + void _updatePrefix() { + if (_nextPrefixOtherLines != null) { + _prefixOtherLines = _nextPrefixOtherLines; + _nextPrefixOtherLines = null; } - bool lineTerminated = false; - - if (s.endsWith('\n')) { - s = s.substring(0, s.length - 1); - lineTerminated = true; - } - final List parts = s.split('\n'); - _buffer.write(parts[0]); - for (int i = 1; i < parts.length; ++i) { - _buffer - ..write('\n') - ..write(prefixOtherLines) - ..write(parts[i]); - } - - if (lineTerminated) - _buffer.write('\n'); - - _atLineStart = lineTerminated; } - /// Write text assuming the text already obeys the specified prefixes for the - /// first and subsequent lines. - void writeRaw(String text) { - if (text.isEmpty) - return; - _buffer.write(text); - _atLineStart = text.endsWith('\n'); + void _writeLine( + String line, { + @required bool includeLineBreak, + @required bool firstLine, + }) { + line = '${_getCurrentPrefix(firstLine)}$line'; + _buffer.write(line.trimRight()); + if (includeLineBreak) + _buffer.write('\n'); + _numLines++; } + String _getCurrentPrefix(bool firstLine) { + return _buffer.isEmpty ? prefixLineOne : (firstLine ? _prefixOtherLines : _prefixOtherLines); + } - /// Write a line assuming the line obeys the specified prefixes. Ensures that + /// Write lines assuming the lines obey the specified prefixes. Ensures that /// a newline is added if one is not present. - /// The same as [writeRaw] except a newline is added at the end of [line] if - /// one is not already present. - /// - /// A new line is not added if the input string already contains a newline. - void writeRawLine(String line) { - if (line.isEmpty) + void writeRawLines(String lines) { + if (lines.isEmpty) return; - _buffer.write(line); - if (!line.endsWith('\n')) + + if (_currentLine.isNotEmpty) { + _finalizeLine(true); + } + assert (_currentLine.isEmpty); + + _buffer.write(lines); + if (!lines.endsWith('\n')) _buffer.write('\n'); - _atLineStart = true; + _numLines++; + _updatePrefix(); } - @override - String toString() => _buffer.toString(); + /// Finishes the current line with a stretched version of text. + void writeStretched(String text, int targetLineLength) { + write(text); + final int currentLineLength = _currentLine.length + _getCurrentPrefix(_buffer.isEmpty).length; + assert (_currentLine.length > 0); + final int targetLength = targetLineLength - currentLineLength; + if (targetLength > 0) { + assert(text.isNotEmpty); + final String lastChar = text[text.length - 1]; + assert(lastChar != '\n'); + _currentLine.write(lastChar * targetLength); + } + // Mark the entire line as not wrappable. + _wrappableRanges.clear(); + } + + String build() { + if (_currentLine.isNotEmpty) + _finalizeLine(false); + + return _buffer.toString(); + } } class _NoDefaultValue { @@ -629,6 +1047,334 @@ class _NoDefaultValue { /// Marker object indicating that a [DiagnosticsNode] has no default value. const _NoDefaultValue kNoDefaultValue = _NoDefaultValue(); +bool _isSingleLine(DiagnosticsTreeStyle style) { + return style == DiagnosticsTreeStyle.singleLine; +} + +/// Renderer that creates ascii art representations of trees of +/// [DiagnosticsNode] objects. +/// +/// See also: +/// +/// * [DiagnosticsNode.toStringDeep], which uses a [TextRender] to return a +/// string representation of this node and its descendants. +class TextTreeRenderer { + /// Creates a [TextTreeRenderer] object with the given arguments specifying + /// how the tree is rendered. + /// + /// Lines are wrapped to at the maximum of [wrapWidth] and the current indent + /// plus [wrapWidthProperties] characters. This ensures that wrapping does not + /// become too excessive when displaying very deep trees and that wrapping + /// only occurs at the overall [wrapWidth] when the tree is not very indented. + /// If [maxDescendentsTruncatableNode] is specified, [DiagnosticsNode] objects + /// with `allowTruncate` set to `true` are truncated after including + /// [maxDescendentsTruncatableNode] descendants of the node to be truncated. + TextTreeRenderer({ + DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 100, + int wrapWidthProperties = 65, + int maxDescendentsTruncatableNode = -1, + }) : assert(minLevel != null), + _minLevel = minLevel, + _wrapWidth = wrapWidth, + _wrapWidthProperties = wrapWidthProperties, + _maxDescendentsTruncatableNode = maxDescendentsTruncatableNode; + + final int _wrapWidth; + final int _wrapWidthProperties; + final DiagnosticLevel _minLevel; + final int _maxDescendentsTruncatableNode; + + /// Text configuration to use to connect this node to a `child`. + /// + /// The singleLine styles are special cased because the connection from the + /// parent to the child should be consistent with the parent's style as the + /// single line style does not provide any meaningful style for how children + /// should be connected to their parents. + TextTreeConfiguration _childTextConfiguration( + DiagnosticsNode child, + TextTreeConfiguration textStyle, + ) { + final DiagnosticsTreeStyle childStyle = child?.style; + return (_isSingleLine(childStyle) || childStyle == DiagnosticsTreeStyle.errorProperty) ? textStyle : child.textTreeConfiguration; + } + + /// Renders a [node] to a String. + String render( + DiagnosticsNode node, { + String prefixLineOne = '', + String prefixOtherLines, + TextTreeConfiguration parentConfiguration, + }) { + final bool isSingleLine = _isSingleLine(node.style) && parentConfiguration?.lineBreakProperties != true; + prefixOtherLines ??= prefixLineOne; + if (node.linePrefix != null) { + prefixLineOne += node.linePrefix; + prefixOtherLines += node.linePrefix; + } + + final TextTreeConfiguration config = node.textTreeConfiguration; + if (prefixOtherLines.isEmpty) + prefixOtherLines += config.prefixOtherLinesRootNode; + + if (node.style == DiagnosticsTreeStyle.truncateChildren) { + // This style is different enough that it isn't worthwhile to reuse the + // existing logic. + final List descendants = []; + const int maxDepth = 5; + int depth = 0; + const int maxLines = 25; + int lines = 0; + void visitor(DiagnosticsNode node) { + for (DiagnosticsNode child in node.getChildren()) { + if (lines < maxLines) { + depth += 1; + descendants.add('$prefixOtherLines${" " * depth}$child'); + if (depth < maxDepth) + visitor(child); + depth -= 1; + } else if (lines == maxLines) { + descendants.add('$prefixOtherLines ...(descendants list truncated after $lines lines)'); + } + lines += 1; + } + } + visitor(node); + final StringBuffer information = StringBuffer(prefixLineOne); + if (lines > 1) { + information.writeln('This ${node.name} had the following descendants (showing up to depth $maxDepth):'); + } else if (descendants.length == 1) { + information.writeln('This ${node.name} had the following child:'); + } else { + information.writeln('This ${node.name} has no descendants.'); + } + information.writeAll(descendants, '\n'); + return information.toString(); + } + final _PrefixedStringBuilder builder = _PrefixedStringBuilder( + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + wrapWidth: math.max(_wrapWidth, prefixOtherLines.length + _wrapWidthProperties), + ); + + List children = node.getChildren(); + + String description = node.toDescription(parentConfiguration: parentConfiguration); + if (config.beforeName.isNotEmpty) { + builder.write(config.beforeName); + } + final bool wrapName = !isSingleLine && node.allowNameWrap; + final bool wrapDescription = !isSingleLine && node.allowWrap; + final bool uppercaseTitle = node.style == DiagnosticsTreeStyle.error; + String name = node.name; + if (uppercaseTitle) { + name = name?.toUpperCase(); + } + if (description == null || description.isEmpty) { + if (node.showName && name != null) + builder.write(name, allowWrap: wrapName); + } else { + bool includeName = false; + if (name != null && name.isNotEmpty && node.showName) { + includeName = true; + builder.write(name, allowWrap: wrapName); + if (node.showSeparator) + builder.write(config.afterName, allowWrap: wrapName); + + builder.write( + config.isNameOnOwnLine || description.contains('\n') ? '\n' : ' ', + allowWrap: wrapName, + ); + } + if (!isSingleLine && builder.requiresMultipleLines && !builder.isCurrentLineEmpty) { + // Make sure there is a break between the current line and next one if + // there is not one already. + builder.write('\n'); + } + if (includeName) { + builder.incrementPrefixOtherLines( + children.isEmpty ? config.propertyPrefixNoChildren : config.propertyPrefixIfChildren, + updateCurrentLine: true, + ); + } + + if (uppercaseTitle) { + description = description.toUpperCase(); + } + builder.write(description.trimRight(), allowWrap: wrapDescription); + + if (!includeName) { + builder.incrementPrefixOtherLines( + children.isEmpty ? config.propertyPrefixNoChildren : config.propertyPrefixIfChildren, + updateCurrentLine: false, + ); + } + } + if (config.suffixLineOne.isNotEmpty) { + builder.writeStretched(config.suffixLineOne, builder.wrapWidth); + } + + final Iterable propertiesIterable = node.getProperties().where( + (DiagnosticsNode n) => !n.isFiltered(_minLevel) + ); + List properties; + if (_maxDescendentsTruncatableNode >= 0 && node.allowTruncate) { + if (propertiesIterable.length < _maxDescendentsTruncatableNode) { + properties = + propertiesIterable.take(_maxDescendentsTruncatableNode).toList(); + properties.add(DiagnosticsNode.message('...')); + } else { + properties = propertiesIterable.toList(); + } + if (_maxDescendentsTruncatableNode < children.length) { + children = children.take(_maxDescendentsTruncatableNode).toList(); + children.add(DiagnosticsNode.message('...')); + } + } else { + properties = propertiesIterable.toList(); + } + + // If the node does not show a separator and there is no description then + // we should not place a separator between the name and the value. + // Essentially in this case the properties are treated a bit like a value. + if ((properties.isNotEmpty || children.isNotEmpty || node.emptyBodyDescription != null) && + (node.showSeparator || description?.isNotEmpty == true)) { + builder.write(config.afterDescriptionIfBody); + } + + if (config.lineBreakProperties) + builder.write(config.lineBreak); + + if (properties.isNotEmpty) + builder.write(config.beforeProperties); + + builder.incrementPrefixOtherLines(config.bodyIndent, updateCurrentLine: false); + + if (node.emptyBodyDescription != null && + properties.isEmpty && + children.isEmpty && + prefixLineOne.isNotEmpty) { + builder.write(node.emptyBodyDescription); + if (config.lineBreakProperties) + builder.write(config.lineBreak); + } + + for (int i = 0; i < properties.length; ++i) { + final DiagnosticsNode property = properties[i]; + if (i > 0) + builder.write(config.propertySeparator); + + final TextTreeConfiguration propertyStyle = property.textTreeConfiguration; + if (_isSingleLine(property.style)) { + // We have to treat single line properties slightly differently to deal + // with cases where a single line properties output may not have single + // linebreak. + final String propertyRender = render(property, + prefixLineOne: '${propertyStyle.prefixLineOne}', + prefixOtherLines: '${propertyStyle.childLinkSpace}${propertyStyle.prefixOtherLines}', + parentConfiguration: config, + ); + final List propertyLines = propertyRender.split('\n'); + if (propertyLines.length == 1 && !config.lineBreakProperties) { + builder.write(propertyLines.first); + } else { + builder.write(propertyRender, allowWrap: false); + if (!propertyRender.endsWith('\n')) + builder.write('\n'); + } + } else + { + final String propertyRender = render(property, + prefixLineOne: '${builder.prefixOtherLines}${propertyStyle.prefixLineOne}', + prefixOtherLines: '${builder.prefixOtherLines}${propertyStyle.childLinkSpace}${propertyStyle.prefixOtherLines}', + parentConfiguration: config, + ); + builder.writeRawLines(propertyRender); + } + } + if (properties.isNotEmpty) + builder.write(config.afterProperties); + + builder.write(config.mandatoryAfterProperties); + + if (!config.lineBreakProperties) + builder.write(config.lineBreak); + + final String prefixChildren = '${config.bodyIndent}'; + final String prefixChildrenRaw = '$prefixOtherLines$prefixChildren'; + if (children.isEmpty && + config.addBlankLineIfNoChildren && + builder.requiresMultipleLines && + builder.prefixOtherLines.trimRight().isNotEmpty + ) { + builder.write(config.lineBreak); + } + + if (children.isNotEmpty && config.showChildren) { + if (config.isBlankLineBetweenPropertiesAndChildren && + properties.isNotEmpty && + children.first.textTreeConfiguration.isBlankLineBetweenPropertiesAndChildren) { + builder.write(config.lineBreak); + } + + builder.prefixOtherLines = prefixOtherLines; + + for (int i = 0; i < children.length; i++) { + final DiagnosticsNode child = children[i]; + assert(child != null); + final TextTreeConfiguration childConfig = _childTextConfiguration(child, config); + if (i == children.length - 1) { + final String lastChildPrefixLineOne = '$prefixChildrenRaw${childConfig.prefixLastChildLineOne}'; + final String childPrefixOtherLines = '$prefixChildrenRaw${childConfig.childLinkSpace}${childConfig.prefixOtherLines}'; + builder.writeRawLines(render( + child, + prefixLineOne: lastChildPrefixLineOne, + prefixOtherLines: childPrefixOtherLines, + parentConfiguration: config, + )); + if (childConfig.footer.isNotEmpty) { + builder.prefixOtherLines = prefixChildrenRaw; + builder.write('${childConfig.childLinkSpace}${childConfig.footer}'); + if (childConfig.manditoryFooter.isNotEmpty) { + builder.writeStretched( + childConfig.manditoryFooter, + math.max(builder.wrapWidth, _wrapWidthProperties + childPrefixOtherLines.length), + ); + } + builder.write(config.lineBreak); + } + } else { + final TextTreeConfiguration nextChildStyle = _childTextConfiguration(children[i + 1], config); + final String childPrefixLineOne = '$prefixChildrenRaw${childConfig.prefixLineOne}'; + final String childPrefixOtherLines ='$prefixChildrenRaw${nextChildStyle.linkCharacter}${childConfig.prefixOtherLines}'; + builder.writeRawLines(render( + child, + prefixLineOne: childPrefixLineOne, + prefixOtherLines: childPrefixOtherLines, + parentConfiguration: config, + )); + if (childConfig.footer.isNotEmpty) { + builder.prefixOtherLines = prefixChildrenRaw; + builder.write('${childConfig.linkCharacter}${childConfig.footer}'); + if (childConfig.manditoryFooter.isNotEmpty) { + builder.writeStretched( + childConfig.manditoryFooter, + math.max(builder.wrapWidth, _wrapWidthProperties + childPrefixOtherLines.length), + ); + } + builder.write(config.lineBreak); + } + } + } + } + if (parentConfiguration == null && config.manditoryFooter.isNotEmpty) { + builder.writeStretched(config.manditoryFooter, builder.wrapWidth); + builder.write(config.lineBreak); + } + return builder.build(); + } +} + /// Defines diagnostics data for a [value]. /// /// [DiagnosticsNode] provides a high quality multi-line string dump via @@ -646,12 +1392,18 @@ abstract class DiagnosticsNode { this.style, this.showName = true, this.showSeparator = true, + this.linePrefix, }) : assert(showName != null), assert(showSeparator != null), // A name ending with ':' indicates that the user forgot that the ':' will // be automatically added for them when generating descriptions of the // property. - assert(name == null || !name.endsWith(':'), 'Names of diagnostic nodes must not end with colons.'); + assert( + name == null || !name.endsWith(':'), + 'Names of diagnostic nodes must not end with colons.\n' + 'name:\n' + ' "$name"' + ); /// Diagnostics containing just a string `message` and not a concrete name or /// value. @@ -666,6 +1418,7 @@ abstract class DiagnosticsNode { String message, { DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, + bool allowWrap = true, }) { assert(style != null); assert(level != null); @@ -675,6 +1428,7 @@ abstract class DiagnosticsNode { description: message, style: style, showName: false, + allowWrap: allowWrap, level: level, ); } @@ -724,6 +1478,9 @@ abstract class DiagnosticsNode { /// will make the name self-evident. final bool showName; + /// Prefix to include at the start of each line + final String linePrefix; + /// Description to show if the node has no displayed properties or children. String get emptyBodyDescription => null; @@ -733,6 +1490,15 @@ abstract class DiagnosticsNode { /// Hint for how the node should be displayed. final DiagnosticsTreeStyle style; + /// Whether to wrap text on onto multiple lines or not. + bool get allowWrap => false; + + /// Whether to wrap the name onto multiple lines or not. + bool get allowNameWrap => false; + + /// Whether to allow truncation when displaying the node and its children. + bool get allowTruncate => false; + /// Properties of this [DiagnosticsNode]. /// /// Properties and children are kept distinct even though they are both @@ -761,17 +1527,39 @@ abstract class DiagnosticsNode { @mustCallSuper Map toJsonMap() { final Map data = { - 'name': name, - 'showSeparator': showSeparator, 'description': toDescription(), - 'level': describeEnum(level), - 'showName': showName, - 'emptyBodyDescription': emptyBodyDescription, - 'style': describeEnum(style), - 'valueToString': value.toString(), 'type': runtimeType.toString(), - 'hasChildren': getChildren().isNotEmpty, }; + if (name != null) + data['name'] = name; + + if (!showSeparator) + data['showSeparator'] = showSeparator; + if (level != DiagnosticLevel.info) + data['level'] = describeEnum(level); + if (showName == false) + data['showName'] = showName; + if (emptyBodyDescription != null) + data['emptyBodyDescription'] = emptyBodyDescription; + if (style != DiagnosticsTreeStyle.sparse) + data['style'] = describeEnum(style); + + if (allowTruncate) + data['allowTruncate'] = allowTruncate; + + final bool hasChildren = getChildren().isNotEmpty; + if (hasChildren) + data['hasChildren'] = hasChildren; + + if (linePrefix?.isNotEmpty == true) + data['linePrefix'] = linePrefix; + + if (!allowWrap) + data['allowWrap'] = allowWrap; + + if (allowNameWrap) + data['allowNameWrap'] = allowNameWrap; + return data; } @@ -791,7 +1579,7 @@ abstract class DiagnosticsNode { }) { assert(style != null); assert(minLevel != null); - if (style == DiagnosticsTreeStyle.singleLine) + if (_isSingleLine(style)) return toStringDeep(parentConfiguration: parentConfiguration, minLevel: minLevel); final String description = toDescription(parentConfiguration: parentConfiguration); @@ -821,24 +1609,22 @@ abstract class DiagnosticsNode { return transitionTextConfiguration; case DiagnosticsTreeStyle.singleLine: return singleLineTextConfiguration; + case DiagnosticsTreeStyle.errorProperty: + return errorPropertyTextConfiguration; + case DiagnosticsTreeStyle.shallow: + return shallowTextConfiguration; + case DiagnosticsTreeStyle.error: + return errorTextConfiguration; + case DiagnosticsTreeStyle.truncateChildren: + // Truncate children doesn't really need its own text style as the + // rendering is quite custom. + return whitespaceTextConfiguration; + case DiagnosticsTreeStyle.flat: + return flatTextConfiguration; } return null; } - /// Text configuration to use to connect this node to a `child`. - /// - /// The singleLine style is special cased because the connection from the - /// parent to the child should be consistent with the parent's style as the - /// single line style does not provide any meaningful style for how children - /// should be connected to their parents. - TextTreeConfiguration _childTextConfiguration( - DiagnosticsNode child, - TextTreeConfiguration textStyle, - ) { - return (child != null && child.style != DiagnosticsTreeStyle.singleLine) ? - child.textTreeConfiguration : textStyle; - } - /// Returns a string representation of this node and its descendants. /// /// `prefixLineOne` will be added to the front of the first line of the @@ -862,150 +1648,16 @@ abstract class DiagnosticsNode { TextTreeConfiguration parentConfiguration, DiagnosticLevel minLevel = DiagnosticLevel.debug, }) { - assert(minLevel != null); - prefixOtherLines ??= prefixLineOne; - - final List children = getChildren(); - final TextTreeConfiguration config = textTreeConfiguration; - if (prefixOtherLines.isEmpty) - prefixOtherLines += config.prefixOtherLinesRootNode; - - final _PrefixedStringBuilder builder = _PrefixedStringBuilder( - prefixLineOne, - prefixOtherLines, + return TextTreeRenderer( + minLevel: minLevel, + wrapWidth: 65, + wrapWidthProperties: 65, + ).render( + this, + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + parentConfiguration: parentConfiguration, ); - - final String description = toDescription(parentConfiguration: parentConfiguration); - if (description == null || description.isEmpty) { - if (showName && name != null) - builder.write(name); - } else { - if (name != null && name.isNotEmpty && showName) { - builder.write(name); - if (showSeparator) - builder.write(config.afterName); - - builder.write( - config.isNameOnOwnLine || description.contains('\n') ? '\n' : ' '); - if (description.contains('\n') && style == DiagnosticsTreeStyle.singleLine) - builder.prefixOtherLines += ' '; - } - builder.prefixOtherLines += children.isEmpty ? - config.propertyPrefixNoChildren : config.propertyPrefixIfChildren; - builder.write(description); - } - - final List properties = getProperties().where( - (DiagnosticsNode n) => !n.isFiltered(minLevel) - ).toList(); - - if (properties.isNotEmpty || children.isNotEmpty || emptyBodyDescription != null) - builder.write(config.afterDescriptionIfBody); - - if (config.lineBreakProperties) - builder.write(config.lineBreak); - - if (properties.isNotEmpty) - builder.write(config.beforeProperties); - - builder.prefixOtherLines += config.bodyIndent; - - if (emptyBodyDescription != null && - properties.isEmpty && - children.isEmpty && - prefixLineOne.isNotEmpty) { - builder.write(emptyBodyDescription); - if (config.lineBreakProperties) - builder.write(config.lineBreak); - } - - for (int i = 0; i < properties.length; ++i) { - final DiagnosticsNode property = properties[i]; - if (i > 0) - builder.write(config.propertySeparator); - - const int kWrapWidth = 65; - if (property.style != DiagnosticsTreeStyle.singleLine) { - final TextTreeConfiguration propertyStyle = property.textTreeConfiguration; - builder.writeRaw(property.toStringDeep( - prefixLineOne: '${builder.prefixOtherLines}${propertyStyle.prefixLineOne}', - prefixOtherLines: '${builder.prefixOtherLines}${propertyStyle.linkCharacter}${propertyStyle.prefixOtherLines}', - parentConfiguration: config, - minLevel: minLevel, - )); - continue; - } - assert(property.style == DiagnosticsTreeStyle.singleLine); - final String message = property.toString(parentConfiguration: config, minLevel: minLevel); - if (!config.lineBreakProperties || message.length < kWrapWidth) { - builder.write(message); - } else { - // debugWordWrap doesn't handle line breaks within the text being - // wrapped so we must call it on each line. - final List lines = message.split('\n'); - for (int j = 0; j < lines.length; ++j) { - final String line = lines[j]; - if (j > 0) - builder.write(config.lineBreak); - builder.write(debugWordWrap(line, kWrapWidth, wrapIndent: ' ').join('\n')); - } - } - if (config.lineBreakProperties) - builder.write(config.lineBreak); - } - if (properties.isNotEmpty) - builder.write(config.afterProperties); - - if (!config.lineBreakProperties) - builder.write(config.lineBreak); - - final String prefixChildren = '$prefixOtherLines${config.bodyIndent}'; - - if (children.isEmpty && - config.addBlankLineIfNoChildren && - builder.hasMultipleLines) { - final String prefix = prefixChildren.trimRight(); - if (prefix.isNotEmpty) - builder.writeRaw('$prefix${config.lineBreak}'); - } - - if (children.isNotEmpty && config.showChildren) { - if (config.isBlankLineBetweenPropertiesAndChildren && - properties.isNotEmpty && - children.first.textTreeConfiguration.isBlankLineBetweenPropertiesAndChildren) { - builder.write(config.lineBreak); - } - - for (int i = 0; i < children.length; i++) { - final DiagnosticsNode child = children[i]; - assert(child != null); - final TextTreeConfiguration childConfig = _childTextConfiguration(child, config); - if (i == children.length - 1) { - final String lastChildPrefixLineOne = '$prefixChildren${childConfig.prefixLastChildLineOne}'; - builder.writeRawLine(child.toStringDeep( - prefixLineOne: lastChildPrefixLineOne, - prefixOtherLines: '$prefixChildren${childConfig.childLinkSpace}${childConfig.prefixOtherLines}', - parentConfiguration: config, - minLevel: minLevel, - )); - if (childConfig.footer.isNotEmpty) - builder.writeRaw('$prefixChildren${childConfig.childLinkSpace}${childConfig.footer}'); - } else { - final TextTreeConfiguration nextChildStyle = _childTextConfiguration(children[i + 1], config); - final String childPrefixLineOne = '$prefixChildren${childConfig.prefixLineOne}'; - final String childPrefixOtherLines ='$prefixChildren${nextChildStyle.linkCharacter}${childConfig.prefixOtherLines}'; - builder.writeRawLine(child.toStringDeep( - prefixLineOne: childPrefixLineOne, - prefixOtherLines: childPrefixOtherLines, - parentConfiguration: config, - minLevel: minLevel, - )); - if (childConfig.footer.isNotEmpty) - builder.writeRaw('$prefixChildren${nextChildStyle.linkCharacter}${childConfig.footer}'); - } - } - } - return builder.toString(); } } @@ -1048,11 +1700,13 @@ class MessageProperty extends DiagnosticsProperty { MessageProperty( String name, String message, { + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(name != null), assert(message != null), + assert(style != null), assert(level != null), - super(name, null, description: message, level: level); + super(name, null, description: message, style: style, level: level); } /// Property which encloses its string [value] in quotes. @@ -1064,7 +1718,7 @@ class MessageProperty extends DiagnosticsProperty { class StringProperty extends DiagnosticsProperty { /// Create a diagnostics property for strings. /// - /// The [showName], [quoted], and [level] arguments must not be null. + /// The [showName], [quoted], [style], and [level] arguments must not be null. StringProperty( String name, String value, { @@ -1074,9 +1728,11 @@ class StringProperty extends DiagnosticsProperty { Object defaultValue = kNoDefaultValue, this.quoted = true, String ifEmpty, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(showName != null), assert(quoted != null), + assert(style != null), assert(level != null), super( name, @@ -1086,6 +1742,7 @@ class StringProperty extends DiagnosticsProperty { tooltip: tooltip, showName: showName, ifEmpty: ifEmpty, + style: style, level: level, ); @@ -1131,6 +1788,7 @@ abstract class _NumProperty extends DiagnosticsProperty { bool showName = true, Object defaultValue = kNoDefaultValue, String tooltip, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : super( name, @@ -1140,6 +1798,7 @@ abstract class _NumProperty extends DiagnosticsProperty { defaultValue: defaultValue, tooltip: tooltip, level: level, + style: style, ); _NumProperty.lazy( @@ -1150,6 +1809,7 @@ abstract class _NumProperty extends DiagnosticsProperty { bool showName = true, Object defaultValue = kNoDefaultValue, String tooltip, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : super.lazy( name, @@ -1158,6 +1818,7 @@ abstract class _NumProperty extends DiagnosticsProperty { showName: showName, defaultValue: defaultValue, tooltip: tooltip, + style: style, level: level, ); @@ -1195,7 +1856,7 @@ abstract class _NumProperty extends DiagnosticsProperty { class DoubleProperty extends _NumProperty { /// If specified, [unit] describes the unit for the [value] (e.g. px). /// - /// The [showName] and [level] arguments must not be null. + /// The [showName], [style], and [level] arguments must not be null. DoubleProperty( String name, double value, { @@ -1204,8 +1865,10 @@ class DoubleProperty extends _NumProperty { String tooltip, Object defaultValue = kNoDefaultValue, bool showName = true, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(showName != null), + assert(style != null), assert(level != null), super( name, @@ -1215,6 +1878,7 @@ class DoubleProperty extends _NumProperty { tooltip: tooltip, defaultValue: defaultValue, showName: showName, + style :style, level: level, ); @@ -1256,7 +1920,7 @@ class DoubleProperty extends _NumProperty { class IntProperty extends _NumProperty { /// Create a diagnostics property for integers. /// - /// The [showName] and [level] arguments must not be null. + /// The [showName], [style], and [level] arguments must not be null. IntProperty( String name, int value, { @@ -1264,9 +1928,11 @@ class IntProperty extends _NumProperty { bool showName = true, String unit, Object defaultValue = kNoDefaultValue, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(showName != null), assert(level != null), + assert(style != null), super( name, value, @@ -1468,7 +2134,7 @@ class IterableProperty extends DiagnosticsProperty> { /// [defaultValue] is used to indicate that a specific concrete value is not /// interesting to display. /// - /// The [style], [showName], and [level] arguments must not be null. + /// The [style], [showName], [showSeparator], and [level] arguments must not be null. IterableProperty( String name, Iterable value, { @@ -1477,9 +2143,11 @@ class IterableProperty extends DiagnosticsProperty> { String ifEmpty = '[]', DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, bool showName = true, + bool showSeparator = true, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(style != null), assert(showName != null), + assert(showSeparator != null), assert(level != null), super( name, @@ -1489,6 +2157,7 @@ class IterableProperty extends DiagnosticsProperty> { ifEmpty: ifEmpty, style: style, showName: showName, + showSeparator: showSeparator, level: level, ); @@ -1506,7 +2175,7 @@ class IterableProperty extends DiagnosticsProperty> { return '[${value.join(', ')}]'; } - return value.join(style == DiagnosticsTreeStyle.singleLine ? ', ' : '\n'); + return value.join(_isSingleLine(style) ? ', ' : '\n'); } /// Priority level of the diagnostic used to control which diagnostics should @@ -1718,6 +2387,10 @@ class DiagnosticsProperty extends DiagnosticsNode { this.defaultValue = kNoDefaultValue, this.tooltip, this.missingIfNull = false, + String linePrefix, + this.expandableValue = false, + this.allowWrap = true, + this.allowNameWrap = true, DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(showName != null), @@ -1735,6 +2408,7 @@ class DiagnosticsProperty extends DiagnosticsNode { showName: showName, showSeparator: showSeparator, style: style, + linePrefix: linePrefix, ); /// Property with a [value] that is computed only when needed. @@ -1760,6 +2434,9 @@ class DiagnosticsProperty extends DiagnosticsNode { this.defaultValue = kNoDefaultValue, this.tooltip, this.missingIfNull = false, + this.expandableValue = false, + this.allowWrap = true, + this.allowNameWrap = true, DiagnosticsTreeStyle style = DiagnosticsTreeStyle.singleLine, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(showName != null), @@ -1783,6 +2460,16 @@ class DiagnosticsProperty extends DiagnosticsNode { final String _description; + /// Whether to expose properties and children of the value as properties and + /// children. + final bool expandableValue; + + @override + final bool allowWrap; + + @override + final bool allowNameWrap; + @override Map toJsonMap() { final Map json = super.toJsonMap(); @@ -1798,9 +2485,8 @@ class DiagnosticsProperty extends DiagnosticsNode { if (exception != null) json['exception'] = exception.toString(); json['propertyType'] = propertyType.toString(); - json['valueToString'] = valueToString(); json['defaultLevel'] = describeEnum(_defaultLevel); - if (T is Diagnosticable) + if (T is Diagnosticable || T is DiagnosticsNode) json['isDiagnosticableValue'] = true; return json; } @@ -1823,7 +2509,7 @@ class DiagnosticsProperty extends DiagnosticsNode { // DiagnosticableTree values are shown using the shorter toStringShort() // instead of the longer toString() because the toString() for a // DiagnosticableTree value is likely too large to be useful. - return v is DiagnosticableTree ? v.toStringShort() : v.toString(); + return (v is DiagnosticableTree ? v.toStringShort() : v.toString()) ?? ''; } @override @@ -1968,10 +2654,32 @@ class DiagnosticsProperty extends DiagnosticsNode { final ComputePropertyValueCallback _computeValue; @override - List getProperties() => []; + List getProperties() { + if (expandableValue) { + final T object = value; + if (object is DiagnosticsNode) { + return object.getProperties(); + } + if (object is Diagnosticable) { + return object.toDiagnosticsNode(style: style).getProperties(); + } + } + return const []; + } @override - List getChildren() => []; + List getChildren() { + if (expandableValue) { + final T object = value; + if (object is DiagnosticsNode) { + return object.getChildren(); + } + if (object is Diagnosticable) { + return object.toDiagnosticsNode(style: style).getChildren(); + } + } + return const []; + } } /// [DiagnosticsNode] that lazily calls the associated [Diagnosticable] [value] @@ -2541,3 +3249,56 @@ mixin DiagnosticableTreeMixin implements DiagnosticableTree { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { } } + + +/// [DiagnosticsNode] that exists mainly to provide a container for other +/// diagnostics that typically lacks a meaningful value of its own. +/// +/// This class is typically used for displaying complex nested error messages. +class DiagnosticsBlock extends DiagnosticsNode { + /// Creates a diagnostic with properties specified by [properties] and + /// children specified by [children]. + DiagnosticsBlock({ + String name, + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.whitespace, + bool showName = true, + bool showSeparator = true, + String linePrefix, + this.value, + String description, + this.level = DiagnosticLevel.info, + this.allowTruncate = false, + List children = const[], + List properties = const [], + }) : _description = description, + _children = children, + _properties = properties, + super( + name: name, + style: style, + showName: showName && name != null, + showSeparator: showSeparator, + linePrefix: linePrefix, + ); + + final List _children; + final List _properties; + + @override + final DiagnosticLevel level; + final String _description; + @override + final Object value; + + @override + final bool allowTruncate; + + @override + List getChildren() => _children; + + @override + List getProperties() => _properties; + + @override + String toDescription({TextTreeConfiguration parentConfiguration}) => _description; +} diff --git a/packages/flutter/lib/src/gestures/binding.dart b/packages/flutter/lib/src/gestures/binding.dart index 8c7bdf8f7a..45faed882b 100644 --- a/packages/flutter/lib/src/gestures/binding.dart +++ b/packages/flutter/lib/src/gestures/binding.dart @@ -183,12 +183,11 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H exception: exception, stack: stack, library: 'gesture library', - context: 'while dispatching a non-hit-tested pointer event', + context: ErrorDescription('while dispatching a non-hit-tested pointer event'), event: event, hitTestEntry: null, - informationCollector: (StringBuffer information) { - information.writeln('Event:'); - information.writeln(' $event'); + informationCollector: () sync* { + yield DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty); }, )); } @@ -202,14 +201,12 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H exception: exception, stack: stack, library: 'gesture library', - context: 'while dispatching a pointer event', + context: ErrorDescription('while dispatching a pointer event'), event: event, hitTestEntry: entry, - informationCollector: (StringBuffer information) { - information.writeln('Event:'); - information.writeln(' $event'); - information.writeln('Target:'); - information.write(' ${entry.target}'); + informationCollector: () sync* { + yield DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty); + yield DiagnosticsProperty('Target', entry.target, style: DiagnosticsTreeStyle.errorProperty); }, )); } @@ -244,7 +241,7 @@ class FlutterErrorDetailsForPointerEventDispatcher extends FlutterErrorDetails { dynamic exception, StackTrace stack, String library, - String context, + DiagnosticsNode context, this.event, this.hitTestEntry, InformationCollector informationCollector, diff --git a/packages/flutter/lib/src/gestures/pointer_router.dart b/packages/flutter/lib/src/gestures/pointer_router.dart index 5240dac2d8..2d2352e8e0 100644 --- a/packages/flutter/lib/src/gestures/pointer_router.dart +++ b/packages/flutter/lib/src/gestures/pointer_router.dart @@ -76,13 +76,12 @@ class PointerRouter { exception: exception, stack: stack, library: 'gesture library', - context: 'while routing a pointer event', + context: ErrorDescription('while routing a pointer event'), router: this, route: route, event: event, - informationCollector: (StringBuffer information) { - information.writeln('Event:'); - information.write(' $event'); + informationCollector: () sync* { + yield DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty); }, )); } @@ -123,7 +122,7 @@ class FlutterErrorDetailsForPointerRouter extends FlutterErrorDetails { dynamic exception, StackTrace stack, String library, - String context, + DiagnosticsNode context, this.router, this.route, this.event, diff --git a/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart b/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart index 75fa51e0c1..e1e9f50ff8 100644 --- a/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart +++ b/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart @@ -55,10 +55,9 @@ class PointerSignalResolver { exception: exception, stack: stack, library: 'gesture library', - context: 'while resolving a PointerSignalEvent', - informationCollector: (StringBuffer information) { - information.writeln('Event:'); - information.write(' $event'); + context: ErrorDescription('while resolving a PointerSignalEvent'), + informationCollector: () sync* { + yield DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty); }, )); } diff --git a/packages/flutter/lib/src/gestures/recognizer.dart b/packages/flutter/lib/src/gestures/recognizer.dart index b95fc255a7..a6d277fcee 100644 --- a/packages/flutter/lib/src/gestures/recognizer.dart +++ b/packages/flutter/lib/src/gestures/recognizer.dart @@ -169,12 +169,11 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT exception: exception, stack: stack, library: 'gesture', - context: 'while handling a gesture', - informationCollector: (StringBuffer information) { - information.writeln('Handler: $name'); - information.writeln('Recognizer:'); - information.writeln(' $this'); - }, + context: ErrorDescription('while handling a gesture'), + informationCollector: () sync* { + yield StringProperty('Handler', name); + yield DiagnosticsProperty('Recognizer', this, style: DiagnosticsTreeStyle.errorProperty); + } )); } return result; diff --git a/packages/flutter/lib/src/material/refresh_indicator.dart b/packages/flutter/lib/src/material/refresh_indicator.dart index a03b736137..f3934a4400 100644 --- a/packages/flutter/lib/src/material/refresh_indicator.dart +++ b/packages/flutter/lib/src/material/refresh_indicator.dart @@ -362,7 +362,7 @@ class RefreshIndicatorState extends State with TickerProviderS 'The onRefresh callback returned null.\n' 'The RefreshIndicator onRefresh callback must return a Future.' ), - context: 'when calling onRefresh', + context: ErrorDescription('when calling onRefresh'), library: 'material library', )); return true; diff --git a/packages/flutter/lib/src/painting/image_provider.dart b/packages/flutter/lib/src/painting/image_provider.dart index b414d6ccb8..e552aca7a9 100644 --- a/packages/flutter/lib/src/painting/image_provider.dart +++ b/packages/flutter/lib/src/painting/image_provider.dart @@ -274,14 +274,12 @@ abstract class ImageProvider { imageCompleter.setError( exception: exception, stack: stack, - context: 'while resolving an image', + context: ErrorDescription('while resolving an image'), silent: true, // could be a network error or whatnot - informationCollector: (StringBuffer information) { - information.writeln('Image provider: $this'); - information.writeln('Image configuration: $configuration'); - if (obtainedKey != null) { - information.writeln('Image key: $obtainedKey'); - } + informationCollector: () sync* { + yield DiagnosticsProperty('Image provider', this); + yield DiagnosticsProperty('Image configuration', configuration); + yield DiagnosticsProperty('Image key', obtainedKey, defaultValue: null); }, ); } @@ -448,9 +446,9 @@ abstract class AssetBundleImageProvider extends ImageProvider('Image provider', this); + yield DiagnosticsProperty('Image key', key); }, ); } @@ -505,9 +503,9 @@ class NetworkImage extends ImageProvider { return MultiFrameImageStreamCompleter( codec: _loadAsync(key), scale: key.scale, - informationCollector: (StringBuffer information) { - information.writeln('Image provider: $this'); - information.write('Image key: $key'); + informationCollector: () sync* { + yield DiagnosticsProperty('Image provider', this); + yield DiagnosticsProperty('Image key', key); }, ); } @@ -579,8 +577,8 @@ class FileImage extends ImageProvider { return MultiFrameImageStreamCompleter( codec: _loadAsync(key), scale: key.scale, - informationCollector: (StringBuffer information) { - information.writeln('Path: ${file?.path}'); + informationCollector: () sync* { + yield ErrorDescription('Path: ${file?.path}'); }, ); } @@ -815,7 +813,7 @@ class _ErrorImageCompleter extends ImageStreamCompleter { _ErrorImageCompleter(); void setError({ - String context, + DiagnosticsNode context, dynamic exception, StackTrace stack, InformationCollector informationCollector, diff --git a/packages/flutter/lib/src/painting/image_stream.dart b/packages/flutter/lib/src/painting/image_stream.dart index c560f874f2..eeb2d0ea72 100644 --- a/packages/flutter/lib/src/painting/image_stream.dart +++ b/packages/flutter/lib/src/painting/image_stream.dart @@ -284,7 +284,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { listener(_currentImage, true); } catch (exception, stack) { reportError( - context: 'by a synchronously-called image listener', + context: ErrorDescription('by a synchronously-called image listener'), exception: exception, stack: stack, ); @@ -298,7 +298,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { FlutterErrorDetails( exception: exception, library: 'image resource service', - context: 'by a synchronously-called image error listener', + context: ErrorDescription('by a synchronously-called image error listener'), stack: stack, ), ); @@ -336,7 +336,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { listener(image, false); } catch (exception, stack) { reportError( - context: 'by an image listener', + context: ErrorDescription('by an image listener'), exception: exception, stack: stack, ); @@ -374,7 +374,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { /// See [FlutterErrorDetails] for further details on these values. @protected void reportError({ - String context, + DiagnosticsNode context, dynamic exception, StackTrace stack, InformationCollector informationCollector, @@ -405,7 +405,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { } catch (exception, stack) { FlutterError.reportError( FlutterErrorDetails( - context: 'when reporting an error to an image listener', + context: ErrorDescription('when reporting an error to an image listener'), library: 'image resource service', exception: exception, stack: stack, @@ -451,7 +451,7 @@ class OneFrameImageStreamCompleter extends ImageStreamCompleter { : assert(image != null) { image.then(setImage, onError: (dynamic error, StackTrace stack) { reportError( - context: 'resolving a single-frame image stream', + context: ErrorDescription('resolving a single-frame image stream'), exception: error, stack: stack, informationCollector: informationCollector, @@ -511,7 +511,7 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { _scale = scale { codec.then(_handleCodecReady, onError: (dynamic error, StackTrace stack) { reportError( - context: 'resolving an image codec', + context: ErrorDescription('resolving an image codec'), exception: error, stack: stack, informationCollector: informationCollector, @@ -579,7 +579,7 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { _nextFrame = await _codec.getNextFrame(); } catch (exception, stack) { reportError( - context: 'resolving an image frame', + context: ErrorDescription('resolving an image frame'), exception: exception, stack: stack, informationCollector: _informationCollector, diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index a23a2347ae..168417a57c 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -497,11 +497,14 @@ class BoxConstraints extends Constraints { InformationCollector informationCollector, }) { assert(() { - void throwError(String message) { - final StringBuffer information = StringBuffer(); - if (informationCollector != null) - informationCollector(information); - throw FlutterError('$message\n${information}The offending constraints were:\n $this'); + void throwError(DiagnosticsNode message) { + final List information = [message]; + if (informationCollector != null) { + information.addAll(informationCollector()); + } + + information.add(DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty)); + throw FlutterError.fromParts(information); } if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { final List affectedFieldsList = []; @@ -524,27 +527,27 @@ class BoxConstraints extends Constraints { } else { whichFields = affectedFieldsList.single; } - throwError('BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values' } in $whichFields.'); + throwError(ErrorSummary('BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values' } in $whichFields.')); } if (minWidth < 0.0 && minHeight < 0.0) - throwError('BoxConstraints has both a negative minimum width and a negative minimum height.'); + throwError(ErrorSummary('BoxConstraints has both a negative minimum width and a negative minimum height.')); if (minWidth < 0.0) - throwError('BoxConstraints has a negative minimum width.'); + throwError(ErrorSummary('BoxConstraints has a negative minimum width.')); if (minHeight < 0.0) - throwError('BoxConstraints has a negative minimum height.'); + throwError(ErrorSummary('BoxConstraints has a negative minimum height.')); if (maxWidth < minWidth && maxHeight < minHeight) - throwError('BoxConstraints has both width and height constraints non-normalized.'); + throwError(ErrorSummary('BoxConstraints has both width and height constraints non-normalized.')); if (maxWidth < minWidth) - throwError('BoxConstraints has non-normalized width constraints.'); + throwError(ErrorSummary('BoxConstraints has non-normalized width constraints.')); if (maxHeight < minHeight) - throwError('BoxConstraints has non-normalized height constraints.'); + throwError(ErrorSummary('BoxConstraints has non-normalized height constraints.')); if (isAppliedConstraint) { if (minWidth.isInfinite && minHeight.isInfinite) - throwError('BoxConstraints forces an infinite width and infinite height.'); + throwError(ErrorSummary('BoxConstraints forces an infinite width and infinite height.')); if (minWidth.isInfinite) - throwError('BoxConstraints forces an infinite width.'); + throwError(ErrorSummary('BoxConstraints forces an infinite width.')); if (minHeight.isInfinite) - throwError('BoxConstraints forces an infinite height.'); + throwError(ErrorSummary('BoxConstraints forces an infinite height.')); } assert(isNormalized); return true; @@ -1512,28 +1515,23 @@ abstract class RenderBox extends RenderObject { (!sizedByParent && debugDoingThisLayout)) return true; assert(!debugDoingThisResize); - String contract, violation, hint; + final List information = []; + information.add(ErrorSummary('RenderBox size setter called incorrectly.')); if (debugDoingThisLayout) { assert(sizedByParent); - violation = 'It appears that the size setter was called from performLayout().'; - hint = ''; + information.add(ErrorDescription('It appears that the size setter was called from performLayout().')); } else { - violation = 'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).'; + information.add(ErrorDescription( + 'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).' + )); if (owner != null && owner.debugDoingLayout) - hint = 'Only the object itself can set its size. It is a contract violation for other objects to set it.'; + information.add(ErrorDescription('Only the object itself can set its size. It is a contract violation for other objects to set it.')); } if (sizedByParent) - contract = 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().'; + information.add(ErrorDescription('Because this RenderBox has sizedByParent set to true, it must set its size in performResize().')); else - contract = 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().'; - throw FlutterError( - 'RenderBox size setter called incorrectly.\n' - '$violation\n' - '$hint\n' - '$contract\n' - 'The RenderBox in question is:\n' - ' $this' - ); + information.add(ErrorDescription('Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().')); + throw FlutterError.fromParts(information); }()); assert(() { value = debugAdoptSize(value); @@ -1713,78 +1711,80 @@ abstract class RenderBox extends RenderObject { assert(() { if (!hasSize) { assert(!debugNeedsLayout); // this is called in the size= setter during layout, but in that case we have a size - String contract; + DiagnosticsNode contract; if (sizedByParent) - contract = 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().\n'; + contract = ErrorDescription('Because this RenderBox has sizedByParent set to true, it must set its size in performResize().'); else - contract = 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().\n'; - throw FlutterError( - 'RenderBox did not set its size during layout.\n' - '$contract' - 'It appears that this did not happen; layout completed, but the size property is still null.\n' - 'The RenderBox in question is:\n' - ' $this' - ); + contract = ErrorDescription('Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().'); + throw FlutterError.fromParts([ + ErrorSummary('RenderBox did not set its size during layout.'), + contract, + ErrorDescription('It appears that this did not happen; layout completed, but the size property is still null.'), + DiagnosticsProperty('The RenderBox in question is', this, style: DiagnosticsTreeStyle.errorProperty) + ]); } // verify that the size is not infinite if (!_size.isFinite) { - final StringBuffer information = StringBuffer(); + final List information = [ + ErrorSummary('$runtimeType object was given an infinite size during layout.'), + ErrorDescription( + 'This probably means that it is a render object that tries to be ' + 'as big as possible, but it was put inside another render object ' + 'that allows its children to pick their own size.' + ) + ]; if (!constraints.hasBoundedWidth) { RenderBox node = this; while (!node.constraints.hasBoundedWidth && node.parent is RenderBox) node = node.parent; - information.writeln('The nearest ancestor providing an unbounded width constraint is:'); - information.write(' '); - information.writeln(node.toStringShallow(joiner: '\n ')); + + information.add(node.describeForError('The nearest ancestor providing an unbounded width constraint is')); } if (!constraints.hasBoundedHeight) { RenderBox node = this; while (!node.constraints.hasBoundedHeight && node.parent is RenderBox) node = node.parent; - information.writeln('The nearest ancestor providing an unbounded height constraint is:'); - information.write(' '); - information.writeln(node.toStringShallow(joiner: '\n ')); + information.add(node.describeForError('The nearest ancestor providing an unbounded height constraint is')); } - throw FlutterError( - '$runtimeType object was given an infinite size during layout.\n' + final List errorParts = []; + errorParts.add(ErrorSummary('$runtimeType object was given an infinite size during layout.')); + errorParts.add(ErrorDescription( 'This probably means that it is a render object that tries to be ' 'as big as possible, but it was put inside another render object ' - 'that allows its children to pick their own size.\n' - '$information' - 'The constraints that applied to the $runtimeType were:\n' - ' $constraints\n' - 'The exact size it was given was:\n' - ' $_size\n' - 'See https://flutter.dev/layout/ for more information.' - ); - } + 'that allows its children to pick their own size.' + )); + errorParts.addAll(information); + errorParts.add(DiagnosticsProperty('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty)); + errorParts.add(DiagnosticsProperty('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty)); + errorParts.add(ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.')); + throw FlutterError.fromParts(errorParts); + } // verify that the size is within the constraints if (!constraints.isSatisfiedBy(_size)) { - throw FlutterError( - '$runtimeType does not meet its constraints.\n' - 'Constraints: $constraints\n' - 'Size: $_size\n' - 'If you are not writing your own RenderBox subclass, then this is not ' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=BUG.md' - ); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType does not meet its constraints.'), + DiagnosticsProperty('Constraints', constraints, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('Size', _size, style: DiagnosticsTreeStyle.errorProperty), + ErrorHint( + 'If you are not writing your own RenderBox subclass, then this is not ' + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=BUG.md' + ), + ]); } if (debugCheckIntrinsicSizes) { // verify that the intrinsics are sane assert(!RenderObject.debugCheckingIntrinsics); RenderObject.debugCheckingIntrinsics = true; - final StringBuffer failures = StringBuffer(); - int failureCount = 0; + final List failures = []; double testIntrinsic(double function(double extent), String name, double constraint) { final double result = function(constraint); if (result < 0) { - failures.writeln(' * $name($constraint) returned a negative value: $result'); - failureCount += 1; + failures.add(ErrorDescription(' * $name($constraint) returned a negative value: $result')); } if (!result.isFinite) { - failures.writeln(' * $name($constraint) returned a non-finite value: $result'); - failureCount += 1; + failures.add(ErrorDescription(' * $name($constraint) returned a non-finite value: $result')); } return result; } @@ -1793,8 +1793,7 @@ abstract class RenderBox extends RenderObject { final double min = testIntrinsic(getMin, 'getMinIntrinsic$name', constraint); final double max = testIntrinsic(getMax, 'getMaxIntrinsic$name', constraint); if (min > max) { - failures.writeln(' * getMinIntrinsic$name($constraint) returned a larger value ($min) than getMaxIntrinsic$name($constraint) ($max)'); - failureCount += 1; + failures.add(ErrorDescription(' * getMinIntrinsic$name($constraint) returned a larger value ($min) than getMaxIntrinsic$name($constraint) ($max)')); } } @@ -1809,13 +1808,15 @@ abstract class RenderBox extends RenderObject { RenderObject.debugCheckingIntrinsics = false; if (failures.isNotEmpty) { - assert(failureCount > 0); - throw FlutterError( - 'The intrinsic dimension methods of the $runtimeType class returned values that violate the intrinsic protocol contract.\n' - 'The following ${failureCount > 1 ? "failures" : "failure"} was detected:\n' - '$failures' - 'If you are not writing your own RenderBox subclass, then this is not\n' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=BUG.md' + // TODO(jacobr): consider nesting the failures object so it is collapsible. + throw FlutterError.fromParts([ + ErrorSummary('The intrinsic dimension methods of the $runtimeType class returned values that violate the intrinsic protocol contract.'), + ErrorDescription('The following ${failures.length > 1 ? "failures" : "failure"} was detected:') // should this be tagged as an error or not? + ]..addAll(failures) + ..add(ErrorHint( + 'If you are not writing your own RenderBox subclass, then this is not\n' + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=BUG.md' + )) ); } } diff --git a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart index 2e936df0d9..d7a0d6d0f2 100644 --- a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart +++ b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart @@ -198,16 +198,23 @@ mixin DebugOverflowIndicatorMixin on RenderObject { return regions; } - void _reportOverflow(RelativeRect overflow, String overflowHints) { - overflowHints ??= 'The edge of the $runtimeType that is ' - 'overflowing has been marked in the rendering with a yellow and black ' - 'striped pattern. This is usually caused by the contents being too big ' - 'for the $runtimeType.\n' - 'This is considered an error condition because it indicates that there ' - 'is content that cannot be seen. If the content is legitimately bigger ' - 'than the available space, consider clipping it with a ClipRect widget ' - 'before putting it in the $runtimeType, or using a scrollable ' - 'container, like a ListView.'; + void _reportOverflow(RelativeRect overflow, List overflowHints) { + overflowHints ??= []; + if (overflowHints.isEmpty) { + overflowHints.add(ErrorDescription( + 'The edge of the $runtimeType that is ' + 'overflowing has been marked in the rendering with a yellow and black ' + 'striped pattern. This is usually caused by the contents being too big ' + 'for the $runtimeType.' + )); + overflowHints.add(ErrorHint( + 'This is considered an error condition because it indicates that there ' + 'is content that cannot be seen. If the content is legitimately bigger ' + 'than the available space, consider clipping it with a ClipRect widget ' + 'before putting it in the $runtimeType, or using a scrollable ' + 'container, like a ListView.' + )); + } final List overflows = []; if (overflow.left > 0.0) @@ -232,18 +239,22 @@ mixin DebugOverflowIndicatorMixin on RenderObject { overflows[overflows.length - 1] = 'and ${overflows[overflows.length - 1]}'; overflowText = overflows.join(', '); } + // TODO(jacobr): add the overflows in pixels as structured data so they can + // be visualized in debugging tools. FlutterError.reportError( FlutterErrorDetailsForRendering( - exception: 'A $runtimeType overflowed by $overflowText.', + exception: FlutterError('A $runtimeType overflowed by $overflowText.'), library: 'rendering library', - context: 'during layout', + context: ErrorDescription('during layout'), renderObject: this, - informationCollector: (StringBuffer information) { - information.writeln(overflowHints); - information.writeln('The specific $runtimeType in question is:'); - information.writeln(' ${toStringShallow(joiner: '\n ')}'); - information.writeln('◢◤' * (FlutterError.wrapWidth ~/ 2)); - }, + informationCollector: () sync* { + yield* overflowHints; + yield describeForError('The specific $runtimeType in question is'); + // TODO(jacobr): this line is ascii art that it would be nice to + // handle a little more generically in GUI debugging clients in the + // future. + yield DiagnosticsNode.message('◢◤' * (FlutterError.wrapWidth ~/ 2), allowWrap: false); + } ), ); } @@ -259,7 +270,7 @@ mixin DebugOverflowIndicatorMixin on RenderObject { Offset offset, Rect containerRect, Rect childRect, { - String overflowHints, + List overflowHints, }) { final RelativeRect overflow = RelativeRect.fromRect(containerRect, childRect); diff --git a/packages/flutter/lib/src/rendering/flex.dart b/packages/flutter/lib/src/rendering/flex.dart index 3208df716d..d034da81c3 100644 --- a/packages/flutter/lib/src/rendering/flex.dart +++ b/packages/flutter/lib/src/rendering/flex.dart @@ -653,15 +653,16 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin addendum = []; if (!canFlex && (mainAxisSize == MainAxisSize.max || _getFit(child) == FlexFit.tight)) { - error = 'RenderFlex children have non-zero flex but incoming $dimension constraints are unbounded.'; - message = 'When a $identity is in a parent that does not provide a finite $dimension constraint, for example ' - 'if it is in a $axis scrollable, it will try to shrink-wrap its children along the $axis ' - 'axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to ' - 'expand to fill the remaining space in the $axis direction.'; - final StringBuffer information = StringBuffer(); + error = ErrorSummary('RenderFlex children have non-zero flex but incoming $dimension constraints are unbounded.'); + message = ErrorDescription( + 'When a $identity is in a parent that does not provide a finite $dimension constraint, for example ' + 'if it is in a $axis scrollable, it will try to shrink-wrap its children along the $axis ' + 'axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to ' + 'expand to fill the remaining space in the $axis direction.' + ); RenderBox node = this; switch (_direction) { case Axis.horizontal: @@ -678,36 +679,38 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin[ + error, + message, + ErrorDescription( + 'These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child ' + 'cannot simultaneously expand to fit its parent.' + ), + ErrorHint( + 'Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible ' + 'children (using Flexible rather than Expanded). This will allow the flexible children ' + 'to size themselves to less than the infinite remaining space they would otherwise be ' + 'forced to take, and then will cause the RenderFlex to shrink-wrap the children ' + 'rather than expanding to fit the maximum constraints provided by the parent.' + ), + ErrorDescription( + 'If this message did not help you determine the problem, consider using debugDumpRenderTree():\n' + ' https://flutter.dev/debugging/#rendering-layer\n' + ' http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html' + ), + describeForError('The affected RenderFlex is', style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The creator information is set to', debugCreator, style: DiagnosticsTreeStyle.errorProperty) + ]..addAll(addendum) + ..add(ErrorDescription( + 'If none of the above helps enough to fix this problem, please don\'t hesitate to file a bug:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md' + ))); }()); totalFlex += childParentData.flex; lastFlexChild = child; @@ -953,19 +956,28 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin debugOverflowHints = [ + ErrorDescription( + 'The overflowing $runtimeType has an orientation of $_direction.' + ), + ErrorDescription( + 'The edge of the $runtimeType that is overflowing has been marked ' + 'in the rendering with a yellow and black striped pattern. This is ' + 'usually caused by the contents being too big for the $runtimeType.' + ), + ErrorHint( + 'Consider applying a flex factor (e.g. using an Expanded widget) to ' + 'force the children of the $runtimeType to fit within the available ' + 'space instead of being sized to their natural size.' + ), + ErrorHint( + 'This is considered an error condition because it indicates that there ' + 'is content that cannot be seen. If the content is legitimately bigger ' + 'than the available space, consider clipping it with a ClipRect widget ' + 'before putting it in the flex, or using a scrollable container rather ' + 'than a Flex, like a ListView.' + ) + ]; // Simulate a child rect that overflows by the right amount. This child // rect is never used for drawing, just for determining the overflow diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index d180cb4023..9970900eb0 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -529,13 +529,11 @@ class ContainerLayer extends Layer { 'See https://api.flutter.dev/flutter/rendering/debugCheckElevations.html ' 'for more details.'), library: 'rendering library', - context: 'during compositing', - informationCollector: (StringBuffer buffer) { - buffer.writeln('Attempted to composite layer:'); - buffer.writeln(child); - buffer.writeln('after layer:'); - buffer.writeln(predecessor); - buffer.writeln('which occupies the same area at a higher elevation.'); + context: ErrorDescription('during compositing'), + informationCollector: () sync* { + yield child.toDiagnosticsNode(name: 'Attempted to composite layer', style: DiagnosticsTreeStyle.errorProperty); + yield predecessor.toDiagnosticsNode(name: 'after layer', style: DiagnosticsTreeStyle.errorProperty); + yield ErrorDescription('which occupies the same area at a higher elevation.'); } )); return [ diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index b2d45c5928..1e26812f53 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -17,7 +17,7 @@ import 'binding.dart'; import 'debug.dart'; import 'layer.dart'; -export 'package:flutter/foundation.dart' show FlutterError, InformationCollector, DiagnosticsNode, DiagnosticsProperty, StringProperty, DoubleProperty, EnumProperty, FlagProperty, IntProperty, DiagnosticPropertiesBuilder; +export 'package:flutter/foundation.dart' show FlutterError, InformationCollector, DiagnosticsNode, ErrorSummary, ErrorDescription, ErrorHint, DiagnosticsProperty, StringProperty, DoubleProperty, EnumProperty, FlagProperty, IntProperty, DiagnosticPropertiesBuilder; export 'package:flutter/gestures.dart' show HitTestEntry, HitTestResult; export 'package:flutter/painting.dart'; @@ -1187,38 +1187,16 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im exception: exception, stack: stack, library: 'rendering library', - context: 'during $method()', + context: ErrorDescription('during $method()'), renderObject: this, - informationCollector: (StringBuffer information) { - information.writeln('The following RenderObject was being processed when the exception was fired:'); - information.writeln(' ${toStringShallow(joiner: '\n ')}'); - final List descendants = []; - const int maxDepth = 5; - int depth = 0; - const int maxLines = 25; - int lines = 0; - void visitor(RenderObject child) { - if (lines < maxLines) { - depth += 1; - descendants.add('${" " * depth}$child'); - if (depth < maxDepth) - child.visitChildren(visitor); - depth -= 1; - } else if (lines == maxLines) { - descendants.add(' ...(descendants list truncated after $lines lines)'); - } - lines += 1; - } - visitChildren(visitor); - if (lines > 1) { - information.writeln('This RenderObject had the following descendants (showing up to depth $maxDepth):'); - } else if (descendants.length == 1) { - information.writeln('This RenderObject had the following child:'); - } else { - information.writeln('This RenderObject has no descendants.'); - } - information.writeAll(descendants, '\n'); - }, + informationCollector: () sync* { + yield describeForError('The following RenderObject was being processed when the exception was fired'); + // TODO(jacobr): this error message has a code smell. Consider whether + // displaying the truncated children is really useful for command line + // users. Inspector users can see the full tree by clicking on the + // render object so this may not be that useful. + yield describeForError('This RenderObject', style: DiagnosticsTreeStyle.truncateChildren); + } )); } @@ -1558,7 +1536,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im assert(constraints != null); assert(constraints.debugAssertIsValid( isAppliedConstraint: true, - informationCollector: (StringBuffer information) { + informationCollector: () sync* { final List stack = StackTrace.current.toString().split('\n'); int targetFrame; final Pattern layoutFramePattern = RegExp(r'^#[0-9]+ +RenderObject.layout \('); @@ -1569,18 +1547,16 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im } } if (targetFrame != null && targetFrame < stack.length) { - information.writeln( - 'These invalid constraints were provided to $runtimeType\'s layout() ' - 'function by the following function, which probably computed the ' - 'invalid constraints in question:' - ); final Pattern targetFramePattern = RegExp(r'^#[0-9]+ +(.+)$'); final Match targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]); - if (targetFrameMatch != null && targetFrameMatch.groupCount > 0) { - information.writeln(' ${targetFrameMatch.group(1)}'); - } else { - information.writeln(stack[targetFrame]); - } + final String problemFunction = (targetFrameMatch != null && targetFrameMatch.groupCount > 0) ? targetFrameMatch.group(1) : stack[targetFrame].trim(); + // TODO(jacobr): this case is similar to displaying a single stack frame. + yield ErrorDescription( + 'These invalid constraints were provided to $runtimeType\'s layout() ' + 'function by the following function, which probably computed the ' + 'invalid constraints in question:\n' + ' $problemFunction' + ); } }, )); @@ -2712,6 +2688,19 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im ); } } + + /// Adds a debug representation of a [RenderObject] optimized for including in + /// error messages. + /// + /// The default [style] of [DiagnosticsTreeStyle.shallow] ensures that all of + /// the properties of the render object are included in the error output but + /// none of the children of the object are. + /// + /// You should always include a RenderObject in an error message if it is the + /// [RenderObject] causing the failure or contract violation of the error. + DiagnosticsNode describeForError(String name, { DiagnosticsTreeStyle style = DiagnosticsTreeStyle.shallow }) { + return toDiagnosticsNode(name: name, style: style); + } } /// Generic mixin for render objects with one child. @@ -3108,7 +3097,7 @@ class FlutterErrorDetailsForRendering extends FlutterErrorDetails { dynamic exception, StackTrace stack, String library, - String context, + DiagnosticsNode context, this.renderObject, InformationCollector informationCollector, bool silent = false, diff --git a/packages/flutter/lib/src/rendering/sliver.dart b/packages/flutter/lib/src/rendering/sliver.dart index 4076adb253..5169cc5865 100644 --- a/packages/flutter/lib/src/rendering/sliver.dart +++ b/packages/flutter/lib/src/rendering/sliver.dart @@ -421,10 +421,14 @@ class SliverConstraints extends Constraints { void verify(bool check, String message) { if (check) return; - final StringBuffer information = StringBuffer(); - if (informationCollector != null) - informationCollector(information); - throw FlutterError('$runtimeType is not valid: $message\n${information}The offending constraints were:\n $this'); + final List information = []; + information.add(ErrorSummary('$runtimeType is not valid: $message')); + + if (informationCollector != null) { + information.addAll(informationCollector()); + } + information.add(DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty)); + throw FlutterError.fromParts(information); } verify(axis != null, 'The "axis" is null.'); verify(growthDirection != null, 'The "growthDirection" is null.'); @@ -696,14 +700,20 @@ class SliverGeometry extends Diagnosticable { InformationCollector informationCollector, }) { assert(() { - void verify(bool check, String message) { + void verify(bool check, String summary, {List details}) { if (check) return; - final StringBuffer information = StringBuffer(); - if (informationCollector != null) - informationCollector(information); - throw FlutterError('$runtimeType is not valid: $message\n$information'); + final List information = []; + information.add(ErrorSummary('$runtimeType is not valid: $summary')); + if (details != null) { + information.addAll(details); + } + if (informationCollector != null) { + information.addAll(informationCollector()); + } + throw FlutterError.fromParts(information); } + verify(scrollExtent != null, 'The "scrollExtent" is null.'); verify(scrollExtent >= 0.0, 'The "scrollExtent" is negative.'); verify(paintExtent != null, 'The "paintExtent" is null.'); @@ -714,8 +724,8 @@ class SliverGeometry extends Diagnosticable { verify(cacheExtent >= 0.0, 'The "cacheExtent" is negative.'); if (layoutExtent > paintExtent) { verify(false, - 'The "layoutExtent" exceeds the "paintExtent".\n' + - _debugCompareFloats('paintExtent', paintExtent, 'layoutExtent', layoutExtent), + 'The "layoutExtent" exceeds the "paintExtent".', + details: _debugCompareFloats('paintExtent', paintExtent, 'layoutExtent', layoutExtent), ); } verify(maxPaintExtent != null, 'The "maxPaintExtent" is null.'); @@ -723,9 +733,10 @@ class SliverGeometry extends Diagnosticable { // than precisionErrorTolerance, we will not throw the assert below. if (paintExtent - maxPaintExtent > precisionErrorTolerance) { verify(false, - 'The "maxPaintExtent" is less than the "paintExtent".\n' + - _debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent) + - 'By definition, a sliver can\'t paint more than the maximum that it can paint!', + 'The "maxPaintExtent" is less than the "paintExtent".', + details: + _debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent) + ..add(ErrorDescription('By definition, a sliver can\'t paint more than the maximum that it can paint!')) ); } verify(hitTestExtent != null, 'The "hitTestExtent" is null.'); @@ -866,14 +877,22 @@ class SliverPhysicalParentData extends ParentData { /// children using absolute coordinates. class SliverPhysicalContainerParentData extends SliverPhysicalParentData with ContainerParentDataMixin { } -String _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) { +List _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) { + final List information = []; if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1)) { - return 'The $labelA is ${valueA.toStringAsFixed(1)}, but ' - 'the $labelB is ${valueB.toStringAsFixed(1)}. '; + information..add(ErrorDescription( + 'The $labelA is ${valueA.toStringAsFixed(1)}, but ' + 'the $labelB is ${valueB.toStringAsFixed(1)}.' + )); + } else { + information + ..add(ErrorDescription('The $labelA is $valueA, but the $labelB is $valueB.')) + ..add(ErrorHint( + 'Maybe you have fallen prey to floating point rounding errors, and should explicitly ' + 'apply the min() or max() functions, or the clamp() method, to the $labelB?' + )); } - return 'The $labelA is $valueA, but the $labelB is $valueB. ' - 'Maybe you have fallen prey to floating point rounding errors, and should explicitly ' - 'apply the min() or max() functions, or the clamp() method, to the $labelB? '; + return information; } /// Base class for the render objects that implement scroll effects in viewports. @@ -1036,28 +1055,30 @@ abstract class RenderSliver extends RenderObject { (!sizedByParent && debugDoingThisLayout)) return true; assert(!debugDoingThisResize); - String contract, violation, hint; + DiagnosticsNode contract, violation, hint; if (debugDoingThisLayout) { assert(sizedByParent); - violation = 'It appears that the geometry setter was called from performLayout().'; - hint = ''; + violation = ErrorDescription('It appears that the geometry setter was called from performLayout().'); } else { - violation = 'The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).'; + violation = ErrorDescription('The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).'); if (owner != null && owner.debugDoingLayout) - hint = 'Only the object itself can set its geometry. It is a contract violation for other objects to set it.'; + hint = ErrorDescription('Only the object itself can set its geometry. It is a contract violation for other objects to set it.'); } if (sizedByParent) - contract = 'Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().'; + contract = ErrorDescription('Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().'); else - contract = 'Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().'; - throw FlutterError( - 'RenderSliver geometry setter called incorrectly.\n' - '$violation\n' - '$hint\n' - '$contract\n' - 'The RenderSliver in question is:\n' - ' $this' - ); + contract = ErrorDescription('Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().'); + + final List information = [ + ErrorSummary('RenderSliver geometry setter called incorrectly.'), + violation + ]; + if (hint != null) + information.add(hint); + information.add(contract); + information.add(describeForError('The RenderSliver in question is')); + + throw FlutterError.fromParts(information); }()); _geometry = value; } @@ -1091,22 +1112,23 @@ abstract class RenderSliver extends RenderObject { @override void debugAssertDoesMeetConstraints() { assert(geometry.debugAssertIsValid( - informationCollector: (StringBuffer information) { - information.writeln('The RenderSliver that returned the offending geometry was:'); - information.writeln(' ${toStringShallow(joiner: '\n ')}'); - }, + informationCollector: () sync* { + yield describeForError('The RenderSliver that returned the offending geometry was'); + } )); assert(() { if (geometry.paintExtent > constraints.remainingPaintExtent) { - throw FlutterError( - 'SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.\n' - 'The render object whose geometry violates the constraints is the following:\n' - ' ${toStringShallow(joiner: '\n ')}\n' + - _debugCompareFloats('remainingPaintExtent', constraints.remainingPaintExtent, - 'paintExtent', geometry.paintExtent) + + throw FlutterError.fromParts([ + ErrorSummary('SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.'), + describeForError('The render object whose geometry violates the constraints is the following') + ]..addAll(_debugCompareFloats( + 'remainingPaintExtent', constraints.remainingPaintExtent, + 'paintExtent', geometry.paintExtent, + )) + ..add(ErrorDescription( 'The paintExtent must cause the child sliver to paint within the viewport, and so ' - 'cannot exceed the remainingPaintExtent.' - ); + 'cannot exceed the remainingPaintExtent.', + ))); } return true; }()); diff --git a/packages/flutter/lib/src/scheduler/binding.dart b/packages/flutter/lib/src/scheduler/binding.dart index 2ede21d5de..a5793a7cd5 100644 --- a/packages/flutter/lib/src/scheduler/binding.dart +++ b/packages/flutter/lib/src/scheduler/binding.dart @@ -393,14 +393,14 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { exception: exception, stack: exceptionStack, library: 'scheduler library', - context: 'during a task callback', - informationCollector: (callbackStack == null) ? null : (StringBuffer information) { - information.writeln( - '\nThis exception was thrown in the context of a task callback. ' - 'When the task callback was _registered_ (as opposed to when the ' - 'exception was thrown), this was the stack:' + context: ErrorDescription('during a task callback'), + informationCollector: (callbackStack == null) ? null : () sync* { + yield DiagnosticsStackTrace( + '\nThis exception was thrown in the context of a scheduler callback. ' + 'When the scheduler callback was _registered_ (as opposed to when the ' + 'exception was thrown), this was the stack', + callbackStack, ); - FlutterError.defaultStackFilter(callbackStack.toString().trimRight().split('\n')).forEach(information.writeln); }, )); } @@ -493,22 +493,22 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { FlutterError.reportError(FlutterErrorDetails( exception: reason, library: 'scheduler library', - informationCollector: (StringBuffer information) { + informationCollector: () sync* { if (count == 1) { - information.writeln( + // TODO(jacobr): I have added an extra line break in this case. + yield ErrorDescription( 'There was one transient callback left. ' 'The stack trace for when it was registered is as follows:' ); } else { - information.writeln( + yield ErrorDescription( 'There were $count transient callbacks left. ' 'The stack traces for when they were registered are as follows:' ); } for (int id in callbacks.keys) { final _FrameCallbackEntry entry = callbacks[id]; - information.writeln('── callback $id ──'); - FlutterError.defaultStackFilter(entry.debugStack.toString().trimRight().split('\n')).forEach(information.writeln); + yield DiagnosticsStackTrace('── callback $id ──', entry.debugStack, showSeparator: false); } }, )); @@ -1015,14 +1015,14 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { exception: exception, stack: exceptionStack, library: 'scheduler library', - context: 'during a scheduler callback', - informationCollector: (callbackStack == null) ? null : (StringBuffer information) { - information.writeln( + context: ErrorDescription('during a scheduler callback'), + informationCollector: (callbackStack == null) ? null : () sync* { + yield DiagnosticsStackTrace( '\nThis exception was thrown in the context of a scheduler callback. ' 'When the scheduler callback was _registered_ (as opposed to when the ' - 'exception was thrown), this was the stack:' + 'exception was thrown), this was the stack', + callbackStack, ); - FlutterError.defaultStackFilter(callbackStack.toString().trimRight().split('\n')).forEach(information.writeln); }, )); } diff --git a/packages/flutter/lib/src/services/platform_channel.dart b/packages/flutter/lib/src/services/platform_channel.dart index 6fcaca5ada..3c9c1625cb 100644 --- a/packages/flutter/lib/src/services/platform_channel.dart +++ b/packages/flutter/lib/src/services/platform_channel.dart @@ -493,7 +493,7 @@ class EventChannel { exception: exception, stack: stack, library: 'services library', - context: 'while activating platform stream on channel $name', + context: ErrorDescription('while activating platform stream on channel $name'), )); } }, onCancel: () async { @@ -505,7 +505,7 @@ class EventChannel { exception: exception, stack: stack, library: 'services library', - context: 'while de-activating platform stream on channel $name', + context: ErrorDescription('while de-activating platform stream on channel $name'), )); } }); diff --git a/packages/flutter/lib/src/services/platform_messages.dart b/packages/flutter/lib/src/services/platform_messages.dart index 1aa026291c..2f0b05f3bb 100644 --- a/packages/flutter/lib/src/services/platform_messages.dart +++ b/packages/flutter/lib/src/services/platform_messages.dart @@ -51,7 +51,7 @@ class BinaryMessages { exception: exception, stack: stack, library: 'services library', - context: 'during a platform message response callback', + context: ErrorDescription('during a platform message response callback'), )); } }); @@ -79,7 +79,7 @@ class BinaryMessages { exception: exception, stack: stack, library: 'services library', - context: 'during a platform message callback', + context: ErrorDescription('during a platform message callback'), )); } finally { callback(response); diff --git a/packages/flutter/lib/src/widgets/binding.dart b/packages/flutter/lib/src/widgets/binding.dart index 0599fe0131..3654918ae7 100644 --- a/packages/flutter/lib/src/widgets/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -937,7 +937,7 @@ class RenderObjectToWidgetElement extends RootRenderObje exception: exception, stack: stack, library: 'widgets library', - context: 'attaching to the render tree', + context: ErrorDescription('attaching to the render tree'), ); FlutterError.reportError(details); final Widget error = ErrorWidget.builder(details); diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index d02f997957..257ad9116e 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -21,9 +21,9 @@ export 'package:flutter/foundation.dart' show protected, required, visibleForTesting; -export 'package:flutter/foundation.dart' show FlutterError, debugPrint, debugPrintStack; +export 'package:flutter/foundation.dart' show FlutterError, ErrorSummary, ErrorDescription, ErrorHint, debugPrint, debugPrintStack; export 'package:flutter/foundation.dart' show VoidCallback, ValueChanged, ValueGetter, ValueSetter; -export 'package:flutter/foundation.dart' show DiagnosticLevel; +export 'package:flutter/foundation.dart' show DiagnosticsNode, DiagnosticLevel; export 'package:flutter/foundation.dart' show Key, LocalKey, ValueKey; export 'package:flutter/rendering.dart' show RenderObject, RenderBox, debugDumpRenderTree, debugDumpLayerTree; @@ -197,16 +197,19 @@ abstract class GlobalKey> extends Key { _debugIllFatedElements.clear(); _debugReservations.clear(); if (duplicates != null) { - final StringBuffer buffer = StringBuffer(); - buffer.writeln('Multiple widgets used the same GlobalKey.\n'); + final List information = []; + information.add(ErrorSummary('Multiple widgets used the same GlobalKey.')); for (GlobalKey key in duplicates.keys) { final Set elements = duplicates[key]; - buffer.writeln('The key $key was used by ${elements.length} widgets:'); - for (Element element in elements) - buffer.writeln('- $element'); + // TODO(jacobr): this will omit the '- ' before each widget name and + // use the more standard whitespace style instead. Please let me know + // if the '- ' style is a feature we want to maintain and we can add + // another tree style that supports it. I also see '* ' in some places + // so it would be nice to unify and normalize. + information.add(Element.describeElements('The key $key was used by ${elements.length} widgets', elements)); } - buffer.write('A GlobalKey can only be specified on one widget at a time in the widget tree.'); - throw FlutterError(buffer.toString()); + information.add(ErrorDescription('A GlobalKey can only be specified on one widget at a time in the widget tree.')); + throw FlutterError.fromParts(information); } return true; }()); @@ -2066,6 +2069,24 @@ abstract class BuildContext { /// pull data down, than it is to use [visitChildElements] recursively to push /// data down to them. void visitChildElements(ElementVisitor visitor); + + /// Returns a description of an [Element] from the current build context. + DiagnosticsNode describeElement(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}); + + /// Returns a description of the [Widget] associated with the current build context. + DiagnosticsNode describeWidget(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}); + + /// Adds a description of a specific type of widget missing from the current + /// build context's ancestry tree. + /// + /// You can find an example of using this method in [debugCheckHasMaterial]. + List describeMissingAncestor({ @required Type expectedAncestorType }); + + /// Adds a description of the ownership chain from a specific [Element] + /// to the error report. + /// + /// The ownership chain is useful for debugging the source of an element. + DiagnosticsNode describeOwnershipChain(String name); } /// Manager class for the widgets framework. @@ -2278,10 +2299,11 @@ class BuildOwner { _dirtyElements[index].rebuild(); } catch (e, stack) { _debugReportException( - 'while rebuilding dirty elements', e, stack, - informationCollector: (StringBuffer information) { - information.writeln('The element being rebuilt at the time was index $index of $dirtyCount:'); - information.write(' ${_dirtyElements[index]}'); + ErrorDescription('while rebuilding dirty elements'), + e, + stack, + informationCollector: () sync* { + yield _dirtyElements[index].describeElement('The element being rebuilt at the time was index $index of $dirtyCount'); }, ); } @@ -2442,7 +2464,7 @@ class BuildOwner { return true; }()); } catch (e, stack) { - _debugReportException('while finalizing the widget tree', e, stack); + _debugReportException(ErrorSummary('while finalizing the widget tree'), e, stack); } finally { Timeline.finishSync(); } @@ -2642,6 +2664,60 @@ abstract class Element extends DiagnosticableTree implements BuildContext { return result; } + @override + List describeMissingAncestor({ @required Type expectedAncestorType }) { + final List information = []; + final List ancestors = []; + visitAncestorElements((Element element) { + ancestors.add(element); + return true; + }); + + information.add(DiagnosticsProperty( + 'The specific widget that could not find a $expectedAncestorType ancestor was', + this, + style: DiagnosticsTreeStyle.errorProperty, + )); + + if (ancestors.isNotEmpty) { + information.add(describeElements('The ancestors of this widget were', ancestors)); + } else { + information.add(ErrorDescription( + 'This widget is the root of the tree, so it has no ' + 'ancestors, let alone a "$expectedAncestorType" ancestor.' + )); + } + return information; + } + + /// Returns a list of [Element]s from the current build context to the error report. + static DiagnosticsNode describeElements(String name, Iterable elements) { + return DiagnosticsBlock( + name: name, + children: elements.map((Element element) => DiagnosticsProperty('', element)).toList(), + allowTruncate: true, + ); + } + + @override + DiagnosticsNode describeElement(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}) { + return DiagnosticsProperty(name, this, style: style); + } + + @override + DiagnosticsNode describeWidget(String name, {DiagnosticsTreeStyle style = DiagnosticsTreeStyle.errorProperty}) { + return DiagnosticsProperty(name, this, style: style); + } + + @override + DiagnosticsNode describeOwnershipChain(String name) { + // TODO(jacobr): make this structured so clients can support clicks on + // individual entries. For example, is this an iterable with arrows as + // separators? + return StringProperty(name, debugGetCreatorChain(10)); + } + + // This is used to verify that Element objects move through life in an // orderly fashion. _ElementLifecycle _debugLifecycleState = _ElementLifecycle.initial; @@ -3600,6 +3676,7 @@ class ErrorWidget extends LeafRenderObjectWidget { /// Creates a widget that displays the given error message. ErrorWidget(Object exception) : message = _stringify(exception), + _flutterError = exception is FlutterError ? exception : null, super(key: UniqueKey()); /// The configurable factory for [ErrorWidget]. @@ -3630,6 +3707,7 @@ class ErrorWidget extends LeafRenderObjectWidget { /// The message to display. final String message; + final FlutterError _flutterError; static String _stringify(Object exception) { try { @@ -3646,7 +3724,10 @@ class ErrorWidget extends LeafRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(StringProperty('message', message, quoted: false)); + if (_flutterError == null) + properties.add(StringProperty('message', message, quoted: false)); + else + properties.add(_flutterError.toDiagnosticsNode(style: DiagnosticsTreeStyle.whitespace)); } } @@ -3739,7 +3820,7 @@ abstract class ComponentElement extends Element { built = build(); debugWidgetBuilderValue(widget, built); } catch (e, stack) { - built = ErrorWidget.builder(_debugReportException('building $this', e, stack)); + built = ErrorWidget.builder(_debugReportException(ErrorDescription('building $this'), e, stack)); } finally { // We delay marking the element as clean until after calling build() so // that attempts to markNeedsBuild() during build() will be ignored. @@ -3750,7 +3831,7 @@ abstract class ComponentElement extends Element { _child = updateChild(_child, built, slot); assert(_child != null); } catch (e, stack) { - built = ErrorWidget.builder(_debugReportException('building $this', e, stack)); + built = ErrorWidget.builder(_debugReportException(ErrorDescription('building $this'), e, stack)); _child = updateChild(null, built, slot); } @@ -5002,7 +5083,7 @@ class _DebugCreator { } FlutterErrorDetails _debugReportException( - String context, + DiagnosticsNode context, dynamic exception, StackTrace stack, { InformationCollector informationCollector, diff --git a/packages/flutter/lib/src/widgets/image.dart b/packages/flutter/lib/src/widgets/image.dart index ae0046bc63..caf02af3a9 100644 --- a/packages/flutter/lib/src/widgets/image.dart +++ b/packages/flutter/lib/src/widgets/image.dart @@ -93,7 +93,7 @@ Future precacheImage( onError(exception, stackTrace); } else { FlutterError.reportError(FlutterErrorDetails( - context: 'image failed to precache', + context: ErrorDescription('image failed to precache'), library: 'image resource service', exception: exception, stack: stackTrace, diff --git a/packages/flutter/lib/src/widgets/layout_builder.dart b/packages/flutter/lib/src/widgets/layout_builder.dart index ab7f34dad3..0e67506fb6 100644 --- a/packages/flutter/lib/src/widgets/layout_builder.dart +++ b/packages/flutter/lib/src/widgets/layout_builder.dart @@ -113,14 +113,14 @@ class _LayoutBuilderElement extends RenderObjectElement { built = widget.builder(this, constraints); debugWidgetBuilderValue(widget, built); } catch (e, stack) { - built = ErrorWidget.builder(_debugReportException('building $widget', e, stack)); + built = ErrorWidget.builder(_debugReportException(ErrorDescription('building $widget'), e, stack)); } } try { _child = updateChild(_child, built, null); assert(_child != null); } catch (e, stack) { - built = ErrorWidget.builder(_debugReportException('building $widget', e, stack)); + built = ErrorWidget.builder(_debugReportException(ErrorDescription('building $widget'), e, stack)); _child = updateChild(null, built, slot); } }); @@ -226,7 +226,7 @@ class _RenderLayoutBuilder extends RenderBox with RenderObjectWithChildMixin groupName != null; + + /// Include the text rendering of the nodes (helpful for debugging). + final bool includeToStringDeep; + + final int maxDescendentsTruncatableNode; } // Production implementation of [WidgetInspectorService]. @@ -961,6 +970,22 @@ mixin WidgetInspectorService { return Future.value(); } + static const String _consoleObjectGroup = 'console-group'; + + void _reportError(FlutterErrorDetails details) { + postEvent('Flutter.Error', _nodeToJson( + details.toDiagnosticsNode(), + _SerializeConfig( + groupName: _consoleObjectGroup, + includeToStringDeep: true, + subtreeDepth: 5, + includeProperties: true, + expandPropertyValues: true, + maxDescendentsTruncatableNode: 5, + ), + )); + } + /// Called to register service extensions. /// /// See also: @@ -975,6 +1000,18 @@ mixin WidgetInspectorService { SchedulerBinding.instance.addPersistentFrameCallback(_onFrameStart); + final FlutterExceptionHandler structuredExceptionHandler = _reportError; + final FlutterExceptionHandler defaultExceptionHandler = FlutterError.onError; + + _registerBoolServiceExtension( + name: 'structuredErrors', + getter: () async => FlutterError.onError == structuredExceptionHandler, + setter: (bool value) { + FlutterError.onError = value ? structuredExceptionHandler : defaultExceptionHandler; + return Future.value(); + }, + ); + _registerBoolServiceExtension( name: 'show', getter: () async => WidgetsApp.debugShowWidgetInspectorOverride, @@ -1236,7 +1273,7 @@ mixin WidgetInspectorService { final _InspectorReferenceData data = _idToReferenceData[id]; if (data == null) { - throw FlutterError('Id does not exist.'); + throw FlutterError.fromParts([ErrorSummary('Id does not exist.')]); } return data.object; } @@ -1271,9 +1308,9 @@ mixin WidgetInspectorService { final _InspectorReferenceData referenceData = _idToReferenceData[id]; if (referenceData == null) - throw FlutterError('Id does not exist'); + throw FlutterError.fromParts([ErrorSummary('Id does not exist')]); if (_groups[groupName]?.remove(referenceData) != true) - throw FlutterError('Id is not in group'); + throw FlutterError.fromParts([ErrorSummary('Id is not in group')]); _decrementReferenceCount(referenceData); } @@ -1316,11 +1353,13 @@ mixin WidgetInspectorService { return false; } selection.currentElement = object; + developer.inspect(selection.currentElement); } else { if (object == selection.current) { return false; } selection.current = object; + developer.inspect(selection.current); } if (selectionChangedCallback != null) { if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) { @@ -1357,7 +1396,7 @@ mixin WidgetInspectorService { else if (value is Element) path = _getElementParentChain(value, groupName); else - throw FlutterError('Cannot get parent chain for node of type ${value.runtimeType}'); + throw FlutterError.fromParts([ErrorSummary('Cannot get parent chain for node of type ${value.runtimeType}')]); return path.map((_DiagnosticsPathNode node) => _pathNodeToJson( node, @@ -1370,7 +1409,7 @@ mixin WidgetInspectorService { return null; return { 'node': _nodeToJson(pathNode.node, config), - 'children': _nodesToJson(pathNode.children, config), + 'children': _nodesToJson(pathNode.children, config, parent: pathNode.node), 'childIndex': pathNode.childIndex, }; } @@ -1444,15 +1483,20 @@ mixin WidgetInspectorService { if (config.subtreeDepth > 0 || (config.pathToInclude != null && config.pathToInclude.isNotEmpty)) { - json['children'] = _nodesToJson(_getChildrenHelper(node, config), config); + json['children'] = _nodesToJson(_getChildrenHelper(node, config), config, parent: node); } if (config.includeProperties) { + List properties = node.getProperties(); + if (properties.isEmpty && value is Diagnosticable) { + properties = value.toDiagnosticsNode().getProperties(); + } json['properties'] = _nodesToJson( - node.getProperties().where( + properties.where( (DiagnosticsNode node) => !node.isFiltered(createdByLocalProject ? DiagnosticLevel.fine : DiagnosticLevel.info), ), - _SerializeConfig(groupName: config.groupName, subtreeDepth: 1, expandPropertyValues: true), + _SerializeConfig.merge(config, subtreeDepth: math.max(0, config.subtreeDepth - 1)), + parent: node, ); } @@ -1480,6 +1524,7 @@ mixin WidgetInspectorService { subtreeDepth: 0, expandPropertyValues: false, ), + parent: node, ); } } @@ -1523,13 +1568,30 @@ mixin WidgetInspectorService { return jsonString; } + List _truncateNodes(Iterable nodes, _SerializeConfig config) { + if (nodes.every((DiagnosticsNode node) => node.value is Element) && isWidgetCreationTracked()) { + final List localNodes = nodes.where((DiagnosticsNode node) => + _isValueCreatedByLocalProject(node.value)).toList(); + if (localNodes.isNotEmpty) { + return localNodes; + } + } + return nodes.take(config.maxDescendentsTruncatableNode).toList(); + } + List> _nodesToJson( Iterable nodes, - _SerializeConfig config, - ) { + _SerializeConfig config, { + @required DiagnosticsNode parent, + }) { + bool truncated = false; if (nodes == null) return >[]; - return nodes.map>( + if (config.maxDescendentsTruncatableNode >= 0 && parent?.allowTruncate == true && nodes.length > config.maxDescendentsTruncatableNode) { + nodes = _truncateNodes(nodes, config)..add(DiagnosticsNode.message('...')); + truncated = true; + } + final List> json = nodes.map>( (DiagnosticsNode node) { if (config.pathToInclude != null && config.pathToInclude.isNotEmpty) { if (config.pathToInclude.first == node.value) { @@ -1552,6 +1614,9 @@ mixin WidgetInspectorService { _SerializeConfig.merge(config, subtreeDepth: config.subtreeDepth - 1) : config, ); }).toList(); + if (truncated) + json.last['truncated'] = true; + return json; } /// Returns a JSON representation of the properties of the [DiagnosticsNode] @@ -1563,7 +1628,7 @@ mixin WidgetInspectorService { List _getProperties(String diagnosticsNodeId, String groupName) { final DiagnosticsNode node = toObject(diagnosticsNodeId); - return _nodesToJson(node == null ? const [] : node.getProperties(), _SerializeConfig(groupName: groupName)); + return _nodesToJson(node == null ? const [] : node.getProperties(), _SerializeConfig(groupName: groupName), parent: node); } /// Returns a JSON representation of the children of the [DiagnosticsNode] @@ -1575,7 +1640,7 @@ mixin WidgetInspectorService { List _getChildren(String diagnosticsNodeId, String groupName) { final DiagnosticsNode node = toObject(diagnosticsNodeId); final _SerializeConfig config = _SerializeConfig(groupName: groupName); - return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config); + return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config, parent: node); } /// Returns a JSON representation of the children of the [DiagnosticsNode] @@ -1597,7 +1662,7 @@ mixin WidgetInspectorService { List _getChildrenSummaryTree(String diagnosticsNodeId, String groupName) { final DiagnosticsNode node = toObject(diagnosticsNodeId); final _SerializeConfig config = _SerializeConfig(groupName: groupName, summaryTree: true); - return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config); + return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config, parent: node); } /// Returns a JSON representation of the children of the [DiagnosticsNode] @@ -1614,7 +1679,7 @@ mixin WidgetInspectorService { final DiagnosticsNode node = toObject(diagnosticsNodeId); // With this value of minDepth we only expand one extra level of important nodes. final _SerializeConfig config = _SerializeConfig(groupName: groupName, subtreeDepth: 1, includeProperties: true); - return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config); + return _nodesToJson(node == null ? const [] : _getChildrenHelper(node, config), config, parent: node); } List _getChildrenHelper(DiagnosticsNode node, _SerializeConfig config) { @@ -1622,6 +1687,9 @@ mixin WidgetInspectorService { } bool _shouldShowInSummaryTree(DiagnosticsNode node) { + if (node.level == DiagnosticLevel.error) { + return true; + } final Object value = node.value; if (value is! Diagnosticable) { return true; @@ -1634,12 +1702,21 @@ mixin WidgetInspectorService { return _isValueCreatedByLocalProject(value); } + bool _isDeepStyle(DiagnosticsTreeStyle style) => false; + List _getChildrenFiltered( DiagnosticsNode node, _SerializeConfig config, ) { final List children = []; - for (DiagnosticsNode child in node.getChildren()) { + final Object value = node.value; + List rawChildren = node.getChildren(); + if (rawChildren.isEmpty && node is DiagnosticsProperty && value is Diagnosticable && config.expandPropertyValues && + _isDeepStyle(node.style)) { + rawChildren = value.toDiagnosticsNode().getChildren(); + } + + for (DiagnosticsNode child in rawChildren) { if (!config.summaryTree || _shouldShowInSummaryTree(child)) { children.add(child); } else { @@ -2180,7 +2257,6 @@ class _WidgetInspectorState extends State // changed. }); }; - assert(WidgetInspectorService.instance.selectionChangedCallback == null); WidgetInspectorService.instance.selectionChangedCallback = _selectionChangedCallback; } @@ -2557,10 +2633,12 @@ class _InspectorOverlayLayer extends Layer { return true; }()); if (inDebugMode == false) { - throw FlutterError( - 'The inspector should never be used in production mode due to the ' - 'negative performance impact.' - ); + throw FlutterError.fromParts([ + ErrorSummary( + 'The inspector should never be used in production mode due to the ' + 'negative performance impact.' + ) + ]); } } diff --git a/packages/flutter/test/foundation/assertions_test.dart b/packages/flutter/test/foundation/assertions_test.dart index 9c1dddf347..4db1b82706 100644 --- a/packages/flutter/test/foundation/assertions_test.dart +++ b/packages/flutter/test/foundation/assertions_test.dart @@ -22,9 +22,9 @@ void main() { exception: 'Example exception', stack: StackTrace.current, library: 'Example library', - context: 'Example context', - informationCollector: (StringBuffer information) { - information.writeln('Example information'); + context: ErrorDescription('Example context'), + informationCollector: () sync* { + yield ErrorDescription('Example information'); }, ); @@ -46,50 +46,272 @@ void main() { FlutterErrorDetails( exception: 'MESSAGE', library: 'LIBRARY', - context: 'CONTEXTING', - informationCollector: (StringBuffer information) { - information.writeln('INFO'); + context: ErrorDescription('CONTEXTING'), + informationCollector: () sync* { + yield ErrorDescription('INFO'); }, ).toString(), - 'Error caught by LIBRARY, thrown CONTEXTING.\n' - 'MESSAGE\n' - 'INFO', + '══╡ EXCEPTION CAUGHT BY LIBRARY ╞════════════════════════════════\n' + 'The following message was thrown CONTEXTING:\n' + 'MESSAGE\n' + '\n' + 'INFO\n' + '═════════════════════════════════════════════════════════════════\n' + ); expect( FlutterErrorDetails( library: 'LIBRARY', - context: 'CONTEXTING', - informationCollector: (StringBuffer information) { - information.writeln('INFO'); + context: ErrorDescription('CONTEXTING'), + informationCollector: () sync* { + yield ErrorDescription('INFO'); }, ).toString(), - 'Error caught by LIBRARY, thrown CONTEXTING.\n' + '══╡ EXCEPTION CAUGHT BY LIBRARY ╞════════════════════════════════\n' + 'The following Null object was thrown CONTEXTING:\n' ' null\n' - 'INFO', + '\n' + 'INFO\n' + '═════════════════════════════════════════════════════════════════\n', ); expect( FlutterErrorDetails( exception: 'MESSAGE', - context: 'CONTEXTING', - informationCollector: (StringBuffer information) { - information.writeln('INFO'); + context: ErrorDescription('CONTEXTING'), + informationCollector: () sync* { + yield ErrorDescription('INFO'); }, ).toString(), - 'Error caught by Flutter framework, thrown CONTEXTING.\n' + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following message was thrown CONTEXTING:\n' + 'MESSAGE\n' + '\n' + 'INFO\n' + '═════════════════════════════════════════════════════════════════\n' + ); + expect( + FlutterErrorDetails( + exception: 'MESSAGE', + context: ErrorDescription('CONTEXTING ${'SomeContext(BlaBla)'}'), + informationCollector: () sync* { + yield ErrorDescription('INFO'); + }, + ).toString(), + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following message was thrown CONTEXTING SomeContext(BlaBla):\n' 'MESSAGE\n' - 'INFO', + '\n' + 'INFO\n' + '═════════════════════════════════════════════════════════════════\n', ); expect( const FlutterErrorDetails( exception: 'MESSAGE', ).toString(), - 'Error caught by Flutter framework.\n' - 'MESSAGE', + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following message was thrown:\n' + 'MESSAGE\n' + '═════════════════════════════════════════════════════════════════\n' ); expect( const FlutterErrorDetails().toString(), - 'Error caught by Flutter framework.\n' - ' null', + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following Null object was thrown:\n' + ' null\n' + '═════════════════════════════════════════════════════════════════\n' ); }); + + test('FlutterError default constructor', () { + FlutterError error = FlutterError( + 'My Error Summary.\n' + 'My first description.\n' + 'My second description.' + ); + expect(error.diagnostics.length, equals(3)); + expect(error.diagnostics[0].level, DiagnosticLevel.summary); + expect(error.diagnostics[1].level, DiagnosticLevel.info); + expect(error.diagnostics[2].level, DiagnosticLevel.info); + expect(error.diagnostics[0].toString(), 'My Error Summary.'); + expect(error.diagnostics[1].toString(), 'My first description.'); + expect(error.diagnostics[2].toString(), 'My second description.'); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' My Error Summary.\n' + ' My first description.\n' + ' My second description.\n' + ); + + error = FlutterError( + 'My Error Summary.\n' + 'My first description.\n' + 'My second description.\n' + '\n' + ); + + expect(error.diagnostics.length, equals(5)); + expect(error.diagnostics[0].level, DiagnosticLevel.summary); + expect(error.diagnostics[1].level, DiagnosticLevel.info); + expect(error.diagnostics[2].level, DiagnosticLevel.info); + expect(error.diagnostics[0].toString(), 'My Error Summary.'); + expect(error.diagnostics[1].toString(), 'My first description.'); + expect(error.diagnostics[2].toString(), 'My second description.'); + expect(error.diagnostics[3].toString(), ''); + expect(error.diagnostics[4].toString(), ''); + expect( + error.toStringDeep(), + 'FlutterError\n' + ' My Error Summary.\n' + ' My first description.\n' + ' My second description.\n' + '\n' + '\n' + ); + + error = FlutterError( + 'My Error Summary.\n' + 'My first description.\n' + '\n' + 'My second description.' + ); + expect(error.diagnostics.length, equals(4)); + expect(error.diagnostics[0].level, DiagnosticLevel.summary); + expect(error.diagnostics[1].level, DiagnosticLevel.info); + expect(error.diagnostics[2].level, DiagnosticLevel.info); + expect(error.diagnostics[3].level, DiagnosticLevel.info); + expect(error.diagnostics[0].toString(), 'My Error Summary.'); + expect(error.diagnostics[1].toString(), 'My first description.'); + expect(error.diagnostics[2].toString(), ''); + expect(error.diagnostics[3].toString(), 'My second description.'); + + expect( + error.toStringDeep(), + 'FlutterError\n' + ' My Error Summary.\n' + ' My first description.\n' + '\n' + ' My second description.\n' + ); + error = FlutterError('My Error Summary.'); + expect(error.diagnostics.length, 1); + expect(error.diagnostics.first.level, DiagnosticLevel.summary); + expect(error.diagnostics.first.toString(), 'My Error Summary.'); + + expect( + error.toStringDeep(), + 'FlutterError\n' + ' My Error Summary.\n' + ); + }); + + test('Malformed FlutterError objects', () { + { + AssertionError error; + try { + throw FlutterError.fromParts([]); + } on AssertionError catch (e) { + error = e; + } + expect( + FlutterErrorDetails(exception: error).toString(), + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following assertion was thrown:\n' + 'Empty FlutterError\n' + '═════════════════════════════════════════════════════════════════\n', + ); + } + + { + AssertionError error; + try { + throw FlutterError.fromParts([ + (ErrorDescription('Error description without a summary'))]); + } on AssertionError catch (e) { + error = e; + } + expect( + FlutterErrorDetails(exception: error).toString(), + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following assertion was thrown:\n' + 'FlutterError is missing a summary.\n' + 'All FlutterError objects should start with a short (one line)\n' + 'summary description of the problem that was detected.\n' + 'Malformed FlutterError:\n' + ' Error description without a summary\n' + '\n' + 'This error should still help you solve your problem, however\n' + 'please also report this malformed error in the framework by\n' + 'filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md\n' + '═════════════════════════════════════════════════════════════════\n', + ); + } + + { + AssertionError error; + try { + throw FlutterError.fromParts([ + ErrorSummary('Error Summary A'), + ErrorDescription('Some descriptionA'), + ErrorSummary('Error Summary B'), + ErrorDescription('Some descriptionB'), + ]); + } on AssertionError catch (e) { + error = e; + } + expect( + FlutterErrorDetails(exception: error).toString(), + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following assertion was thrown:\n' + 'FlutterError contained multiple error summaries.\n' + 'All FlutterError objects should have only a single short (one\n' + 'line) summary description of the problem that was detected.\n' + 'Malformed FlutterError:\n' + ' Error Summary A\n' + ' Some descriptionA\n' + ' Error Summary B\n' + ' Some descriptionB\n' + '\n' + 'The malformed error has 2 summaries.\n' + 'Summary 1: Error Summary A\n' + 'Summary 2: Error Summary B\n' + '\n' + 'This error should still help you solve your problem, however\n' + 'please also report this malformed error in the framework by\n' + 'filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md\n' + '═════════════════════════════════════════════════════════════════\n', + ); + } + + { + AssertionError error; + try { + throw FlutterError.fromParts([ + ErrorDescription('Some description'), + ErrorSummary('Error summary'), + ]); + } on AssertionError catch (e) { + error = e; + } + expect( + FlutterErrorDetails(exception: error).toString(), + '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' + 'The following assertion was thrown:\n' + 'FlutterError is missing a summary.\n' + 'All FlutterError objects should start with a short (one line)\n' + 'summary description of the problem that was detected.\n' + 'Malformed FlutterError:\n' + ' Some description\n' + ' Error summary\n' + '\n' + 'This error should still help you solve your problem, however\n' + 'please also report this malformed error in the framework by\n' + 'filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=BUG.md\n' + '═════════════════════════════════════════════════════════════════\n', + ); + } + }); } diff --git a/packages/flutter/test/foundation/diagnostics_test.dart b/packages/flutter/test/foundation/diagnostics_test.dart index f39200b81e..27278f2cfe 100644 --- a/packages/flutter/test/foundation/diagnostics_test.dart +++ b/packages/flutter/test/foundation/diagnostics_test.dart @@ -61,16 +61,14 @@ void validateNodeJsonSerialization(DiagnosticsNode node) { void validateNodeJsonSerializationHelper(Map json, DiagnosticsNode node) { expect(json['name'], equals(node.name)); - expect(json['showSeparator'], equals(node.showSeparator)); + expect(json['showSeparator'] ?? true, equals(node.showSeparator)); expect(json['description'], equals(node.toDescription())); - expect(json['level'], equals(describeEnum(node.level))); - expect(json['showName'], equals(node.showName)); + expect(json['level'] ?? describeEnum(DiagnosticLevel.info), equals(describeEnum(node.level))); + expect(json['showName'] ?? true, equals(node.showName)); expect(json['emptyBodyDescription'], equals(node.emptyBodyDescription)); - expect(json['style'], equals(describeEnum(node.style))); - final String valueToString = node is DiagnosticsProperty ? node.valueToString() : node.value.toString(); - expect(json['valueToString'], equals(valueToString)); + expect(json['style'] ?? describeEnum(DiagnosticsTreeStyle.sparse), equals(describeEnum(node.style))); expect(json['type'], equals(node.runtimeType.toString())); - expect(json['hasChildren'], equals(node.getChildren().isNotEmpty)); + expect(json['hasChildren'] ?? false, equals(node.getChildren().isNotEmpty)); } void validatePropertyJsonSerialization(DiagnosticsProperty property) { @@ -169,7 +167,6 @@ void validatePropertyJsonSerializationHelper(final Map json, Dia expect(json.containsKey('exception'), isFalse); } expect(json['propertyType'], equals(property.propertyType.toString())); - expect(json['valueToString'], equals(property.valueToString())); expect(json.containsKey('defaultLevel'), isTrue); if (property.value is Diagnosticable) { expect(json['isDiagnosticableValue'], isTrue); @@ -267,12 +264,28 @@ void main() { ' ╚═══════════\n', ); - // You would never really want to make everything a leaf child like this - // but you can and still get a readable tree. + goldenStyleTest( + 'error children', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.error, + golden: + 'TestTree#00000\n' + ' ├─child node A: TestTree#00000\n' + ' ├─child node B: TestTree#00000\n' + ' │ ├─child node B1: TestTree#00000\n' + ' │ ├─child node B2: TestTree#00000\n' + ' │ ╘═╦══╡ CHILD NODE B3: TESTTREE#00000 ╞═══════════════════════════════\n' + ' │ ╚══════════════════════════════════════════════════════════════════\n' + ' ╘═╦══╡ CHILD NODE C: TESTTREE#00000 ╞════════════════════════════════\n' + ' ╚══════════════════════════════════════════════════════════════════\n', + ); + + // You would never really want to make everything a transition child like + // this but you can and still get a readable tree. // The joint between single and double lines here is a bit clunky // but we could correct that if there is any real use for this style. goldenStyleTest( - 'leaf', + 'transition', style: DiagnosticsTreeStyle.transition, golden: 'TestTree#00000:\n' @@ -296,6 +309,26 @@ void main() { ' ╚═══════════\n', ); + goldenStyleTest( + 'error', + style: DiagnosticsTreeStyle.error, + golden: + '══╡ TESTTREE#00000 ╞═════════════════════════════════════════════\n' + '╞═╦══╡ CHILD NODE A: TESTTREE#00000 ╞════════════════════════════════\n' + '│ ╚══════════════════════════════════════════════════════════════════\n' + '╞═╦══╡ CHILD NODE B: TESTTREE#00000 ╞════════════════════════════════\n' + '│ ║ ╞═╦══╡ CHILD NODE B1: TESTTREE#00000 ╞═══════════════════════════════\n' + '│ ║ │ ╚══════════════════════════════════════════════════════════════════\n' + '│ ║ ╞═╦══╡ CHILD NODE B2: TESTTREE#00000 ╞═══════════════════════════════\n' + '│ ║ │ ╚══════════════════════════════════════════════════════════════════\n' + '│ ║ ╘═╦══╡ CHILD NODE B3: TESTTREE#00000 ╞═══════════════════════════════\n' + '│ ║ ╚══════════════════════════════════════════════════════════════════\n' + '│ ╚══════════════════════════════════════════════════════════════════\n' + '╘═╦══╡ CHILD NODE C: TESTTREE#00000 ╞════════════════════════════════\n' + ' ╚══════════════════════════════════════════════════════════════════\n' + '═════════════════════════════════════════════════════════════════\n', + ); + goldenStyleTest( 'whitespace', style: DiagnosticsTreeStyle.whitespace, @@ -320,40 +353,42 @@ void main() { test('TreeDiagnosticsMixin tree with properties test', () async { void goldenStyleTest( String description, { + String name, DiagnosticsTreeStyle style, DiagnosticsTreeStyle lastChildStyle, + DiagnosticsTreeStyle propertyStyle = DiagnosticsTreeStyle.singleLine, @required String golden, }) { final TestTree tree = TestTree( properties: [ - StringProperty('stringProperty1', 'value1', quoted: false), - DoubleProperty('doubleProperty1', 42.5), - DoubleProperty('roundedProperty', 1.0 / 3.0), - StringProperty('DO_NOT_SHOW', 'DO_NOT_SHOW', level: DiagnosticLevel.hidden, quoted: false), - DiagnosticsProperty('DO_NOT_SHOW_NULL', null, defaultValue: null), - DiagnosticsProperty('nullProperty', null), - StringProperty('node_type', '', showName: false, quoted: false), + StringProperty('stringProperty1', 'value1', quoted: false, style: propertyStyle), + DoubleProperty('doubleProperty1', 42.5, style: propertyStyle), + DoubleProperty('roundedProperty', 1.0 / 3.0, style: propertyStyle), + StringProperty('DO_NOT_SHOW', 'DO_NOT_SHOW', level: DiagnosticLevel.hidden, quoted: false, style: propertyStyle), + DiagnosticsProperty('DO_NOT_SHOW_NULL', null, defaultValue: null, style: propertyStyle), + DiagnosticsProperty('nullProperty', null, style: propertyStyle), + StringProperty('node_type', '', showName: false, quoted: false, style: propertyStyle), ], children: [ TestTree(name: 'node A', style: style), TestTree( name: 'node B', properties: [ - StringProperty('p1', 'v1', quoted: false), - StringProperty('p2', 'v2', quoted: false), + StringProperty('p1', 'v1', quoted: false, style: propertyStyle), + StringProperty('p2', 'v2', quoted: false, style: propertyStyle), ], children: [ TestTree(name: 'node B1', style: style), TestTree( name: 'node B2', - properties: [StringProperty('property1', 'value1', quoted: false)], + properties: [StringProperty('property1', 'value1', quoted: false, style: propertyStyle)], style: style, ), TestTree( name: 'node B3', properties: [ - StringProperty('node_type', '', showName: false, quoted: false), - IntProperty('foo', 42), + StringProperty('node_type', '', showName: false, quoted: false, style: propertyStyle), + IntProperty('foo', 42, style: propertyStyle), ], style: lastChildStyle ?? style, ), @@ -363,7 +398,7 @@ void main() { TestTree( name: 'node C', properties: [ - StringProperty('foo', 'multi\nline\nvalue!', quoted: false), + StringProperty('foo', 'multi\nline\nvalue!', quoted: false, style: propertyStyle), ], style: lastChildStyle ?? style, ), @@ -371,11 +406,13 @@ void main() { style: lastChildStyle, ); - if (tree.style != DiagnosticsTreeStyle.singleLine) + if (tree.style != DiagnosticsTreeStyle.singleLine && + tree.style != DiagnosticsTreeStyle.errorProperty) { expect(tree, hasAGoodToStringDeep); + } expect( - tree.toDiagnosticsNode(style: style).toStringDeep(), + tree.toDiagnosticsNode(name: name, style: style).toStringDeep(), equalsIgnoringHashCodes(golden), reason: description, ); @@ -413,6 +450,45 @@ void main() { ' value!\n', ); + goldenStyleTest( + 'sparse with indented single line properties', + style: DiagnosticsTreeStyle.sparse, + propertyStyle: DiagnosticsTreeStyle.errorProperty, + golden: + 'TestTree#00000\n' + ' │ stringProperty1:\n' + ' │ value1\n' + ' │ doubleProperty1:\n' + ' │ 42.5\n' + ' │ roundedProperty:\n' + ' │ 0.3\n' + ' │ nullProperty:\n' + ' │ null\n' + ' │ \n' + ' │\n' + ' ├─child node A: TestTree#00000\n' + ' ├─child node B: TestTree#00000\n' + ' │ │ p1:\n' + ' │ │ v1\n' + ' │ │ p2:\n' + ' │ │ v2\n' + ' │ │\n' + ' │ ├─child node B1: TestTree#00000\n' + ' │ ├─child node B2: TestTree#00000\n' + ' │ │ property1:\n' + ' │ │ value1\n' + ' │ │\n' + ' │ └─child node B3: TestTree#00000\n' + ' │ \n' + ' │ foo: 42\n' + ' │\n' + ' └─child node C: TestTree#00000\n' + ' foo:\n' + ' multi\n' + ' line\n' + ' value!\n', + ); + goldenStyleTest( 'dense', style: DiagnosticsTreeStyle.dense, @@ -458,7 +534,7 @@ void main() { ); goldenStyleTest( - 'leaf children', + 'transition children', style: DiagnosticsTreeStyle.sparse, lastChildStyle: DiagnosticsTreeStyle.transition, golden: @@ -492,6 +568,40 @@ void main() { ' ╚═══════════\n', ); + goldenStyleTest( + 'error children', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.error, + golden: + 'TestTree#00000\n' + ' │ stringProperty1: value1\n' + ' │ doubleProperty1: 42.5\n' + ' │ roundedProperty: 0.3\n' + ' │ nullProperty: null\n' + ' │ \n' + ' │\n' + ' ├─child node A: TestTree#00000\n' + ' ├─child node B: TestTree#00000\n' + ' │ │ p1: v1\n' + ' │ │ p2: v2\n' + ' │ │\n' + ' │ ├─child node B1: TestTree#00000\n' + ' │ ├─child node B2: TestTree#00000\n' + ' │ │ property1: value1\n' + ' │ │\n' + ' │ ╘═╦══╡ CHILD NODE B3: TESTTREE#00000 ╞═══════════════════════════════\n' + ' │ ║ \n' + ' │ ║ foo: 42\n' + ' │ ╚══════════════════════════════════════════════════════════════════\n' + ' ╘═╦══╡ CHILD NODE C: TESTTREE#00000 ╞════════════════════════════════\n' + ' ║ foo:\n' + ' ║ multi\n' + ' ║ line\n' + ' ║ value!\n' + ' ╚══════════════════════════════════════════════════════════════════\n', + ); + + // You would never really want to make everything a transition child like // this but you can and still get a readable tree. goldenStyleTest( @@ -560,6 +670,32 @@ void main() { ' value!\n', ); + goldenStyleTest( + 'flat', + style: DiagnosticsTreeStyle.flat, + golden: + 'TestTree#00000:\n' + 'stringProperty1: value1\n' + 'doubleProperty1: 42.5\n' + 'roundedProperty: 0.3\n' + 'nullProperty: null\n' + '\n' + 'child node A: TestTree#00000\n' + 'child node B: TestTree#00000:\n' + 'p1: v1\n' + 'p2: v2\n' + 'child node B1: TestTree#00000\n' + 'child node B2: TestTree#00000:\n' + 'property1: value1\n' + 'child node B3: TestTree#00000:\n' + '\n' + 'foo: 42\n' + 'child node C: TestTree#00000:\n' + 'foo:\n' + ' multi\n' + ' line\n' + ' value!\n', + ); // Single line mode does not display children. goldenStyleTest( 'single line', @@ -567,10 +703,33 @@ void main() { golden: 'TestTree#00000(stringProperty1: value1, doubleProperty1: 42.5, roundedProperty: 0.3, nullProperty: null, )', ); + goldenStyleTest( + 'single line', + name: 'some name', + style: DiagnosticsTreeStyle.singleLine, + golden: 'some name: TestTree#00000(stringProperty1: value1, doubleProperty1: 42.5, roundedProperty: 0.3, nullProperty: null, )', + ); + + // No name so we don't indent. + goldenStyleTest( + 'indented single line', + style: DiagnosticsTreeStyle.errorProperty, + golden: 'TestTree#00000(stringProperty1: value1, doubleProperty1: 42.5, roundedProperty: 0.3, nullProperty: null, )\n', + ); + + goldenStyleTest( + 'indented single line', + name: 'some name', + style: DiagnosticsTreeStyle.errorProperty, + golden: + 'some name:\n' + ' TestTree#00000(stringProperty1: value1, doubleProperty1: 42.5, roundedProperty: 0.3, nullProperty: null, )\n', + ); + // TODO(jacobr): this is an ugly test case. // There isn't anything interesting for this case as the children look the - // same with and without children. Only difference is odd not clearly - // desirable density of B3 being right next to node C. + // same with and without children. Only difference is the odd and + // undesirable density of B3 being right next to node C. goldenStyleTest( 'single line last child', style: DiagnosticsTreeStyle.sparse, @@ -595,6 +754,40 @@ void main() { ' │ └─child node B3: TestTree#00000(, foo: 42)\n' ' └─child node C: TestTree#00000(foo: multi\\nline\\nvalue!)\n', ); + + // TODO(jacobr): this is an ugly test case. + // There isn't anything interesting for this case as the children look the + // same with and without children. Only difference is the odd and + // undesirable density of B3 being right next to node C. + // Typically header lines should not be places as leaves in the tree and + // should instead be places in front of other nodes that they + // function as a header for. + goldenStyleTest( + 'indented single line last child', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.errorProperty, + golden: + 'TestTree#00000\n' + ' │ stringProperty1: value1\n' + ' │ doubleProperty1: 42.5\n' + ' │ roundedProperty: 0.3\n' + ' │ nullProperty: null\n' + ' │ \n' + ' │\n' + ' ├─child node A: TestTree#00000\n' + ' ├─child node B: TestTree#00000\n' + ' │ │ p1: v1\n' + ' │ │ p2: v2\n' + ' │ │\n' + ' │ ├─child node B1: TestTree#00000\n' + ' │ ├─child node B2: TestTree#00000\n' + ' │ │ property1: value1\n' + ' │ │\n' + ' │ └─child node B3:\n' + ' │ TestTree#00000(, foo: 42)\n' + ' └─child node C:\n' + ' TestTree#00000(foo: multi\\nline\\nvalue!)\n', + ); }); test('transition test', () { @@ -868,7 +1061,7 @@ void main() { final DoubleProperty throwingProperty = DoubleProperty.lazy( 'name', - () => throw FlutterError('Invalid constraints'), + () => throw FlutterError.fromParts([ErrorSummary('Invalid constraints')]), ); // TODO(jacobr): it would be better if throwingProperty.object threw an // exception. @@ -1312,7 +1505,7 @@ void main() { final DiagnosticsProperty throwingWithDescription = DiagnosticsProperty.lazy( 'name', - () => throw FlutterError('Property not available'), + () => throw FlutterError.fromParts([ErrorSummary('Property not available')]), description: 'missing', defaultValue: null, ); @@ -1324,7 +1517,7 @@ void main() { final DiagnosticsProperty throwingProperty = DiagnosticsProperty.lazy( 'name', - () => throw FlutterError('Property not available'), + () => throw FlutterError.fromParts([ErrorSummary('Property not available')]), defaultValue: null, ); expect(throwingProperty.value, isNull); @@ -1542,6 +1735,34 @@ void main() { ); }); + test('Stack trace test', () { + final StackTrace stack = StackTrace.fromString( + '#0 someMethod() file:///diagnostics_test.dart:42:19\n' + '#1 someMethod2() file:///diagnostics_test.dart:12:3\n' + '#2 someMethod3() file:///foo.dart:4:1\n' + ); + + expect( + DiagnosticsStackTrace('Stack trace', stack).toStringDeep(), + equalsIgnoringHashCodes( + 'Stack trace:\n' + '#0 someMethod() file:///diagnostics_test.dart:42:19\n' + '#1 someMethod2() file:///diagnostics_test.dart:12:3\n' + '#2 someMethod3() file:///foo.dart:4:1\n' + ) + ); + + expect( + DiagnosticsStackTrace('-- callback 2 --', stack, showSeparator: false).toStringDeep(), + equalsIgnoringHashCodes( + '-- callback 2 --\n' + '#0 someMethod() file:///diagnostics_test.dart:42:19\n' + '#1 someMethod2() file:///diagnostics_test.dart:12:3\n' + '#2 someMethod3() file:///foo.dart:4:1\n' + ) + ); + }); + test('message test', () { final DiagnosticsNode message = DiagnosticsNode.message('hello world'); expect(message.toString(), equals('hello world')); @@ -1557,4 +1778,324 @@ void main() { expect(messageProperty.showName, isTrue); validatePropertyJsonSerialization(messageProperty); }); + + test('error message style wrap test', () { + // This tests wrapping of properties with styles typical for error messages. + DiagnosticsNode createTreeWithWrappingNodes({ + DiagnosticsTreeStyle rootStyle, + DiagnosticsTreeStyle propertyStyle, + }) { + return TestTree( + name: 'Test tree', + properties: [ + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsNode.message( + 'This is a very long message that must wrap as it cannot fit on one line. ' + 'This is a very long message that must wrap as it cannot fit on one line. ' + 'This is a very long message that must wrap as it cannot fit on one line.', + style: propertyStyle, + ), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsProperty(null, + 'Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap.', + allowWrap: false), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsNode.message( + 'This property has a very long property name that will be allowed to wrap unlike most property names. This property has a very long property name that will be allowed to wrap unlike most property names:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html', + style: propertyStyle, + ), + DiagnosticsNode.message( + 'This property has a very long property name that will be allowed to wrap unlike most property names. This property has a very long property name that will be allowed to wrap unlike most property names:\n' + ' https://goo.gl/', + style: propertyStyle, + ), + DiagnosticsNode.message( + 'Click on the following url:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html', + style: propertyStyle, + ), + DiagnosticsNode.message( + 'Click on the following url\n' + ' https://goo.gl/', + style: propertyStyle, + ), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsProperty( + 'multi-line value', + '[1.0, 0.0, 0.0, 0.0]\n' + '[1.0, 1.0, 0.0, 0.0]\n' + '[1.0, 0.0, 1.0, 0.0]\n' + '[1.0, 0.0, 0.0, 1.0]\n', + style: propertyStyle, + ), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsProperty( + 'This property has a very long property name that will be allowed to wrap unlike most property names. This property has a very long property name that will be allowed to wrap unlike most property names', + 'This is a very long message that must wrap as it cannot fit on one line. ' + 'This is a very long message that must wrap as it cannot fit on one line. ' + 'This is a very long message that must wrap as it cannot fit on one line.', + style: propertyStyle, + ), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + DiagnosticsProperty( + 'This property has a very long property name that will be allowed to wrap unlike most property names. This property has a very long property name that will be allowed to wrap unlike most property names', + '[1.0, 0.0, 0.0, 0.0]\n' + '[1.0, 1.0, 0.0, 0.0]\n' + '[1.0, 0.0, 1.0, 0.0]\n' + '[1.0, 0.0, 0.0, 1.0]\n', + style: propertyStyle, + ), + DiagnosticsNode.message( + '--- example property at max length --', + style: propertyStyle, + ), + MessageProperty( + 'diagnosis', + 'insufficient data to draw conclusion (less than five repaints)', + style: propertyStyle, + ), + ], + ).toDiagnosticsNode(style: rootStyle); + } + + final TextTreeRenderer renderer = TextTreeRenderer(wrapWidth: 40, wrapWidthProperties: 40); + expect( + renderer.render(createTreeWithWrappingNodes( + rootStyle: DiagnosticsTreeStyle.error, + propertyStyle: DiagnosticsTreeStyle.singleLine, + )), + equalsIgnoringHashCodes( + '══╡ TESTTREE#00000 ╞════════════════════\n' + '--- example property at max length --\n' + 'This is a very long message that must\n' + 'wrap as it cannot fit on one line. This\n' + 'is a very long message that must wrap as\n' + 'it cannot fit on one line. This is a\n' + 'very long message that must wrap as it\n' + 'cannot fit on one line.\n' + '--- example property at max length --\n' + 'Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap.\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' https://goo.gl/\n' + 'Click on the following url:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + 'Click on the following url\n' + ' https://goo.gl/\n' + '--- example property at max length --\n' + 'multi-line value:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + '--- example property at max length --\n' + 'diagnosis: insufficient data to draw\n' + ' conclusion (less than five repaints)\n' + '════════════════════════════════════════\n', + ) + ); + + // This output looks ugly but verifies that no indentation on word wrap + // leaks in if the style is flat. + expect( + renderer.render(createTreeWithWrappingNodes( + rootStyle: DiagnosticsTreeStyle.sparse, + propertyStyle: DiagnosticsTreeStyle.flat, + )), + equalsIgnoringHashCodes( + 'TestTree#00000\n' + ' --- example property at max length --\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line. This\n' + ' is a very long message that must wrap as\n' + ' it cannot fit on one line. This is a\n' + ' very long message that must wrap as it\n' + ' cannot fit on one line.\n' + ' --- example property at max length --\n' + ' Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap.\n' + ' --- example property at max length --\n' + ' This property has a very long property\n' + ' name that will be allowed to wrap unlike\n' + ' most property names. This property has a\n' + ' very long property name that will be\n' + ' allowed to wrap unlike most property\n' + ' names:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + ' This property has a very long property\n' + ' name that will be allowed to wrap unlike\n' + ' most property names. This property has a\n' + ' very long property name that will be\n' + ' allowed to wrap unlike most property\n' + ' names:\n' + ' https://goo.gl/\n' + ' Click on the following url:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + ' Click on the following url\n' + ' https://goo.gl/\n' + ' --- example property at max length --\n' + ' multi-line value:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + ' --- example property at max length --\n' + ' This property has a very long property\n' + ' name that will be allowed to wrap unlike\n' + ' most property names. This property has a\n' + ' very long property name that will be\n' + ' allowed to wrap unlike most property\n' + ' names:\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line. This\n' + ' is a very long message that must wrap as\n' + ' it cannot fit on one line. This is a\n' + ' very long message that must wrap as it\n' + ' cannot fit on one line.\n' + ' --- example property at max length --\n' + ' This property has a very long property\n' + ' name that will be allowed to wrap unlike\n' + ' most property names. This property has a\n' + ' very long property name that will be\n' + ' allowed to wrap unlike most property\n' + ' names:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + ' --- example property at max length --\n' + ' diagnosis: insufficient data to draw\n' + ' conclusion (less than five repaints)\n' + ) + ); + + // This case matches the styles that should generally be used for error + // messages + expect( + renderer.render(createTreeWithWrappingNodes( + rootStyle: DiagnosticsTreeStyle.error, + propertyStyle: DiagnosticsTreeStyle.errorProperty, + )), + equalsIgnoringHashCodes( + '══╡ TESTTREE#00000 ╞════════════════════\n' + '--- example property at max length --\n' + 'This is a very long message that must\n' + 'wrap as it cannot fit on one line. This\n' + 'is a very long message that must wrap as\n' + 'it cannot fit on one line. This is a\n' + 'very long message that must wrap as it\n' + 'cannot fit on one line.\n' + '--- example property at max length --\n' + 'Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap even though it is very long. Message that is not allowed to wrap.\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' https://goo.gl/\n' + 'Click on the following url:\n' + ' http://someverylongurl.com/that-might-be-tempting-to-wrap-even-though-it-is-a-url-so-should-not-wrap.html\n' + 'Click on the following url\n' + ' https://goo.gl/\n' + '--- example property at max length --\n' + 'multi-line value:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + ' This is a very long message that must\n' + ' wrap as it cannot fit on one line.\n' + '--- example property at max length --\n' + 'This property has a very long property\n' + 'name that will be allowed to wrap unlike\n' + 'most property names. This property has a\n' + 'very long property name that will be\n' + 'allowed to wrap unlike most property\n' + 'names:\n' + ' [1.0, 0.0, 0.0, 0.0]\n' + ' [1.0, 1.0, 0.0, 0.0]\n' + ' [1.0, 0.0, 1.0, 0.0]\n' + ' [1.0, 0.0, 0.0, 1.0]\n' + '--- example property at max length --\n' + 'diagnosis:\n' + ' insufficient data to draw conclusion\n' + ' (less than five repaints)\n' + '════════════════════════════════════════\n' + ) + ); + }); } diff --git a/packages/flutter/test/foundation/error_reporting_test.dart b/packages/flutter/test/foundation/error_reporting_test.dart index d0d97d9329..113105a45a 100644 --- a/packages/flutter/test/foundation/error_reporting_test.dart +++ b/packages/flutter/test/foundation/error_reporting_test.dart @@ -56,19 +56,20 @@ Future main() async { exception: getAssertionErrorWithMessage(), stack: sampleStack, library: 'error handling test', - context: 'testing the error handling logic', - informationCollector: (StringBuffer information) { - information.writeln('line 1 of extra information'); - information.writeln('line 2 of extra information\n'); // the double trailing newlines here are intentional + context: ErrorDescription('testing the error handling logic'), + informationCollector: () sync* { + yield ErrorDescription('line 1 of extra information'); + yield ErrorHint('line 2 of extra information\n'); }, )); expect(console.join('\n'), matches( '^══╡ EXCEPTION CAUGHT BY ERROR HANDLING TEST ╞═══════════════════════════════════════════════════════\n' 'The following assertion was thrown testing the error handling logic:\n' 'Message goes here\\.\n' - '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\': Failed assertion: line [0-9]+ pos [0-9]+: \'false\'\n' + '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\':\n' + 'Failed assertion: line [0-9]+ pos [0-9]+: \'false\'\n' '\n' - 'Either the assertion indicates an error in the framework itself, or we should provide substantially ' + 'Either the assertion indicates an error in the framework itself, or we should provide substantially\n' 'more information in this error message to help you determine and fix the underlying cause\\.\n' 'In either case, please report this assertion by filing a bug on GitHub:\n' ' https://github\\.com/flutter/flutter/issues/new\\?template=BUG\\.md\n' @@ -102,14 +103,15 @@ Future main() async { expect(console.join('\n'), matches( '^══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════\n' 'The following assertion was thrown:\n' - 'word word word word word word word word word word word word word word word word word word word word ' - 'word word word word word word word word word word word word word word word word word word word word ' - 'word word word word word word word word word word word word word word word word word word word word ' - 'word word word word word word word word word word word word word word word word word word word word ' 'word word word word word word word word word word word word word word word word word word word word\n' - '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\': Failed assertion: line [0-9]+ pos [0-9]+: \'false\'\n' + 'word word word word word word word word word word word word word word word word word word word word\n' + 'word word word word word word word word word word word word word word word word word word word word\n' + 'word word word word word word word word word word word word word word word word word word word word\n' + 'word word word word word word word word word word word word word word word word word word word word\n' + '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\':\n' + 'Failed assertion: line [0-9]+ pos [0-9]+: \'false\'\n' '\n' - 'Either the assertion indicates an error in the framework itself, or we should provide substantially ' + 'Either the assertion indicates an error in the framework itself, or we should provide substantially\n' 'more information in this error message to help you determine and fix the underlying cause\\.\n' 'In either case, please report this assertion by filing a bug on GitHub:\n' ' https://github\\.com/flutter/flutter/issues/new\\?template=BUG\\.md\n' @@ -138,18 +140,19 @@ Future main() async { exception: getAssertionErrorWithoutMessage(), stack: sampleStack, library: 'error handling test', - context: 'testing the error handling logic', - informationCollector: (StringBuffer information) { - information.writeln('line 1 of extra information'); - information.writeln('line 2 of extra information\n'); // the double trailing newlines here are intentional - }, + context: ErrorDescription('testing the error handling logic'), + informationCollector: () sync* { + yield ErrorDescription('line 1 of extra information'); + yield ErrorDescription('line 2 of extra information\n'); // the trailing newlines here are intentional + } )); expect(console.join('\n'), matches( '^══╡ EXCEPTION CAUGHT BY ERROR HANDLING TEST ╞═══════════════════════════════════════════════════════\n' 'The following assertion was thrown testing the error handling logic:\n' - '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\': Failed assertion: line [0-9]+ pos [0-9]+: \'false\': is not true\\.\n' + '\'[^\']+flutter/test/foundation/error_reporting_test\\.dart\':[\n ]' + 'Failed[\n ]assertion:[\n ]line[\n ][0-9]+[\n ]pos[\n ][0-9]+:[\n ]\'false\':[\n ]is[\n ]not[\n ]true\\.\n' '\n' - 'Either the assertion indicates an error in the framework itself, or we should provide substantially ' + 'Either the assertion indicates an error in the framework itself, or we should provide substantially\n' 'more information in this error message to help you determine and fix the underlying cause\\.\n' 'In either case, please report this assertion by filing a bug on GitHub:\n' ' https://github\\.com/flutter/flutter/issues/new\\?template=BUG\\.md\n' diff --git a/packages/flutter/test/foundation/service_extensions_test.dart b/packages/flutter/test/foundation/service_extensions_test.dart index 9edf792c37..2970d198a9 100644 --- a/packages/flutter/test/foundation/service_extensions_test.dart +++ b/packages/flutter/test/foundation/service_extensions_test.dart @@ -145,7 +145,7 @@ void main() { tearDownAll(() async { // See widget_inspector_test.dart for tests of the ext.flutter.inspector // service extensions included in this count. - int widgetInspectorExtensionCount = 15; + int widgetInspectorExtensionCount = 16; if (WidgetInspectorService.instance.isWidgetCreationTracked()) { // Some inspector extensions are only exposed if widget creation locations // are tracked. diff --git a/packages/flutter/test/material/paginated_data_table_test.dart b/packages/flutter/test/material/paginated_data_table_test.dart index b7ae49d211..bc9211e055 100644 --- a/packages/flutter/test/material/paginated_data_table_test.dart +++ b/packages/flutter/test/material/paginated_data_table_test.dart @@ -153,7 +153,10 @@ void main() { )); // the column overflows because we're forcing it to 600 pixels high - expect(tester.takeException(), contains('A RenderFlex overflowed by')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by ')); expect(find.text('Gingerbread (0)'), findsOneWidget); expect(find.text('Gingerbread (1)'), findsNothing); @@ -238,7 +241,11 @@ void main() { ), )); // the column overflows because we're forcing it to 600 pixels high - expect(tester.takeException(), contains('A RenderFlex overflowed by')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), contains('A RenderFlex overflowed by')); + expect(find.text('Rows per page:'), findsOneWidget); // Test that we will show some options in the drop down even if the lowest option is bigger than the source: assert(501 > source.rowCount); diff --git a/packages/flutter/test/rendering/debug_overflow_indicator_test.dart b/packages/flutter/test/rendering/debug_overflow_indicator_test.dart index 9fccaba823..43a1b5b47b 100644 --- a/packages/flutter/test/rendering/debug_overflow_indicator_test.dart +++ b/packages/flutter/test/rendering/debug_overflow_indicator_test.dart @@ -33,7 +33,10 @@ void main() { ), ); - expect(tester.takeException(), contains('A RenderUnconstrainedBox overflowed by')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), startsWith('A RenderUnconstrainedBox overflowed by ')); expect(find.byType(UnconstrainedBox), paints..rect()); await tester.pumpWidget( diff --git a/packages/flutter/test/widgets/global_keys_duplicated_test.dart b/packages/flutter/test/widgets/global_keys_duplicated_test.dart index 1350b35c00..57c54a4b41 100644 --- a/packages/flutter/test/widgets/global_keys_duplicated_test.dart +++ b/packages/flutter/test/widgets/global_keys_duplicated_test.dart @@ -82,7 +82,7 @@ void main() { expect(error.toString(), contains('The following GlobalKey was specified multiple times')); // The following line is verifying the grammar is correct in this common case. // We should probably also verify the three other combinations that can be generated... - expect(error.toString(), contains('This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.')); + expect(error.toString().split('\n').join(' '), contains('This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.')); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); expect(error.toString(), contains('Container')); expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); diff --git a/packages/flutter/test/widgets/physical_model_test.dart b/packages/flutter/test/widgets/physical_model_test.dart index 31736f6ae8..fb6c7f49ec 100644 --- a/packages/flutter/test/widgets/physical_model_test.dart +++ b/packages/flutter/test/widgets/physical_model_test.dart @@ -105,7 +105,10 @@ void main() { ), ); - expect(tester.takeException(), startsWith('A RenderFlex overflowed by ')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by ')); await expectLater( find.byKey(key), matchesGoldenFile('physical_model_overflow.png'), diff --git a/packages/flutter/test/widgets/semantics_clipping_test.dart b/packages/flutter/test/widgets/semantics_clipping_test.dart index 7f7e0dea4d..4820155783 100644 --- a/packages/flutter/test/widgets/semantics_clipping_test.dart +++ b/packages/flutter/test/widgets/semantics_clipping_test.dart @@ -39,7 +39,10 @@ void main() { ), )); - expect(tester.takeException(), contains('overflowed')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), contains('overflowed')); expect(semantics, hasSemantics( TestSemantics.root( @@ -98,7 +101,10 @@ void main() { ), )); - expect(tester.takeException(), contains('overflowed')); + final dynamic exception = tester.takeException(); + expect(exception, isInstanceOf()); + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + expect(exception.diagnostics.first.toString(), contains('overflowed')); expect(semantics, hasSemantics( TestSemantics.root( diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index cd1b233637..85c60bcf24 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -501,7 +501,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: exception, stack: _unmangle(stack), - context: 'running a test (but after the test had completed)', + context: ErrorDescription('running a test (but after the test had completed)'), library: 'Flutter test framework', ), forceReport: true); return; @@ -534,31 +534,33 @@ abstract class TestWidgetsFlutterBinding extends BindingBase // _this_ zone, the test framework would find this zone was the current // zone and helpfully throw the error in this zone, causing us to be // directly called again. - String treeDump; + DiagnosticsNode treeDump; try { - treeDump = renderViewElement?.toStringDeep() ?? ''; + treeDump = renderViewElement?.toDiagnosticsNode() ?? DiagnosticsNode.message(''); + // TODO(jacobr): this is a hack to make sure the tree can safely be fully dumped. + // Potentially everything is good enough without this case. + treeDump.toStringDeep(); } catch (exception) { - treeDump = ''; + treeDump = DiagnosticsNode.message('', level: DiagnosticLevel.error); } - final StringBuffer expectLine = StringBuffer(); - final int stackLinesToOmit = reportExpectCall(stack, expectLine); + final List omittedFrames = []; + final int stackLinesToOmit = reportExpectCall(stack, omittedFrames); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: _unmangle(stack), - context: 'running a test', + context: ErrorDescription('running a test'), library: 'Flutter test framework', stackFilter: (Iterable frames) { return FlutterError.defaultStackFilter(frames.skip(stackLinesToOmit)); }, - informationCollector: (StringBuffer information) { + informationCollector: () sync* { if (stackLinesToOmit > 0) - information.writeln(expectLine.toString()); + yield* omittedFrames; if (showAppDumpInErrors) { - information.writeln('At the time of the failure, the widget tree looked as follows:'); - information.writeln('# ${treeDump.split("\n").takeWhile((String s) => s != "").join("\n# ")}'); + yield DiagnosticsProperty('At the time of the failure, the widget tree looked as follows', treeDump, linePrefix: '# ', style: DiagnosticsTreeStyle.flat); } if (description.isNotEmpty) - information.writeln('The test description was:\n$description'); + yield DiagnosticsProperty('The test description was', description, style: DiagnosticsTreeStyle.errorProperty); }, )); assert(_parentZone != null); @@ -847,7 +849,7 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { exception: exception, stack: stack, library: 'Flutter test framework', - context: 'while running async test code', + context: ErrorDescription('while running async test code'), )); return null; }).whenComplete(() { @@ -1335,7 +1337,7 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { exception: error, stack: stack, library: 'Flutter test framework', - context: 'while running async test code', + context: ErrorSummary('while running async test code'), )); return null; } finally { diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart index 098d4c8562..3a1482f8e6 100644 --- a/packages/flutter_test/lib/src/matchers.dart +++ b/packages/flutter_test/lib/src/matchers.dart @@ -754,7 +754,7 @@ class _EqualsIgnoringHashCodes extends Matcher { static final Object _mismatchedValueKey = Object(); static String _normalize(String s) { - return s.replaceAll(RegExp(r'#[0-9a-f]{5}'), '#00000'); + return s.replaceAll(RegExp(r'#[0-9a-fA-F]{5}'), '#00000'); } @override diff --git a/packages/flutter_test/lib/src/stack_manipulation.dart b/packages/flutter_test/lib/src/stack_manipulation.dart index c07f3c49b3..0a7e16cb1e 100644 --- a/packages/flutter_test/lib/src/stack_manipulation.dart +++ b/packages/flutter_test/lib/src/stack_manipulation.dart @@ -4,14 +4,17 @@ // See also test_async_utils.dart which has some stack manipulation code. +import 'package:flutter/foundation.dart'; + /// Report call site for `expect()` call. Returns the number of frames that /// should be elided if a stack were to be modified to hide the expect call, or /// zero if no such call was found. /// /// If the head of the stack trace consists of a failure as a result of calling -/// the test_widgets [expect] function, this will fill the given StringBuffer -/// with the precise file and line number that called that function. -int reportExpectCall(StackTrace stack, StringBuffer information) { +/// the test_widgets [expect] function, this will fill the given +/// FlutterErrorBuilder with the precise file and line number that called that +/// function. +int reportExpectCall(StackTrace stack, List information) { final RegExp line0 = RegExp(r'^#0 +fail \(.+\)$'); final RegExp line1 = RegExp(r'^#1 +_expect \(.+\)$'); final RegExp line2 = RegExp(r'^#2 +expect \(.+\)$'); @@ -25,8 +28,11 @@ int reportExpectCall(StackTrace stack, StringBuffer information) { final Match expectMatch = line4.firstMatch(stackLines[4]); assert(expectMatch != null); assert(expectMatch.groupCount == 2); - information.writeln('This was caught by the test expectation on the following line:'); - information.writeln(' ${expectMatch.group(1)} line ${expectMatch.group(2)}'); + information.add(DiagnosticsStackTrace.singleFrame( + 'This was caught by the test expectation on the following line', + frame: '${expectMatch.group(1)} line ${expectMatch.group(2)}', + )); + return 4; } return 0; diff --git a/packages/flutter_test/lib/src/test_async_utils.dart b/packages/flutter_test/lib/src/test_async_utils.dart index 317ba9b9e0..36fe871d80 100644 --- a/packages/flutter_test/lib/src/test_async_utils.dart +++ b/packages/flutter_test/lib/src/test_async_utils.dart @@ -73,34 +73,37 @@ class TestAsyncUtils { assert(_scopeStack.contains(scope)); bool leaked = false; _AsyncScope closedScope; - final StringBuffer message = StringBuffer(); + final List information = []; while (_scopeStack.isNotEmpty) { closedScope = _scopeStack.removeLast(); if (closedScope == scope) break; if (!leaked) { - message.writeln('Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.'); + information.add(ErrorSummary('Asynchronous call to guarded function leaked.')); + information.add(ErrorHint('You must use "await" with all Future-returning test APIs.')); leaked = true; } - final _StackEntry originalGuarder = _findResponsibleMethod(closedScope.creationStack, 'guard', message); + final _StackEntry originalGuarder = _findResponsibleMethod(closedScope.creationStack, 'guard', information); if (originalGuarder != null) { - message.writeln( + information.add(ErrorDescription( 'The test API method "${originalGuarder.methodName}" ' 'from class ${originalGuarder.className} ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}, ' 'but never completed before its parent scope closed.' - ); + )); } } if (leaked) { if (error != null) { - message.writeln('An uncaught exception may have caused the guarded function leak. The exception was:'); - message.writeln('$error'); - message.writeln('The stack trace associated with this exception was:'); - FlutterError.defaultStackFilter(stack.toString().trimRight().split('\n')).forEach(message.writeln); + information.add(DiagnosticsProperty( + 'An uncaught exception may have caused the guarded function leak. The exception was', + error, + style: DiagnosticsTreeStyle.errorProperty, + )); + information.add(DiagnosticsStackTrace('The stack trace associated with this exception was', stack)); } - throw FlutterError(message.toString().trimRight()); + throw FlutterError.fromParts(information); } if (error != null) return Future.error(error, stack); @@ -182,27 +185,28 @@ class TestAsyncUtils { assert(candidateScope.zone != null); } while (candidateScope.zone != zone); assert(scope != null); - final StringBuffer message = StringBuffer(); - message.writeln('Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - final _StackEntry originalGuarder = _findResponsibleMethod(scope.creationStack, 'guard', message); - final _StackEntry collidingGuarder = _findResponsibleMethod(StackTrace.current, 'guardSync', message); + final List information = []; + information.add(ErrorSummary('Guarded function conflict.')); + information.add(ErrorHint('You must use "await" with all Future-returning test APIs.')); + final _StackEntry originalGuarder = _findResponsibleMethod(scope.creationStack, 'guard', information); + final _StackEntry collidingGuarder = _findResponsibleMethod(StackTrace.current, 'guardSync', information); if (originalGuarder != null && collidingGuarder != null) { String originalName; if (originalGuarder.className == null) { originalName = '(${originalGuarder.methodName}) '; - message.writeln( + information.add(ErrorDescription( 'The guarded "${originalGuarder.methodName}" function ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}.' - ); + )); } else { originalName = '(${originalGuarder.className}.${originalGuarder.methodName}) '; - message.writeln( + information.add(ErrorDescription( 'The guarded method "${originalGuarder.methodName}" ' 'from class ${originalGuarder.className} ' 'was called from ${originalGuarder.callerFile} ' 'on line ${originalGuarder.callerLine}.' - ); + )); } final String again = (originalGuarder.callerFile == collidingGuarder.callerFile) && (originalGuarder.callerLine == collidingGuarder.callerLine) ? @@ -212,53 +216,52 @@ class TestAsyncUtils { (originalGuarder.methodName == collidingGuarder.methodName)) { originalName = ''; collidingName = ''; - message.writeln( + information.add(ErrorDescription( 'Then, it ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' - ); + )); } else if (collidingGuarder.className == null) { collidingName = '(${collidingGuarder.methodName}) '; - message.writeln( + information.add(ErrorDescription( 'Then, the "${collidingGuarder.methodName}" function ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' - ); + )); } else { collidingName = '(${collidingGuarder.className}.${collidingGuarder.methodName}) '; - message.writeln( + information.add(ErrorDescription( 'Then, the "${collidingGuarder.methodName}" method ' '${originalGuarder.className == collidingGuarder.className ? "(also from class ${collidingGuarder.className})" : "from class ${collidingGuarder.className}"} ' 'was called ${again}from ${collidingGuarder.callerFile} ' 'on line ${collidingGuarder.callerLine}.' - ); + )); } - message.writeln( + information.add(ErrorDescription( 'The first ${originalGuarder.className == null ? "function" : "method"} $originalName' 'had not yet finished executing at the time that ' 'the second ${collidingGuarder.className == null ? "function" : "method"} $collidingName' 'was called. Since both are guarded, and the second was not a nested call inside the first, the ' 'first must complete its execution before the second can be called. Typically, this is achieved by ' 'putting an "await" statement in front of the call to the first.' - ); + )); if (collidingGuarder.className == null && collidingGuarder.methodName == 'expect') { - message.writeln( + information.add(ErrorHint( 'If you are confident that all test APIs are being called using "await", and ' 'this expect() call is not being called at the top level but is itself being ' 'called from some sort of callback registered before the ${originalGuarder.methodName} ' 'method was called, then consider using expectSync() instead.' - ); + )); } - message.writeln( - '\n' - 'When the first ${originalGuarder.className == null ? "function" : "method"} ' + information.add(DiagnosticsStackTrace( + '\nWhen the first ${originalGuarder.className == null ? "function" : "method"} ' '$originalName' - 'was called, this was the stack:' - ); - message.writeln(FlutterError.defaultStackFilter(scope.creationStack.toString().trimRight().split('\n')).join('\n')); + 'was called, this was the stack', + scope.creationStack, + )); } - throw FlutterError(message.toString().trimRight()); + throw FlutterError.fromParts(information); } /// Verifies that there are no guarded methods currently pending (see [guard]). @@ -266,21 +269,23 @@ class TestAsyncUtils { /// This is used at the end of tests to ensure that nothing leaks out of the test. static void verifyAllScopesClosed() { if (_scopeStack.isNotEmpty) { - final StringBuffer message = StringBuffer(); - message.writeln('Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.'); + final List information = [ + ErrorSummary('Asynchronous call to guarded function leaked.'), + ErrorHint('You must use "await" with all Future-returning test APIs.') + ]; for (_AsyncScope scope in _scopeStack) { - final _StackEntry guarder = _findResponsibleMethod(scope.creationStack, 'guard', message); + final _StackEntry guarder = _findResponsibleMethod(scope.creationStack, 'guard', information); if (guarder != null) { - message.writeln( + information.add(ErrorDescription( 'The guarded method "${guarder.methodName}" ' '${guarder.className != null ? "from class ${guarder.className} " : ""}' 'was called from ${guarder.callerFile} ' 'on line ${guarder.callerLine}, ' 'but never completed before its parent scope closed.' - ); + )); } } - throw FlutterError(message.toString().trimRight()); + throw FlutterError.fromParts(information); } } @@ -288,7 +293,7 @@ class TestAsyncUtils { return line != ''; } - static _StackEntry _findResponsibleMethod(StackTrace rawStack, String method, StringBuffer errors) { + static _StackEntry _findResponsibleMethod(StackTrace rawStack, String method, List information) { assert(method == 'guard' || method == 'guardSync'); final List stack = rawStack.toString().split('\n').where(_stripAsynchronousSuspensions).toList(); assert(stack.last == ''); @@ -334,18 +339,18 @@ class TestAsyncUtils { // One reason you might get here is if the guarding method was called directly from // a 'dart:' API, like from the Future/microtask mechanism, because dart: URLs in the // stack trace don't have a column number and so don't match the regexp above. - errors.writeln('(Unable to parse the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)'); - errors.writeln('${stack[index]}'); + information.add(ErrorSummary('(Unable to parse the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)')); + information.add(ErrorDescription('${stack[index]}')); } } else { - errors.writeln('(Unable to find the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)'); + information.add(ErrorSummary('(Unable to find the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)')); } } else { - errors.writeln('(Unable to parse the stack frame of the method that called $_className.$method(). The stack may be incomplete or bogus.)'); - errors.writeln('${stack[index]}'); + information.add(ErrorSummary('(Unable to parse the stack frame of the method that called $_className.$method(). The stack may be incomplete or bogus.)')); + information.add(ErrorDescription('${stack[index]}')); } } else { - errors.writeln('(Unable to find the method that called $_className.$method(). The stack may be incomplete or bogus.)'); + information.add(ErrorSummary('(Unable to find the method that called $_className.$method(). The stack may be incomplete or bogus.)')); } return null; } diff --git a/packages/flutter_test/test/matchers_test.dart b/packages/flutter_test/test/matchers_test.dart index 12360426c7..9568911da5 100644 --- a/packages/flutter_test/test/matchers_test.dart +++ b/packages/flutter_test/test/matchers_test.dart @@ -149,7 +149,8 @@ void main() { expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#000000'))); expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#123456'))); - expect('Foo#A3b4D', isNot(equalsIgnoringHashCodes('Foo#00000'))); + expect('FOO#A3b4D', equalsIgnoringHashCodes('FOO#00000')); + expect('FOO#A3b4J', isNot(equalsIgnoringHashCodes('FOO#00000'))); expect('Foo#12345(Bar#9110f)', equalsIgnoringHashCodes('Foo#00000(Bar#00000)')); diff --git a/packages/flutter_test/test/stack_manipulation_test.dart b/packages/flutter_test/test/stack_manipulation_test.dart index d0f16d709f..426657f1b7 100644 --- a/packages/flutter_test/test/stack_manipulation_test.dart +++ b/packages/flutter_test/test/stack_manipulation_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,9 +11,10 @@ void main() { expect(false, isTrue); throw 'unexpectedly did not throw'; } catch (e, stack) { - final StringBuffer information = StringBuffer(); + final List information = []; expect(reportExpectCall(stack, information), 4); - final List lines = information.toString().split('\n'); + final TextTreeRenderer renderer = TextTreeRenderer(); + final List lines = information.map((DiagnosticsNode node) => renderer.render(node).trimRight()).join('\n').split('\n'); expect(lines[0], 'This was caught by the test expectation on the following line:'); expect(lines[1], matches(r'^ .*stack_manipulation_test.dart line [0-9]+$')); } @@ -20,9 +22,9 @@ void main() { try { throw null; } catch (e, stack) { - final StringBuffer information = StringBuffer(); + final List information = []; expect(reportExpectCall(stack, information), 0); - expect(information.toString(), ''); + expect(information, isEmpty); } }); } diff --git a/packages/flutter_test/test/test_async_utils_test.dart b/packages/flutter_test/test/test_async_utils_test.dart index 2b67a8018a..46dc0d33f8 100644 --- a/packages/flutter_test/test/test_async_utils_test.dart +++ b/packages/flutter_test/test/test_async_utils_test.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -43,12 +44,13 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.')); - real_test.expect(lines[2], matches(r'Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.')); - real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); - real_test.expect(lines[4], ''); - real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); + real_test.expect(lines[0], 'Guarded function conflict.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.')); + real_test.expect(lines[3], matches(r'Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.')); + real_test.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); + real_test.expect(lines[5], ''); + real_test.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); real_test.expect(lines.length, greaterThan(6)); } expect(await f1, isNull); @@ -64,13 +66,14 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[2], matches(r'^Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); - real_test.expect(lines[4], ''); - real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); - real_test.expect(lines.length, greaterThan(6)); + real_test.expect(lines[0], 'Guarded function conflict.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[3], matches(r'^Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); + real_test.expect(lines[5], ''); + real_test.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); + real_test.expect(lines.length, greaterThan(7)); } expect(await f1, isNull); expect(f2, isNull); @@ -85,13 +88,14 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[2], matches(r'^Then, the "testGuard3" method from class TestAPISubclass was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPISubclass.testGuard3) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); - real_test.expect(lines[4], ''); - real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); - real_test.expect(lines.length, greaterThan(6)); + real_test.expect(lines[0], 'Guarded function conflict.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[3], matches(r'^Then, the "testGuard3" method from class TestAPISubclass was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPISubclass.testGuard3) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); + real_test.expect(lines[5], ''); + real_test.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); + real_test.expect(lines.length, greaterThan(7)); } expect(await f1, isNull); expect(f2, isNull); @@ -106,13 +110,14 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[2], matches(r'^Then, the "expect" function was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second function (expect) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); - real_test.expect(lines[4], 'If you are confident that all test APIs are being called using "await", and this expect() call is not being called at the top level but is itself being called from some sort of callback registered before the testGuard1 method was called, then consider using expectSync() instead.'); - real_test.expect(lines[5], ''); - real_test.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); + real_test.expect(lines[0], 'Guarded function conflict.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[3], matches(r'^Then, the "expect" function was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second function (expect) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); + real_test.expect(lines[5], 'If you are confident that all test APIs are being called using "await", and this expect() call is not being called at the top level but is itself being called from some sort of callback registered before the testGuard1 method was called, then consider using expectSync() instead.'); + real_test.expect(lines[6], ''); + real_test.expect(lines[7], 'When the first method (TestAPI.testGuard1) was called, this was the stack:'); real_test.expect(lines.length, greaterThan(7)); } expect(await f1, isNull); @@ -126,13 +131,35 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[2], matches(r'^Then, it was called from .*test_async_utils_test.dart on line [0-9]+\.$')); - real_test.expect(lines[3], 'The first method had not yet finished executing at the time that the second method was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); - real_test.expect(lines[4], ''); - real_test.expect(lines[5], 'When the first method was called, this was the stack:'); - real_test.expect(lines.length, greaterThan(6)); + real_test.expect(lines[0], 'Guarded function conflict.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[3], matches(r'^Then, it was called from .*test_async_utils_test.dart on line [0-9]+\.$')); + real_test.expect(lines[4], 'The first method had not yet finished executing at the time that the second method was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.'); + real_test.expect(lines[5], ''); + real_test.expect(lines[6], 'When the first method was called, this was the stack:'); + real_test.expect(lines.length, greaterThan(7)); + // TODO(jacobr): add more tests like this if they are useful. + + final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder(); + e.debugFillProperties(propertiesBuilder); + final List information = propertiesBuilder.properties; + real_test.expect(information.length, 6); + real_test.expect(information[0].level, DiagnosticLevel.summary); + real_test.expect(information[1].level, DiagnosticLevel.hint); + real_test.expect(information[2].level, DiagnosticLevel.info); + real_test.expect(information[3].level, DiagnosticLevel.info); + real_test.expect(information[4].level, DiagnosticLevel.info); + real_test.expect(information[5].level, DiagnosticLevel.info); + real_test.expect(information[0], isInstanceOf>()); + real_test.expect(information[1], isInstanceOf>()); + real_test.expect(information[2], isInstanceOf>()); + real_test.expect(information[3], isInstanceOf>()); + real_test.expect(information[4], isInstanceOf>()); + real_test.expect(information[5], isInstanceOf()); + final DiagnosticsStackTrace stackTraceProperty = information[5]; + real_test.expect(stackTraceProperty.name, '\nWhen the first method was called, this was the stack'); + real_test.expect(stackTraceProperty.value, isInstanceOf()); } await f1; await f2; @@ -146,10 +173,19 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$')); - real_test.expect(lines[2], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.')); - real_test.expect(lines.length, 3); + real_test.expect(lines[0], 'Asynchronous call to guarded function leaked.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$')); + real_test.expect(lines[3], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.')); + real_test.expect(lines.length, 4); + final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder(); + e.debugFillProperties(propertiesBuilder); + final List information = propertiesBuilder.properties; + real_test.expect(information.length, 4); + real_test.expect(information[0].level, DiagnosticLevel.summary); + real_test.expect(information[1].level, DiagnosticLevel.hint); + real_test.expect(information[2].level, DiagnosticLevel.info); + real_test.expect(information[3].level, DiagnosticLevel.info); } await f1; }); @@ -162,10 +198,19 @@ void main() { throw 'unexpectedly did not throw'; } on FlutterError catch (e) { final List lines = e.message.split('\n'); - real_test.expect(lines[0], 'Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.'); - real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$')); - real_test.expect(lines[2], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.')); - real_test.expect(lines.length, 3); + real_test.expect(lines[0], 'Asynchronous call to guarded function leaked.'); + real_test.expect(lines[1], 'You must use "await" with all Future-returning test APIs.'); + real_test.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$')); + real_test.expect(lines[3], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.')); + real_test.expect(lines.length, 4); + final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder(); + e.debugFillProperties(propertiesBuilder); + final List information = propertiesBuilder.properties; + real_test.expect(information.length, 4); + real_test.expect(information[0].level, DiagnosticLevel.summary); + real_test.expect(information[1].level, DiagnosticLevel.hint); + real_test.expect(information[2].level, DiagnosticLevel.info); + real_test.expect(information[3].level, DiagnosticLevel.info); } await f1; }); diff --git a/packages/flutter_tools/test/commands/test_test.dart b/packages/flutter_tools/test/commands/test_test.dart index cefe0bd3f2..951b34e381 100644 --- a/packages/flutter_tools/test/commands/test_test.dart +++ b/packages/flutter_tools/test/commands/test_test.dart @@ -122,7 +122,7 @@ Future _testFile(String testName, String workingDirectory, String testDire reason: 'Failure in $testName to compare to $fullTestExpectation', ); final String expectationLine = expectations[expectationLineNumber]; - final String outputLine = output[outputLineNumber]; + String outputLine = output[outputLineNumber]; if (expectationLine == '<>') { allowSkip = true; expectationLineNumber += 1; @@ -139,6 +139,18 @@ Future _testFile(String testName, String workingDirectory, String testDire expect(haveSeenStdErrMarker, isFalse); haveSeenStdErrMarker = true; } + if (!RegExp(expectationLine).hasMatch(outputLine) && outputLineNumber + 1 < output.length) { + // Check if the RegExp can match the next two lines in the output so + // that it is possible to write expectations that still hold even if a + // line is wrapped slightly differently due to for example a file name + // being longer on one platform than another. + final String mergedLines = '$outputLine\n${output[outputLineNumber+1]}'; + if (RegExp(expectationLine).hasMatch(mergedLines)) { + outputLineNumber += 1; + outputLine = mergedLines; + } + } + expect(outputLine, matches(expectationLine), reason: 'Full output:\n- - - -----8<----- - - -\n${output.join("\n")}\n- - - -----8<----- - - -'); expectationLineNumber += 1; outputLineNumber += 1;