From 9f510ebdc991ef96525c5e268a94805c1370e8b2 Mon Sep 17 00:00:00 2001 From: Jacob Richman Date: Tue, 25 Jul 2017 09:25:13 -0700 Subject: [PATCH] Refactor RenderObject.toStringDeep and Widget.toStringDeep code to use DiagnosticsNode (#11359) Refactor RenderObject.toStringDeep and Widget.toStringDeep code to use DiagnosticsNode. --- .../lib/demo/animation/home.dart | 8 +- .../flutter/lib/src/cupertino/button.dart | 7 +- packages/flutter/lib/src/cupertino/page.dart | 16 + .../flutter/lib/src/cupertino/slider.dart | 10 +- .../flutter/lib/src/cupertino/switch.dart | 18 +- .../foundation/tree_diagnostics_mixin.dart | 1954 ++++++++++++++++- packages/flutter/lib/src/material/button.dart | 7 +- .../flutter/lib/src/material/icon_button.dart | 12 +- .../flutter/lib/src/material/ink_well.dart | 14 +- .../lib/src/material/input_decorator.dart | 18 +- .../flutter/lib/src/material/material.dart | 19 +- .../lib/src/material/progress_indicator.dart | 11 +- packages/flutter/lib/src/material/slider.dart | 10 +- packages/flutter/lib/src/material/switch.dart | 9 +- packages/flutter/lib/src/material/tabs.dart | 10 +- .../flutter/lib/src/material/text_field.dart | 30 +- packages/flutter/lib/src/material/theme.dart | 13 +- .../flutter/lib/src/material/toggleable.dart | 9 +- .../flutter/lib/src/material/tooltip.dart | 10 +- .../flutter/lib/src/painting/box_painter.dart | 48 +- .../flutter/lib/src/painting/decoration.dart | 14 +- .../lib/src/painting/flutter_logo.dart | 17 +- .../flutter/lib/src/painting/text_span.dart | 62 +- .../flutter/lib/src/painting/text_style.dart | 156 +- packages/flutter/lib/src/rendering/block.dart | 6 +- packages/flutter/lib/src/rendering/box.dart | 28 +- packages/flutter/lib/src/rendering/debug.dart | 16 +- .../flutter/lib/src/rendering/editable.dart | 30 +- packages/flutter/lib/src/rendering/flex.dart | 20 +- packages/flutter/lib/src/rendering/image.dart | 33 +- packages/flutter/lib/src/rendering/layer.dart | 114 +- .../flutter/lib/src/rendering/object.dart | 94 +- .../flutter/lib/src/rendering/paragraph.dart | 8 +- .../flutter/lib/src/rendering/proxy_box.dart | 208 +- .../lib/src/rendering/shifted_box.dart | 48 +- .../flutter/lib/src/rendering/sliver.dart | 74 +- .../rendering/sliver_multi_box_adaptor.dart | 47 +- .../rendering/sliver_persistent_header.dart | 22 +- packages/flutter/lib/src/rendering/stack.dart | 16 +- packages/flutter/lib/src/rendering/table.dart | 60 +- packages/flutter/lib/src/rendering/view.dart | 16 +- .../flutter/lib/src/rendering/viewport.dart | 37 +- packages/flutter/lib/src/rendering/wrap.dart | 16 +- .../lib/src/widgets/animated_cross_fade.dart | 20 +- .../lib/src/widgets/automatic_keep_alive.dart | 20 +- packages/flutter/lib/src/widgets/banner.dart | 18 +- packages/flutter/lib/src/widgets/basic.dart | 286 +-- .../flutter/lib/src/widgets/container.dart | 38 +- .../lib/src/widgets/editable_text.dart | 31 +- .../lib/src/widgets/focus_manager.dart | 24 +- .../flutter/lib/src/widgets/framework.dart | 138 +- .../lib/src/widgets/gesture_detector.dart | 20 +- packages/flutter/lib/src/widgets/icon.dart | 16 +- .../flutter/lib/src/widgets/icon_theme.dart | 6 +- packages/flutter/lib/src/widgets/image.dart | 38 +- .../flutter/lib/src/widgets/image_icon.dart | 16 +- .../lib/src/widgets/implicit_animations.dart | 126 +- .../flutter/lib/src/widgets/locale_query.dart | 6 +- .../flutter/lib/src/widgets/media_query.dart | 6 +- packages/flutter/lib/src/widgets/overlay.dart | 52 +- .../lib/src/widgets/overscroll_indicator.dart | 18 +- .../flutter/lib/src/widgets/page_view.dart | 13 +- .../widgets/primary_scroll_controller.dart | 6 +- .../src/widgets/raw_keyboard_listener.dart | 6 +- packages/flutter/lib/src/widgets/routes.dart | 9 +- .../lib/src/widgets/scroll_configuration.dart | 6 +- .../flutter/lib/src/widgets/scroll_view.dart | 35 +- .../flutter/lib/src/widgets/scrollable.dart | 15 +- packages/flutter/lib/src/widgets/sliver.dart | 12 +- .../src/widgets/sliver_persistent_header.dart | 14 +- packages/flutter/lib/src/widgets/table.dart | 6 +- packages/flutter/lib/src/widgets/text.dart | 15 +- .../lib/src/widgets/ticker_provider.dart | 34 +- packages/flutter/lib/src/widgets/title.dart | 10 +- .../flutter/lib/src/widgets/transitions.dart | 6 +- .../flutter/lib/src/widgets/viewport.dart | 22 +- .../tree_diagnostics_mixin_test.dart | 1379 +++++++++++- .../test/painting/flutter_logo_test.dart | 4 +- .../test/painting/text_style_test.dart | 25 +- .../flutter/test/rendering/debug_test.dart | 39 + .../flutter/test/rendering/editable_test.dart | 27 +- .../flutter/test/rendering/flex_test.dart | 17 +- .../test/rendering/paragraph_test.dart | 6 +- .../flutter/test/rendering/slivers_test.dart | 78 +- .../flutter/test/rendering/table_test.dart | 4 +- .../flutter/test/rendering/wrap_test.dart | 6 +- .../test/widgets/animated_container_test.dart | 2 +- packages/flutter/test/widgets/image_test.dart | 2 +- .../flutter/test/widgets/keep_alive_test.dart | 13 +- .../widgets/list_view_viewporting_test.dart | 2 +- .../test/widgets/overflow_box_test.dart | 9 +- .../flutter/test/widgets/overlay_test.dart | 13 +- .../widgets/sliver_fill_viewport_test.dart | 10 +- .../widgets/slivers_appbar_pinned_test.dart | 2 +- 94 files changed, 4610 insertions(+), 1491 deletions(-) diff --git a/examples/flutter_gallery/lib/demo/animation/home.dart b/examples/flutter_gallery/lib/demo/animation/home.dart index 503b766a93..b0d4a986b3 100644 --- a/examples/flutter_gallery/lib/demo/animation/home.dart +++ b/examples/flutter_gallery/lib/demo/animation/home.dart @@ -102,10 +102,10 @@ class _StatusBarPaddingSliver extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('maxHeight: $maxHeight'); - description.add('scrollFactor: $scrollFactor'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('maxHeight', maxHeight)); + description.add(new DoubleProperty('scrollFactor', scrollFactor)); } } diff --git a/packages/flutter/lib/src/cupertino/button.dart b/packages/flutter/lib/src/cupertino/button.dart index db12d153df..358b50e3ee 100644 --- a/packages/flutter/lib/src/cupertino/button.dart +++ b/packages/flutter/lib/src/cupertino/button.dart @@ -101,10 +101,9 @@ class CupertinoButton extends StatefulWidget { _CupertinoButtonState createState() => new _CupertinoButtonState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (!enabled) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('enabled', value: enabled, ifFalse: 'disabled')); } } diff --git a/packages/flutter/lib/src/cupertino/page.dart b/packages/flutter/lib/src/cupertino/page.dart index b2aa609bb0..6cd7968a9b 100644 --- a/packages/flutter/lib/src/cupertino/page.dart +++ b/packages/flutter/lib/src/cupertino/page.dart @@ -422,6 +422,22 @@ class _CupertinoEdgeShadowDecoration extends Decoration { int get hashCode { return edgeGradient.hashCode; } + + @override + DiagnosticsNode toDiagnosticsNode({ + String name, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.singleLine, + }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + style: style, + description: '$runtimeType', + fillProperties: (List properties) { + properties.add(new DiagnosticsProperty('edgeGradient', edgeGradient)); + }, + ); + } } /// A [BoxPainter] used to draw the page transition shadow using gradients. diff --git a/packages/flutter/lib/src/cupertino/slider.dart b/packages/flutter/lib/src/cupertino/slider.dart index 8ed550ad23..147f7d5daa 100644 --- a/packages/flutter/lib/src/cupertino/slider.dart +++ b/packages/flutter/lib/src/cupertino/slider.dart @@ -111,11 +111,11 @@ class CupertinoSlider extends StatefulWidget { _CupertinoSliderState createState() => new _CupertinoSliderState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value.toStringAsFixed(1)}'); - description.add('min: $min'); - description.add('max: $max'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('value', value)); + description.add(new DoubleProperty('min', min)); + description.add(new DoubleProperty('max', max)); } } diff --git a/packages/flutter/lib/src/cupertino/switch.dart b/packages/flutter/lib/src/cupertino/switch.dart index 9d5501e7f3..c638179c4e 100644 --- a/packages/flutter/lib/src/cupertino/switch.dart +++ b/packages/flutter/lib/src/cupertino/switch.dart @@ -88,11 +88,10 @@ class CupertinoSwitch extends StatefulWidget { _CupertinoSwitchState createState() => new _CupertinoSwitchState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value ? "on" : "off"}'); - if (onChanged == null) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true)); + description.add(new ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); } } @@ -420,10 +419,9 @@ class _RenderCupertinoSwitch extends RenderConstrainedBox implements SemanticsAc } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value ? "checked" : "unchecked"}'); - if (!isInteractive) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('value', value: value, ifTrue: 'checked', ifFalse: 'unchecked', showName: true)); + description.add(new FlagProperty('isInteractive', value: isInteractive, ifTrue: 'enabled', ifFalse: 'disabled', showName: true, defaultValue: true)); } } diff --git a/packages/flutter/lib/src/foundation/tree_diagnostics_mixin.dart b/packages/flutter/lib/src/foundation/tree_diagnostics_mixin.dart index 8d461b42d5..05bd1be976 100644 --- a/packages/flutter/lib/src/foundation/tree_diagnostics_mixin.dart +++ b/packages/flutter/lib/src/foundation/tree_diagnostics_mixin.dart @@ -6,6 +6,1586 @@ import 'package:meta/meta.dart'; import 'print.dart'; +/// Styles for displaying a node in a [DiagnosticsNode] tree. +/// +/// See also: +/// +/// * [DiagnosticsNode.toStringDeep], which dumps text art trees for these +/// styles. +enum DiagnosticsTreeStyle { + /// Sparse style for displaying trees. + /// + /// See also: + /// + /// * [RenderObject], which uses this style. + sparse, + + /// Connects a node to its parent with a dashed line. + /// + /// See also: + /// + /// * [RenderSliverMultiBoxAdaptor], which uses this style to distinguish + /// offstage children from onstage children. + offstage, + + /// Slightly more compact version of the [sparse] style. + /// + /// See also: + /// + /// * [Element], which uses this style. + dense, + + /// Style that enables transitioning from nodes of one style to children of + /// another. + /// + /// See also: + /// + /// * [RenderParagraph], which uses this style to display a [TextSpan] child + /// in a way that is compatible with the [DiagnosticsTreeStyle.sparse] + /// style of the [RenderObject] tree. + transition, + + /// Render the tree just using whitespace without connecting parents to + /// children using lines. + /// + /// See also: + /// + /// * [SliverGeometry], which uses this style. + whitespace, + + /// Render the tree on a single line without showing children. + singleLine, +} + +/// Configuration specifying how a particular [DiagnosticsTreeStyle] should be +/// rendered as text art. +/// +/// See also: +/// +/// * [sparseTextConfiguration], which is a typical style. +/// * [leafTextConfiguration], which is an example of a complex tree style. +/// * [DiagnosticsNode.toStringDeep], for code using [TextTreeConfiguration] +/// to render text art for arbitrary trees of [DiagnosticsNode] objects. +class TextTreeConfiguration { + TextTreeConfiguration({ + @required this.prefixLineOne, + @required this.prefixOtherLines, + @required this.prefixLastChildLineOne, + @required this.prefixOtherLinesRootNode, + @required this.linkCharacter, + @required this.propertyPrefixIfChildren, + @required this.propertyPrefixNoChildren, + this.lineBreak: '\n', + this.afterName: ':', + this.afterDescriptionIfBody: '', + this.beforeProperties: '', + this.afterProperties: '', + this.propertySeparator: '', + this.bodyIndent: '', + this.footer: '', + this.showChildren: true, + this.addBlankLineIfNoChildren: true, + this.isNameOnOwnLine: false, + this.isBlankLineBetweenPropertiesAndChildren: true, + }) : childLinkSpace = ' ' * linkCharacter.length; + + /// Prefix to add to the first line to display a child with this style. + final String prefixLineOne; + + /// Prefix to add to other lines to display a child with this style. + /// + /// [prefixOtherLines] should typically be one character shorter than + /// [prefixLineOne] as + final String prefixOtherLines; + + /// Prefix to add to the first line to display the last child of a node with + /// this style. + final String prefixLastChildLineOne; + + /// Additional prefix to add to other lines of a node if this is the root node + /// of the tree. + final String prefixOtherLinesRootNode; + + /// Prefix to add before each property if the node as children. + /// + /// Plays a similar role to [linkCharacter] except that some configurations + /// intentionally use a different line style than the [linkCharacter]. + final String propertyPrefixIfChildren; + + /// Prefix to add before each property if the node does not have children. + /// + /// This string is typically a whitespace string the same length as + /// [propertyPrefixIfChildren] but can have a different length. + final String propertyPrefixNoChildren; + + /// Character to use to draw line linking parent to child. + /// + /// The first child does not require a line but all subsequent children do + /// with the line drawn immediately before the left edge of the previous + /// sibling. + final String linkCharacter; + + /// Whitespace to draw instead of the childLink character if this node is the + /// last child of its parent so no link line is required. + final String childLinkSpace; + + /// Character(s) to use to separate lines. + /// + /// Typically leave set at the default value of '\n' unless this style needs + /// to treat lines differently as is the case for + /// [singleLineTextConfiguration]. + final String lineBreak; + + /// Text added immediately after the name of the node. + /// + /// See [leafTextConfiguration] for an example of using a value other than ':' + /// to achieve a custom line art style. + final String afterName; + + /// Text to add immediately after the description line of a node with + /// properties and/or children. + final String afterDescriptionIfBody; + + /// Optional string to add before the properties of a node. + /// + /// Only displayed if the node has properties. + /// See [singleLineTextConfiguration] for an example of using this field + /// to enclose the property list with parenthesis. + final String beforeProperties; + + /// Optional string to add after the properties of a node. + /// + /// See documentation for [beforeProperties]. + final String afterProperties; + + /// Property separator to add between properties. + /// + /// See [singleLineTextConfiguration] for an example of using this field + /// to render properties as a comma separated list. + final String propertySeparator; + + /// Prefix to add to all lines of the body of the tree node. + /// + /// The body is all content in the node other than the name and description. + final String bodyIndent; + + /// Whether the children of a node should be shown. + /// + /// See [singleLineTextConfiguration] for an example of using this field to + /// hide all children of a node. + final bool showChildren; + + /// Whether to add a blank line at the end of the output for a node if it has + /// no children. + /// + /// See [denseTextConfiguration] for an example of setting this to false. + final bool addBlankLineIfNoChildren; + + /// Whether the name should be displayed on the same line as the description. + final bool isNameOnOwnLine; + + /// Footer to add as its own line at the end of a non-root node. + /// + /// See [leafTextConfiguration] for an example of using footer to draw a box + /// around the node. [footer] is indented the same amount as [prefixOtherLines]. + final String footer; + + /// Add a blank line between properties and children if both are present. + final bool isBlankLineBetweenPropertiesAndChildren; + + /// Whether all text should be added to a single line. + bool get isSingleLine => lineBreak.isEmpty; +} + +/// Default text tree configuration. +/// +/// Example: +/// ``` +/// : +/// │ +/// │ +/// │ ... +/// │ +/// ├─: +/// │ │ +/// │ │ +/// │ │ ... +/// │ │ +/// │ │ +/// │ └─: +/// │ +/// │ +/// │ ... +/// │ +/// │ +/// └─: ' +/// +/// +/// ... +/// +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.sparse] +final TextTreeConfiguration sparseTextConfiguration = new TextTreeConfiguration( + prefixLineOne: '├─', + prefixOtherLines: ' ', + prefixLastChildLineOne: '└─', + linkCharacter: '│', + propertyPrefixIfChildren: '│ ', + propertyPrefixNoChildren: ' ', + prefixOtherLinesRootNode: ' ', +); + +/// Identical to [sparseTextConfiguration] except that the lines connecting +/// parent to children are dashed. +/// +/// Example: +/// ``` +/// : +/// │ +/// │ +/// │ ... +/// │ +/// ├─: +/// ╎ │ +/// ╎ │ +/// ╎ │ ... +/// ╎ │ +/// ╎ │ +/// ╎ └─: +/// ╎ +/// ╎ +/// ╎ ... +/// ╎ +/// ╎ +/// ╎╌: +/// ╎ │ +/// ╎ │ +/// ╎ │ ... +/// ╎ │ +/// ╎ │ +/// ╎ └─: +/// ╎ +/// ╎ +/// ╎ ... +/// ╎ +/// ╎ +/// └╌: ' +/// +/// +/// ... +/// +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.offstage], uses this style for ascii art display. +final TextTreeConfiguration dashedTextConfiguration = new TextTreeConfiguration( + prefixLineOne: '╎╌', + prefixLastChildLineOne: '└╌', + prefixOtherLines: ' ', + linkCharacter: '╎', + // Intentionally not set as a dashed line as that would make the properties + // look like they were disabled. + propertyPrefixIfChildren: '│ ', + propertyPrefixNoChildren: ' ', + prefixOtherLinesRootNode: ' ', +); + +/// Dense text tree configuration that minimizes horizontal whitespace. +/// +/// Example: +/// ``` +/// : +/// │ +/// │ +/// │ ... +/// │ +/// │ +/// ├: +/// │ +/// │ +/// │ ... +/// │ +/// │ +/// └: ' +/// +/// +/// ... +/// +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.dense] +final TextTreeConfiguration denseTextConfiguration = new TextTreeConfiguration( + prefixLineOne: '├', + prefixOtherLines: '', + prefixLastChildLineOne: '└', + linkCharacter: '│', + propertyPrefixIfChildren: '│', + propertyPrefixNoChildren: ' ', + prefixOtherLinesRootNode: '', + addBlankLineIfNoChildren: false, +); + +/// Configuration that draws a box around a leaf node. +/// +/// Used by leaf nodes such as [TextSpan] to draw a clear border around the +/// contents of a node. +/// +/// Example: +/// ``` +/// +/// ╞═╦══ ═══ +/// │ ║ : +/// │ ║ +/// │ ║ ... +/// │ ╚═══════════ +/// ╘═╦══ ═══ +/// ║ : +/// ║ +/// ║ ... +/// ╚═══════════ +/// ``` +/// +/// /// See also: +/// +/// * [DiagnosticsTreeStyle.transition] +final TextTreeConfiguration leafTextConfiguration = new TextTreeConfiguration( + prefixLineOne: '╞═╦══ ', + prefixLastChildLineOne: '╘═╦══ ', + prefixOtherLines: ' ║ ', + footer: ' ╚═══════════\n', + linkCharacter: '│', + // Subtree boundaries are clear due to the border around the node so omit the + // property prefix. + propertyPrefixIfChildren: '', + propertyPrefixNoChildren: '', + prefixOtherLinesRootNode: '', + afterName: ' ═══', + // Add a colon after the description if the node has a body to make the + // connection between the description and the body clearer. + afterDescriptionIfBody: ':', + // Members are indented an extra two spaces to disambiguate as the description + // is placed within the box instead of along side the name as is the case for + // other styles. + bodyIndent: ' ', + isNameOnOwnLine: true, + // 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. +/// +/// Use this style for displaying properties with structured values or for +/// displaying children within a [leafTextConfiguration] as using a style that +/// draws line art would be visually distracting for those cases. +/// +/// Example: +/// ``` +/// +/// : : +/// +/// +/// : : +/// +/// +///``` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.whitespace] +final TextTreeConfiguration whitespaceTextConfiguration = new 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: +/// `: (, , ..., )` +/// +/// See also: +/// +/// * [DiagnosticsTreeStyle.singleLine] +final TextTreeConfiguration singleLineTextConfiguration = new TextTreeConfiguration( + propertySeparator: ', ', + beforeProperties: '(', + afterProperties: ')', + prefixLineOne: '', + prefixOtherLines: '', + prefixLastChildLineOne: '', + lineBreak: '', + addBlankLineIfNoChildren: false, + showChildren: false, + propertyPrefixIfChildren: '', + propertyPrefixNoChildren: '', + linkCharacter: '', + prefixOtherLinesRootNode: '', +); + +/// Builder that builds a String with specified prefixes for the first and +/// subsequent lines. +/// +/// Allows for the incremental building of strings using `write*()` methods. +/// The strings are concatenated into a single string with the first line +/// prefixed by [prefixLineOne] and subsequent lines prefixed by +/// [prefixOtherLines]. +class _PrefixedStringBuilder { + _PrefixedStringBuilder(this.prefixLineOne, this.prefixOtherLines); + + /// Prefix to add to the first line. + final String prefixLineOne; + + /// Prefix to add to subsequent lines. + /// + /// 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; + + final StringBuffer _buffer = new StringBuffer(); + bool _atLineStart = true; + bool _hasMultipleLines = false; + + /// Whether the string being built already has more than 1 line. + bool get hasMultipleLines => _hasMultipleLines; + + /// Write text ensuring the specified prefixes for the first and subsequent + /// lines. + void write(String s) { + if (s.isEmpty) + return; + + if (s == '\n') { + // Edge case to avoid adding trailing whitespace when the caller did + // not explicitly add trailing trailing whitespace. + if (_buffer.isEmpty) { + _buffer.write(prefixLineOne.trimRight()); + } else if (_atLineStart) { + _buffer.write(prefixOtherLines.trimRight()); + _hasMultipleLines = true; + } + _buffer.write('\n'); + _atLineStart = true; + return; + } + + if (_buffer.isEmpty) { + _buffer.write(prefixLineOne); + } else if (_atLineStart) { + _buffer.write(prefixOtherLines); + _hasMultipleLines = true; + } + 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'); + } + + + /// Write a line assuming the line obeys 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) + return; + _buffer.write(line); + if (!line.endsWith('\n')) + _buffer.write('\n'); + _atLineStart = true; + } + + @override + String toString() => _buffer.toString(); +} + +class _NoDefaultValue { + const _NoDefaultValue(); +} + +/// Marker object indicating that a DiagnosticNode has no default value. +const _NoDefaultValue kNoDefaultValue = const _NoDefaultValue(); + +/// Defines diagnostics data for an [Object]. +/// +/// DiagnosticsNode provides a high quality multi-line string dump via +/// [toStringDeep]. The core members are the [name], [description], [getProperties], +/// [object], and [getChildren]. All other members exist typically to provide +/// hints for how [toStringDeep] and debugging tools should format output. +abstract class DiagnosticsNode { + DiagnosticsNode({ + @required this.name, + this.style: DiagnosticsTreeStyle.sparse, + this.showName: true, + this.showSeparator: true, + this.emptyBodyDescription, + }) { + // 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(':')); + } + + /// Constructor that creates a [DiagnosticsNode] where properties and children + /// are computed lazily. + factory DiagnosticsNode.lazy({ + String name, + Object object, + String description, + FillPropertiesCallback fillProperties, + GetChildrenCallback getChildren, + String emptyBodyDescription, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.sparse, + }) { + return new _LazyMembersDiagnosticsNode( + name: name, + object: object, + description: description, + fillProperties: fillProperties, + getChildren: getChildren, + style: style, + emptyBodyDescription: emptyBodyDescription, + ); + } + + + /// Diagnostics containing just a string `message` and not a concrete name or + /// value. + /// + /// See also: + /// + /// * [PropertyMessage], which should be used if the message should be + /// formatted like a property with a separate name and message. + factory DiagnosticsNode.message( + String message, { + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.singleLine, + }) { + return new DiagnosticsProperty( + '', + null, + description: message, + style: style, + showName: false, + ); + } + + /// Label describing the Diagnostics node. + final String name; + + /// Description with a short summary of the node itself not including children + /// or properties. + String get description; + + /// Whether to show a separator between [name] and [description]. + /// + /// If false, name and description should be shown with no separation. + /// `:` is typically used as a separator when displaying as text. + final bool showSeparator; + + /// Whether the diagnostics should be hidden when showing the default + /// view of a tree. + bool get hidden; + + final bool showName; + + /// Description to show if the node has no displayed properties or children. + final String emptyBodyDescription; + + /// Dart object this is diagnostics data for. + Object get object; + + /// Hint for how the node should be displayed. + final DiagnosticsTreeStyle style; + + /// Properties of this DiagnosticsNode. + /// + /// Properties and children are kept distinct even though they are both + /// [List] because they should be grouped differently. + List getProperties(); + + /// Children of this DiagnosticsNode. + /// + /// See also: + /// + /// * [getProperties] + List getChildren(); + + String get _separator => showSeparator ? ':' : ''; + + @override + String toString() { + if (style == DiagnosticsTreeStyle.singleLine) + return toStringDeep(); + + if (name == null || name.isEmpty || showName == false) + return description; + + return description.contains('\n') ? + '$name$_separator\n$description' : '$name$_separator $description'; + } + + TextTreeConfiguration get textTreeConfiguration { + switch (style) { + case DiagnosticsTreeStyle.dense: + return denseTextConfiguration; + case DiagnosticsTreeStyle.sparse: + return sparseTextConfiguration; + case DiagnosticsTreeStyle.offstage: + return dashedTextConfiguration; + case DiagnosticsTreeStyle.whitespace: + return whitespaceTextConfiguration; + case DiagnosticsTreeStyle.transition: + return leafTextConfiguration; + case DiagnosticsTreeStyle.singleLine: + return singleLineTextConfiguration; + } + return sparseTextConfiguration; + } + + /// 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. + /// + /// The [toStringDeep] method takes arguments, but those are intended for + /// internal use when recursing to the descendants, and so can be ignored. + /// + /// See also: + /// + /// * [toString], for a brief description of the object but not its children. + /// * [toStringShallow], for a detailed description of the object but not its + /// children. + String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { + prefixOtherLines ??= prefixLineOne; + + final List children = getChildren(); + final TextTreeConfiguration config = textTreeConfiguration; + if (prefixOtherLines.isEmpty) + prefixOtherLines += config.prefixOtherLinesRootNode; + + final _PrefixedStringBuilder builder = new _PrefixedStringBuilder( + prefixLineOne, prefixOtherLines); + + 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' : ' '); + } + builder.prefixOtherLines += children.isEmpty ? + config.propertyPrefixNoChildren : config.propertyPrefixIfChildren; + builder.write(description); + } + + final List properties = + getProperties().where((DiagnosticsNode n) => !n.hidden).toList(); + if (properties.isNotEmpty || children.isNotEmpty || emptyBodyDescription != null) + builder.write(config.afterDescriptionIfBody); + + if (properties.isNotEmpty) + builder.write(config.beforeProperties); + builder.write(config.lineBreak); + + builder.prefixOtherLines += config.bodyIndent; + + if (emptyBodyDescription != null && + properties.isEmpty && + children.isEmpty && + prefixLineOne.isNotEmpty) { + builder..write(emptyBodyDescription)..write(config.lineBreak); + } + + for (int i = 0; i < properties.length; ++i) { + final DiagnosticsNode property = properties[i]; + if (i > 0) + builder.write(config.propertySeparator); + + final int kWrapWidth = 65; + if (property.style != DiagnosticsTreeStyle.singleLine) { + final TextTreeConfiguration propertyStyle = property.textTreeConfiguration; + builder.writeRaw(property.toStringDeep( + '${builder.prefixOtherLines}${propertyStyle.prefixLineOne}', + '${builder.prefixOtherLines}${propertyStyle.linkCharacter}${propertyStyle.prefixOtherLines}', + )); + continue; + } + assert (property.style == null || + property.style == DiagnosticsTreeStyle.singleLine); + final String message = property == null ? '' : property.toString(); + if (config.isSingleLine || 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')); + } + } + builder.write(config.lineBreak); + } + if (properties.isNotEmpty) + builder.write(config.afterProperties); + + 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]; + + final TextTreeConfiguration childConfig = _childTextConfiguration(child, config); + if (i == children.length - 1) { + final String lastChildPrefixLineOne = '$prefixChildren${childConfig.prefixLastChildLineOne}'; + if (child == null) { + builder.writeRawLine('$lastChildPrefixLineOne'); + continue; + } + builder.writeRawLine(child.toStringDeep( + lastChildPrefixLineOne, + '$prefixChildren${childConfig.childLinkSpace}${childConfig.prefixOtherLines}', + )); + 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}'; + + if (child == null) { + builder.writeRawLine('$childPrefixLineOne'); + continue; + } + builder.writeRawLine(child.toStringDeep(childPrefixLineOne, childPrefixOtherLines)); + if (childConfig.footer.isNotEmpty) + builder.writeRaw('$prefixChildren${nextChildStyle.linkCharacter}${childConfig.footer}'); + } + } + } + return builder.toString(); + } +} + +/// Debugging message displayed like a property. +/// +/// The following two properties should be a [MessageProperty] not +/// [StringProperty] as the intent is to show a message with property style +/// display not to describe the value of an actual property of the object. +/// +/// ```dart +/// new MessageProperty('table size', '$columns\u00D7$rows')); +/// new MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)'); +/// ``` +/// +/// StringProperty should be used if the property has a concrete value that is +/// a string. +/// ```dart +/// new StringProperty('fontFamily', fontFamily); +/// new StringProperty('title', title): +/// ``` +/// +/// See also: +/// +/// * [DiagnosticsProperty.message], which serves the same role for messages +/// without a clear property name. +/// * [StringProperty], which should be used instead for properties with string +/// values. +class MessageProperty extends DiagnosticsProperty { + MessageProperty(String name, String message) : super(name, null, description: message); +} + +/// Property which encloses its string [value] in quotes. +/// +/// See also: +/// +/// * [MessageProperty], which should be used instead if showing a message +/// instead of describing a property with a string value. +class StringProperty extends DiagnosticsProperty { + StringProperty(String name, String value, { + String description, + bool showName: true, + Object defaultValue: kNoDefaultValue, + bool hidden: false, + this.quoted: true, + String ifEmpty, + }) : super( + name, + value, + description: description, + defaultValue: defaultValue, + showName: showName, + hidden: hidden, + ifEmpty: ifEmpty, + ); + + /// Whether the description is enclosed in double quotes. + final bool quoted; + + @override + String valueToString() { + final String text = _description ?? value; + if (quoted && text != null) { + // An empty value would not appear empty after being surrounded with + // quotes so we have to handle this case separately. + if (ifEmpty != null && text.isEmpty) + return ifEmpty; + return '"$text"'; + } + return text.toString(); + } +} + +abstract class _NumProperty extends DiagnosticsProperty { + _NumProperty(String name, + T value, { + bool hidden: false, + String ifNull, + this.unit, + bool showName: true, + Object defaultValue: kNoDefaultValue, + String tooltip, + }) : super( + name, + value, + hidden: hidden, + ifNull: ifNull, + showName: showName, + defaultValue: defaultValue, + tooltip: tooltip, + ); + + _NumProperty.lazy(String name, + ComputePropertyValueCallback computeValue, { + bool hidden: false, + String ifNull, + this.unit, + bool showName: true, + Object defaultValue: kNoDefaultValue, + String tooltip, + }) : super.lazy( + name, + computeValue, + hidden: hidden, + ifNull: ifNull, + showName: showName, + defaultValue: defaultValue, + tooltip: tooltip, + ); + + + /// Optional unit the [value] is measured in. + /// + /// Unit must be acceptable to display immediately after a number with no + /// spaces. For example: 'physical pixels per logical pixel' should be a + /// [tooltip] not a [unit]. + final String unit; + + /// String describing just the numeric [value] without a unit suffix. + String numberToString(); + + @override + String valueToString() { + if (value == null) + return value.toString(); + + return unit != null ? '${numberToString()}$unit' : numberToString(); + } +} +/// Property describing a [double] [value] with an option [unit] of measurement. +/// +/// Numeric formatting is optimized for debug message readability. +class DoubleProperty extends _NumProperty { + + /// If specified, `unit` describes the unit for the [value] (e.g. px). + DoubleProperty(String name, double value, { + bool hidden: false, + String ifNull, + String unit, + String tooltip, + Object defaultValue: kNoDefaultValue, + bool showName : true, + }) : super( + name, + value, + hidden: hidden, + ifNull: ifNull, + unit: unit, + tooltip: tooltip, + defaultValue: defaultValue, + showName: showName, + ); + + /// Property with a [value] that is computed only when needed. + /// + /// Use if computing the property [value] may throw an exception or is + /// expensive. + DoubleProperty.lazy( + String name, + ComputePropertyValueCallback computeValue, { + bool hidden: false, + String ifNull, + String unit, + String tooltip, + Object defaultValue: kNoDefaultValue, + }) : super.lazy( + name, + computeValue, + hidden: hidden, + ifNull: ifNull, + unit: unit, + tooltip: tooltip, + defaultValue: defaultValue, + ); + + @override + String numberToString() => object?.toStringAsFixed(1); +} + +/// An int valued property with an optional unit the value is measured in. +/// +/// Examples of units include 'px' and 'ms'. +class IntProperty extends _NumProperty { + IntProperty(String name, int value, { + String ifNull, + bool showName: true, + String unit, + Object defaultValue: kNoDefaultValue, + bool hidden: false, + }) : super( + name, + value, + ifNull: ifNull, + showName: showName, + unit: unit, + defaultValue: defaultValue, + hidden: hidden, + ); + + @override + String numberToString() => object.toString(); +} + +/// Property which clamps a [double] to between 0 and 1 and formats it as a +/// percentage. +class PercentProperty extends DoubleProperty { + PercentProperty(String name, double fraction, { + String ifNull, + bool showName: true, + String tooltip, + String unit, + }) : super( + name, + fraction, + ifNull: ifNull, + showName: showName, + tooltip: tooltip, + unit: unit, + ); + + @override + String valueToString() { + if (value == null) + return value.toString(); + + return unit != null ? '${numberToString()} $unit' : numberToString(); + } + + @override + String numberToString() { + if (value == null) + return value.toString(); + + return '${(value.clamp(0.0, 1.0) * 100.0).toStringAsFixed(1)}%'; + } +} + +/// Property where the description is either [ifTrue] or [ifFalse] depending on +/// whether [value] is `true` or `false`. +/// +/// Using FlagProperty instead of `DiagnosticsProperty` can make +/// diagnostics display more polished. For example, Given a property named +/// `visible` that is typically true, the following code will return 'hidden' +/// when `visible` is false and the empty string in contrast to `visible: true` +/// or `visible: false`. +/// +/// ## Sample code +/// +/// ```dart +/// new FlagProperty( +/// 'visible', +/// value: true, +/// ifFalse: 'hidden', +/// ) +/// ``` +/// +/// [FlagProperty] should also be used instead of `DiagnosticsProperty` +/// if showing the bool value would not clearly indicate the meaning of the +/// property value. +/// +/// ## Sample code +/// +/// ```dart +/// new FlagProperty( +/// 'inherit', +/// value: inherit, +/// ifTrue: '', +/// ifFalse: '', +/// ) +/// ``` +/// +/// See also: +/// +/// * [ObjectFlagProperty], which provides similar behavior describing whether +/// a `value` is `null`. +class FlagProperty extends DiagnosticsProperty { + /// Constructs a FlagProperty with the given descriptions with the specified descriptions. + /// + /// [showName] defaults to false as typically [ifTrue] and [ifFalse] should + /// be descriptions that make the property name redundant. + FlagProperty(String name, { + @required bool value, + this.ifTrue, + this.ifFalse, + bool showName: false, + bool hidden: false, + Object defaultValue: null, + }) : super( + name, + value, + showName: showName, + hidden: hidden, + defaultValue: defaultValue, + ) { + assert(ifTrue != null || ifFalse != null); + } + + /// Description to use if the property [value] is `true`. + /// + /// If not specified and [value] equals `true`, the description is set to the + /// empty string and the property is [hidden]. + final String ifTrue; + + /// Description to use if the property value is `false`. + /// + /// If not specified and [value] equals `false`, the description is set to the + /// empty string and the property is [hidden]. + final String ifFalse; + + @override + String valueToString() { + if (value == true) + return ifTrue ?? ''; + if (value == false) + return ifFalse ?? ''; + return ''; + } + + @override + bool get hidden { + if (_hidden || object == defaultValue) + return true; + if (object == true) + return ifTrue == null; + if (object == false) + return ifFalse == null; + + return true; + } +} + +/// Property with an `Iterable` [value] that can be displayed with +/// different [DiagnosticsTreeStyle] for custom rendering. +/// +/// If `style` is [DiagnosticsTreeStyle.singleLine], the iterable is described +/// as a comma separated list, otherwise the iterable is described as a line +/// break separated list. +class IterableProperty extends DiagnosticsProperty> { + IterableProperty(String name, Iterable value, { + Object defaultValue: kNoDefaultValue, + String ifNull, + String ifEmpty = '[]', + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.singleLine, + }) : super( + name, + value, + defaultValue: defaultValue, + ifNull: ifNull, + ifEmpty: ifEmpty, + style: style, + ); + + @override + String valueToString() { + if (value == null) + return value.toString(); + + return style == DiagnosticsTreeStyle.singleLine ? + value.join(', ') : object.join('\n'); + } +} + +/// An property than displays enum values tersely. +/// +/// The enum value is converted to a hyphen-separated string. For example: +/// [HitTestBehavior.deferToChild] is shown as `defer-to-child`. +/// +/// See also: +/// +/// * [DiagnosticsProperty] which documents named parameters common to all +/// [DiagnosticsProperty] +class EnumProperty extends DiagnosticsProperty { + EnumProperty(String name, T value, { + Object defaultValue: kNoDefaultValue, + bool hidden: false, + }) : super ( + name, + value, + defaultValue: defaultValue, + hidden: hidden, + ); + + @override + String valueToString() { + if (value == null) + return value.toString(); + + return camelCaseToHyphenatedName(describeEnum(value)); + } +} + +/// Flag describing whether a [value] is `null` or not. +/// +/// [ifPresent] and [ifNull] describe the property [value] +/// when it is present and `null` respectively. If [ifPresent] or [ifNull] is +/// omitted, that is taken to mean that [hidden] should be `true`when [value] is +/// present and null respectively. +/// +/// See also: +/// +/// * [FlagProperty], which provides similar functionality describing whether +/// a `value` is `true` or `false`. +class ObjectFlagProperty extends DiagnosticsProperty { + ObjectFlagProperty(String name, T value, { + this.ifPresent, + String ifNull, + bool showName: false, + bool hidden: false, + }) : super( + name, + value, + showName: showName, + hidden: hidden, + ifNull: ifNull, + ) { + assert(ifPresent != null || ifNull != null); + } + + /// Shorthand constructor to describe whether the property has a value. + /// + /// Only use if prefixing the property name with the word 'has' is a good + /// flag name. + ObjectFlagProperty.has( + String name, + T value, + ) : ifPresent = 'has $name', + super( + name, + value, + showName: false, + ); + + /// Description to use if the property [value] is not `null`. + /// + /// If the property [value] is not `null` and [ifPresent] is null, the + /// [description] is the empty string and the property is [hidden]. + final String ifPresent; + + @override + String valueToString() { + if (value != null) + return ifPresent ?? ''; + + return ifNull ?? ''; + } + + @override + bool get hidden { + if (super.hidden) + return true; + + if (object != null) + return ifPresent == null; + + return ifNull == null; + } +} + +/// Signature for computing the value of a property. +/// +/// May throw exception if accessing the property would throw an exception +/// and callers must handle that case gracefully. For example, accessing a +/// property may trigger an assert that layout constraints were violated. +typedef T ComputePropertyValueCallback(); + +/// Property with a [value] of type [T]. +/// +/// If the default `object.toString()` does not provide an adequate description +/// of the object, specify `description` defining a custom description. +/// * `hidden` specifies whether the property should be hidden. +/// * `showSeparator` indicates whether a separator should be placed +/// between the property `name` and `object`. +class DiagnosticsProperty extends DiagnosticsNode { + DiagnosticsProperty( + String name, + T value, { + String description, + bool hidden: false, + this.ifNull, + this.ifEmpty, + bool showName: true, + bool showSeparator: true, + this.defaultValue: kNoDefaultValue, + this.tooltip, + DiagnosticsTreeStyle style : DiagnosticsTreeStyle.singleLine, + }) : _description = description, + _valueComputed = true, + _value = value, + _computeValue = null, + _hidden = hidden, + super( + name: name, + showName: showName, + showSeparator: showSeparator, + style: style, + ); + + /// Property with a [value] that is computed only when needed. + /// + /// Use if computing the property [value] may throw an exception or is + /// expensive. + DiagnosticsProperty.lazy( + String name, + ComputePropertyValueCallback computeValue, { + String description, + bool hidden: false, + this.ifNull, + this.ifEmpty, + bool showName: true, + bool showSeparator: true, + this.defaultValue: kNoDefaultValue, + this.tooltip, + DiagnosticsTreeStyle style : DiagnosticsTreeStyle.singleLine, + }) : _description = description, + _valueComputed = false, + _value = null, + _computeValue = computeValue, + _hidden = hidden, + super( + name: name, + showName: showName, + showSeparator: showSeparator, + style: style, + ); + + final String _description; + + /// Returns a string representation of the property value. + /// + /// Subclasses should override this method instead of [description] to + /// customize how property values are converted to strings. + /// + /// Overriding this method ensures that behavior controlling how property + /// values are decorated to generate a nice description are consistent across + /// all implementations. Debugging tools may also choose to use + /// [valueToString] directly instead of [description]. + String valueToString() => value.toString(); + + @override + String get description { + if (_description != null) + return addTooltip(_description); + + if (exception != null) + return 'EXCEPTION (${exception.runtimeType})'; + + if (ifNull != null && object == null) + return addTooltip(ifNull); + + String result = valueToString(); + if (result.isEmpty && ifEmpty != null) + result = ifEmpty; + return addTooltip(result); + } + + String addTooltip(String text) { + return tooltip == null ? text : '$text ($tooltip)'; + } + + /// Description if the property [value] is null. + final String ifNull; + + /// Description if the property description would otherwise be empty. + final String ifEmpty; + + /// Optional tooltip typically describing the property. + /// + /// Example tooltip: 'physical pixels per logical pixel' + /// + /// If present, the tooltip is added in parenthesis after the raw value when + /// generating the string description. + final String tooltip; + + Type get propertyType => T; + + /// Returns the value of the property either from cache or by invoking a + /// [ComputePropertyValueCallback]. + /// + /// If an exception is thrown invoking the [ComputePropertyValueCallback], + /// [value] returns `null` and the exception thrown can be found via the + /// [exception] property. + /// + /// See also: + /// + /// * [valueToString], which converts the property value to a string. + T get value { + _maybeCacheValue(); + return _value; + } + + T _value; + + bool _valueComputed; + + @override + T get object => value; + + Object _exception; + + /// Exception thrown if accessing the property [value] threw an exception. + /// + /// Returns null if computing the property value did not throw an exception. + Object get exception { + _maybeCacheValue(); + return _exception; + } + + void _maybeCacheValue() { + if (_valueComputed) + return; + + _valueComputed = true; + assert(_computeValue != null); + try { + _value = _computeValue(); + } catch (exception) { + _exception = exception; + _value = null; + } + } + + final Object defaultValue; + + final bool _hidden; + + @override + bool get hidden { + if (_hidden) + return true; + + if (defaultValue != kNoDefaultValue) { + if (exception != null) + return false; + + return object == defaultValue; + } + return false; + } + + final ComputePropertyValueCallback _computeValue; + + @override + List getProperties() => []; + + @override + List getChildren() => []; +} + +/// Add additional properties describing an object. +/// +/// See also: +/// +/// * [TreeDiagnosticsMixin.debugFillProperties], which lists best practices +/// for specifying properties. +typedef void FillPropertiesCallback(List properties); + +/// Returns a list of [DiagnosticsNode] objects describing an object's children. +/// +/// See also: +/// +/// * [TreeDiagnosticsMixin.debugDescribeChildren], which lists best practices +/// for describing children. +typedef List GetChildrenCallback(); + +class _LazyMembersDiagnosticsNode extends DiagnosticsNode { + _LazyMembersDiagnosticsNode({ + @required String name, + @required String description, + @required this.object, + GetChildrenCallback getChildren, + FillPropertiesCallback fillProperties, + String emptyBodyDescription, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.sparse, + }) : _description = description, + _getChildren = getChildren, + _fillProperties = fillProperties, + super( + name: name, + style: style, + emptyBodyDescription: emptyBodyDescription, + ); + + @override + final Object object; + + final GetChildrenCallback _getChildren; + final FillPropertiesCallback _fillProperties; + + final String _description; + + @override + bool get hidden => false; + + @override + String get description => _description ?? object.toString(); + + @override + List getProperties() { + final List properties = []; + if (_fillProperties != null) + _fillProperties(properties); + return properties; + } + + @override + List getChildren() { + return _getChildren != null ? _getChildren() : []; + } +} + +/// [DiagnosticsNode] for an instance of [TreeDiagnosticsMixin]. +class _TreeDiagnosticsMixinNode extends DiagnosticsNode { + @override + final TreeDiagnosticsMixin object; + + _TreeDiagnosticsMixinNode({ + String name, + this.object, + DiagnosticsTreeStyle style, + }) : super( + name: name, + style: style, + ); + + @override + List getProperties() { + final List description = []; + if (object != null) + object.debugFillProperties(description); + return description; + } + + @override + List getChildren() { + if (object != null) + return object.debugDescribeChildren(); + return []; + } + + @override + String get description => object.toString(); + + @override bool get hidden => false; +} + /// Returns a 5 character long hexadecimal string generated from /// Object.hashCode's 20 least-significant bits. String shortHash(Object object) { @@ -21,14 +1601,14 @@ String describeIdentity(Object object) => /// /// Strips off the enum class name from the `enumEntry.toString()`. /// -/// For example: +/// ## Sample code /// /// ```dart /// enum Day { /// monday, tuesday, wednesday, thursday, friday, saturday, sunday /// } /// -/// main() { +/// validateDescribeEnum() { /// assert(Day.monday.toString() == 'Day.monday'); /// assert(describeEnum(Day.monday) == 'monday'); /// } @@ -40,8 +1620,81 @@ String describeEnum(Object enumEntry) { return description.substring(indexOfDot + 1); } -/// A mixin that helps dump string representations of trees. -abstract class TreeDiagnosticsMixin { +/// Returns a lowercase hyphen-separated version of a camel case name. +/// +/// ## Sample code +/// +/// ```dart +/// validateCamelCaseToHyphenatedName() { +/// assert(camelCaseToHyphenatedName('deferToChild') == 'defer-to-child'); +/// assert(camelCaseToHyphenatedName('Monday') == 'monday'); +/// assert(camelCaseToHyphenatedName('monday') == 'monday'); +/// } +/// ``` +String camelCaseToHyphenatedName(String word) { + final String lowerWord = word.toLowerCase(); + if (word == lowerWord) + return word; + + final StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < word.length; i++) { + final String lower = lowerWord[i]; + if (word[i] != lower && i > 0) + buffer.write('-'); + buffer.write(lower); + } + return buffer.toString(); +} + +/// An interface providing string and [DiagnosticNode] debug representations. +/// +/// The string debug representation is generated from the intermediate +/// [DiagnosticNode] representation. The [DiagnosticNode] representation is +/// also used by debugging tools displaying interactive trees of objects and +/// properties. +/// +/// See also: +/// +/// * [TreeDiagnosticsMixin], which should be used to implement this interface +/// in all contexts where a mixin can be used. +/// * [TreeDiagnosticsMixin.debugFillProperties], which lists best practices +/// for specifying the properties of a [DiagnosticNode]. The most common use +/// case is to override [debugFillProperties] defining custom properties for +/// a subclass of [TreeDiagnosticsMixin] using the existing +/// [DiagnosticsProperty] subclasses. +/// * [TreeDiagnosticsMixin.debugDescribeChildren], which lists best practices +/// for describing the children of a [DiagnosticNode]. Typically the base +/// class already describes the children of a node properly or a node has +/// no children. +/// * [DiagnosticsProperty], which should be used to create leaf diagnostic +/// nodes without properties or children. There are many [DiagnosticProperty] +/// subclasses to handle common use cases. +/// * [DiagnosticsNode.lazy], which should be used to create a DiagnosticNode +/// with children and properties where [TreeDiagnosticsMixin] cannot be used. +abstract class TreeDiagnostics { + const TreeDiagnostics(); + + /// The [toStringDeep] method takes arguments, but those are intended for + /// internal use when recursing to the descendants, and so can be ignored. + /// + /// See also: + /// + /// * [toString], for a brief description of the object but not its children. + /// * [TreeDiagnosticsMixin.toStringShallow], for a detailed description of + /// the object but not its children. + String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { + return toDiagnosticsNode().toStringDeep(prefixLineOne, prefixOtherLines); + } + + DiagnosticsNode toDiagnosticsNode({ String name, DiagnosticsTreeStyle style }); +} + +/// A mixin that helps dump string and [DiagnosticsNode] representations of +/// trees. +/// +/// Use this class to implement [TreeDiagnostics] any time it is possible to use +/// mixins. +abstract class TreeDiagnosticsMixin implements TreeDiagnostics { // This class is intended to be used as a mixin, and should not be // extended directly. factory TreeDiagnosticsMixin._() => null; @@ -58,11 +1711,11 @@ abstract class TreeDiagnosticsMixin { /// Returns a one-line detailed description of the object. /// - /// This description includes everything from [debugFillDescription], but does - /// not recurse to any children. + /// This description is often somewhat long. This includes the same + /// information given by [toStringDeep], but does not recurse to any children. /// /// The [toStringShallow] method can take an argument, which is the string to - /// place between each part obtained from [debugFillDescription]. Passing a + /// place between each part obtained from [debugFillProperties]. Passing a /// string such as `'\n '` will result in a multiline string that indents the /// properties of the object below its name (as per [toString]). /// @@ -74,17 +1727,16 @@ abstract class TreeDiagnosticsMixin { final StringBuffer result = new StringBuffer(); result.write(toString()); result.write(joiner); - final List description = []; - debugFillDescription(description); - result.write(description.join(joiner)); + final List properties = []; + debugFillProperties(properties); + result.write( + properties.where((DiagnosticsNode n) => !n.hidden).join(joiner), + ); return result.toString(); } /// Returns a string representation of this node and its descendants. /// - /// This includes the information from [debugFillDescription], and then - /// recurses into the children using [debugDescribeChildren]. - /// /// The [toStringDeep] method takes arguments, but those are intended for /// internal use when recursing to the descendants, and so can be ignored. /// @@ -93,33 +1745,265 @@ abstract class TreeDiagnosticsMixin { /// * [toString], for a brief description of the object but not its children. /// * [toStringShallow], for a detailed description of the object but not its /// children. + @override String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { - String result = '$prefixLineOne$this\n'; - final String childrenDescription = debugDescribeChildren(prefixOtherLines); - final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines '; - final List description = []; - debugFillDescription(description); - result += description - .expand((String description) => debugWordWrap(description, 65, wrapIndent: ' ')) - .map((String line) => "$descriptionPrefix$line\n") - .join(); - if (childrenDescription == '') { - final String prefix = prefixOtherLines.trimRight(); - if (prefix != '') - result += '$prefix\n'; - } else { - result += childrenDescription; - } - return result; + return toDiagnosticsNode().toStringDeep(prefixLineOne, prefixOtherLines); } - /// Add additional information to the given description for use by - /// [toStringDeep] and [toStringShallow]. + @override + DiagnosticsNode toDiagnosticsNode({ String name, DiagnosticsTreeStyle style }) { + return new _TreeDiagnosticsMixinNode( + name: name, + object: this, + style: style, + ); + } + + /// Add additional properties associated with the node. + /// + /// Use the most specific [DiagnosticsProperty] existing subclass to describe + /// each property instead of the [DiagnosticsProperty] base class. There are + /// only a small number of [DiagnosticProperty] subclasses each covering a + /// common use case. Consider what values a property is relevant for users + /// debugging as users debugging large trees are overloaded with information. + /// Common named parameters in [DiagnosticNode] subclasses help filter when + /// and how properties are displayed. + /// + /// `defaultValue`, `showName`, `showSeparator`, and `hidden` keep string + /// representations of diagnostics terse and hide properties when they are not + /// very useful. + /// + /// * Use `defaultValue` any time the default value of a property is + /// uninteresting. For example, specify a default value of `null` any time + /// a property being `null` does not indicate an error. + /// * Avoid specifying the `hidden` parameter unless the result you want + /// cannot be be achieved by using the `defaultValue` parameter or using + /// the [ObjectFlagProperty] class to conditionally display the property + /// as a flag. + /// * Specify `showName` and `showSeparator` in rare cases where the string + /// output would look clumsy if they were not set. + /// ```dart + /// new DiagnosticsProperty('child(3, 4)', null, ifNull: 'is null', showSeparator: false).toString() + /// ``` + /// Shows using `showSeparator` to get output `child(3, 4) is null` which + /// is more polished than `child(3, 4): is null`. + /// ```dart + /// new DiagnosticsProperty('icon', icon, ifNull: '', showName: false)).toString() + /// ``` + /// Shows using `showName` to omit the property name as in this context the + /// property name does not add useful information. + /// + /// `ifNull`, `ifEmpty`, `unit`, and `tooltip` make property + /// descriptions clearer. The examples in the code sample below illustrate + /// good uses of all of these parameters. + /// + /// ## DiagnosticProperty subclasses for primitive types + /// + /// * [StringProperty], which supports automatically enclosing a [String] + /// value in quotes. + /// * [DoubleProperty], which supports specifying a unit of measurement for + /// a [double] value. + /// * [PercentProperty], which clamps a [double] to between 0 and 1 and + /// formats it as a percentage. + /// * [IntProperty], which supports specifying a unit of measurement for an + /// [int] value. + /// * [FlagProperty], which formats a [bool] value as one or more flags. + /// Depending on the use case it is better to format a bool as + /// `DiagnosticProperty` instead of using [FlagProperty] as the + /// output is more verbose but unambiguous. + /// + /// ## Other important [DiagnosticProperty] subclasses + /// + /// * [EnumProperty], which provides terse descriptions of enum values + /// working around limitations of the `toString` implementation for Dart + /// enum types. + /// * [IterableProperty], which handles iterable values with display + /// customizable depending on the [DiagnosticsTreeStyle] used. + /// * [LazyDiagnosticsProperty], which handles properties where computing the + /// value could throw an exception. + /// * [ObjectFlagProperty], which provides terse descriptions of whether a + /// property value is present or not. For example, whether an `onClick` + /// callback is specified or an animation is in progress. + /// + /// If none of these subclasses apply, use the [DiagnosticProperty] + /// constructor or in rare cases create your own [DiagnosticsProperty] + /// subclass as in the case for [TransformProperty] which handles [Matrix4] + /// that represent transforms. Generally any property value with a good + /// `toString` method implementation works fine using [DiagnosticProperty] + /// directly. + /// + /// ## Sample code + /// + /// This example shows best practices for implementing [debugFillProperties] + /// illustrating use of all common [DiagnosticProperty] subclasses and all + /// common [DiagnosticsProperty] parameters. + /// + /// ```dart + /// abstract class ExampleObject extends Object with TreeDiagnosticsMixin { + /// @override + /// void debugFillProperties(List description) { + /// // Always add properties from the base class first. + /// super.debugFillProperties(description); + /// + /// // Omit the property name 'message' when displaying this String property + /// // as it would just add visual noise. + /// description.add(new StringProperty('message', message, showName: false)); + /// + /// description.add(new DoubleProperty('stepWidth', stepWidth)); + /// + /// // A scale of 1.0 does nothing so should be hidden. + /// description.add(new DoubleProperty('scale', scale, defaultValue: 1.0)); + /// + /// // If the hitTestExtent matches the paintExtent, it is just set to its + /// // default value so is not relevant. + /// description.add(new DoubleProperty('hitTestExtent', hitTestExtent, defaultValue: paintExtent)); + /// + /// // maxWidth of double.INFINITY indicates the width is unconstrained and + /// // so maxWidth has no impact., + /// description.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: double.INFINITY)); + /// + /// // Progress is a value between 0 and 1 or null. Showing it as a + /// // percentage makes the meaning clear enough that the name can be + /// // hidden. + /// description.add(new PercentProperty( + /// 'progress', + /// progress, + /// showName: false, + /// ifNull: '', + /// )); + /// + /// // Most text fields have maxLines set to 1. + /// description.add(new IntProperty('maxLines', maxLines, defaultValue: 1)); + /// + /// // Specify the unit as otherwise it would be unclear that time is in + /// // milliseconds. + /// description.add(new IntProperty('duration', duration.inMilliseconds, unit: 'ms')); + /// + /// // Tooltip is used instead of unit for this case as a unit should be a + /// // terse description appropriate to display directly after a number + /// // without a space. + /// description.add(new DoubleProperty( + /// 'device pixel ratio', + /// ui.window.devicePixelRatio, + /// tooltip: 'physical pixels per logical pixel', + /// )); + /// + /// // Displaying the depth value would be distracting. Instead only display + /// // if the depth value is missing. + /// description.add(new ObjectFlagProperty('depth', depth, ifNull: 'no depth')); + /// + /// // bool flag that is only shown when the value is true. + /// description.add(new FlagProperty('using primary controller', value: primary)); + /// + /// description.add(new FlagProperty( + /// 'isCurrent', + /// value: isCurrent, + /// ifTrue: 'active', + /// ifFalse: 'inactive', + /// showName: false, + /// )); + /// + /// description.add(new DiagnosticsProperty('keepAlive', keepAlive)); + /// + /// // FlagProperty could have also been used in this case. + /// // This option results in the text "obscureText: true" instead + /// // of "obscureText" which is a bit more verbose but a bit clearer. + /// description.add(new DiagnosticsProperty('obscureText', obscureText, defaultValue: false)); + /// + /// description.add(new EnumProperty('textAlign', textAlign, defaultValue: null)); + /// description.add(new EnumProperty('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); + /// + /// // Warn users when the widget is missing but do not show the value. + /// description.add(new ObjectFlagProperty('widget', widget, ifNull: 'no widget')); + /// + /// description.add(new IterableProperty( + /// 'boxShadow', + /// boxShadow, + /// defaultValue: null, + /// style: style, + /// )); + /// + /// // Getting the value of size throws an exception unless hasSize is true. + /// description.add(new DiagnosticsProperty.lazy( + /// 'size', + /// () => size, + /// description: '${ hasSize ? size : "MISSING" }', + /// )); + /// + /// // If the `toString` method for the property value does not provide a + /// // good terse description, write a DiagnosticsProperty subclass as in + /// // the case of TransformProperty which displays a nice debugging view + /// // of a Matrix4 that represents a transform. + /// description.add(new TransformProperty('transform', transform)); + /// + /// // If the value class has a good `toString` method, use + /// // DiagnosticsProperty. Specifying the value type ensures + /// // that debugging tools always know the type of the field and so can + /// // provide the right UI affordances. For example, in this case even + /// // if color is null, a debugging tool still knows the value is a Color + /// // and can display relevant color related UI. + /// description.add(new DiagnosticsProperty('color', color)); + /// + /// // Use a custom description to generate a more terse summary than the + /// // `toString` method on the map class. + /// description.add(new DiagnosticsProperty>( + /// 'handles', + /// handles, + /// description: handles != null ? + /// '${handles.length} active client${ handles.length == 1 ? "" : "s" }' : + /// null, + /// ifNull: 'no notifications ever received', + /// showName: false, + /// )); + /// } + /// + /// String message; + /// double stepWidth; + /// double scale; + /// double paintExtent; + /// double hitTestExtent; + /// double paintExtend; + /// double maxWidth; + /// bool primary; + /// double progress; + /// int maxLines; + /// Duration duration; + /// int depth; + /// dynamic boxShadow; + /// dynamic style; + /// bool hasSize; + /// Matrix4 transform; + /// Map handles; + /// Color color; + /// bool obscureText; + /// ImageRepeat repeat; + /// Size size; + /// Widget widget; + /// bool isCurrent; + /// bool keepAlive; + /// TextAlign textAlign; + /// } + /// ``` + /// + /// Used by [toStringDeep], [toDiagnosticsNode] and [toStringShallow]. @protected @mustCallSuper - void debugFillDescription(List description) { } + void debugFillProperties(List properties) { } - /// Returns a description of this node's children for use by [toStringDeep]. + /// Returns a list of [DiagnosticsNode] objects describing this node's + /// children. + /// + /// Children that are offstage should added with `style` + /// [DiagnosticsTreeStyle.offstage] to indicate that they are offstage. + /// + /// See also: + /// + /// * [RenderTable.debugDescribeChildren], which provides high quality custom + /// descriptions for child nodes. + /// + /// Used by [toStringDeep], [toDiagnosticsNode] and [toStringShallow]. @protected - String debugDescribeChildren(String prefix) => ''; + List debugDescribeChildren() { + return []; + } } diff --git a/packages/flutter/lib/src/material/button.dart b/packages/flutter/lib/src/material/button.dart index da1e9dc5ce..c30e227810 100644 --- a/packages/flutter/lib/src/material/button.dart +++ b/packages/flutter/lib/src/material/button.dart @@ -249,10 +249,9 @@ class MaterialButton extends StatefulWidget { _MaterialButtonState createState() => new _MaterialButtonState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (!enabled) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('enabled', value: enabled, ifFalse: 'disabled')); } } diff --git a/packages/flutter/lib/src/material/icon_button.dart b/packages/flutter/lib/src/material/icon_button.dart index a301190827..22c1ea5ad9 100644 --- a/packages/flutter/lib/src/material/icon_button.dart +++ b/packages/flutter/lib/src/material/icon_button.dart @@ -203,12 +203,10 @@ class IconButton extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$icon'); - if (onPressed == null) - description.add('disabled'); - if (tooltip != null) - description.add('tooltip: "$tooltip"'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('icon', icon, showName: false)); + description.add(new ObjectFlagProperty('onPressed', onPressed, ifNull: 'disabled')); + description.add(new StringProperty('tooltip', tooltip, defaultValue: null, quoted: false)); } } diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index d27ebb3d12..b004b230b5 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -222,8 +222,8 @@ class InkResponse extends StatefulWidget { _InkResponseState createState() => new _InkResponseState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); final List gestures = []; if (onTap != null) gestures.add('tap'); @@ -233,8 +233,14 @@ class InkResponse extends StatefulWidget { gestures.add('long press'); if (gestures.isEmpty) gestures.add(''); - description.add('gestures: ${gestures.join(", ")}'); - description.add('${containedInkWell ? "clipped to " : ""}$highlightShape'); + description.add(new IterableProperty('gestures', gestures)); + description.add(new DiagnosticsProperty('containedInkWell', containedInkWell, hidden: true)); + description.add(new DiagnosticsProperty( + 'highlightShape', + highlightShape, + description: '${containedInkWell ? "clipped to " : ""}$highlightShape', + showName: false, + )); } } diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index 0e53d08425..3fac8fc881 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -372,12 +372,12 @@ class InputDecorator extends StatelessWidget { final Widget child; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('decoration: $decoration'); - description.add('baseStyle: $baseStyle'); - description.add('isFocused: $isFocused'); - description.add('isEmpty: $isEmpty'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('decoration', decoration)); + description.add(new EnumProperty('baseStyle', baseStyle)); + description.add(new DiagnosticsProperty('isFocused', isFocused)); + description.add(new DiagnosticsProperty('isEmpty', isEmpty)); } Color _getActiveColor(ThemeData themeData) { @@ -615,9 +615,9 @@ class _AnimatedLabel extends ImplicitlyAnimatedWidget { _AnimatedLabelState createState() => new _AnimatedLabelState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - '$style'.split('\n').forEach(description.add); + void debugFillProperties(List description) { + super.debugFillProperties(description); + style?.debugFillProperties(description); } } diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index 39fc0bde05..a9f55e2fc4 100644 --- a/packages/flutter/lib/src/material/material.dart +++ b/packages/flutter/lib/src/material/material.dart @@ -175,18 +175,13 @@ class Material extends StatefulWidget { _MaterialState createState() => new _MaterialState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$type'); - description.add('elevation: ${elevation.toStringAsFixed(1)}'); - if (color != null) - description.add('color: $color'); - if (textStyle != null) { - for (String entry in '$textStyle'.split('\n')) - description.add('textStyle.$entry'); - } - if (borderRadius != null) - description.add('borderRadius: $borderRadius'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('type', type)); + description.add(new DoubleProperty('elevation', elevation)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); + textStyle?.debugFillProperties(description, prefix: 'textStyle.'); + description.add(new EnumProperty('borderRadius', borderRadius, defaultValue: null)); } /// The default radius of an ink splash in logical pixels. diff --git a/packages/flutter/lib/src/material/progress_indicator.dart b/packages/flutter/lib/src/material/progress_indicator.dart index 58043daf4b..a1638b6936 100644 --- a/packages/flutter/lib/src/material/progress_indicator.dart +++ b/packages/flutter/lib/src/material/progress_indicator.dart @@ -4,6 +4,7 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'material.dart'; @@ -60,13 +61,9 @@ abstract class ProgressIndicator extends StatefulWidget { Color _getValueColor(BuildContext context) => valueColor?.value ?? Theme.of(context).accentColor; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (value != null) { - description.add('${(value.clamp(0.0, 1.0) * 100.0).toStringAsFixed(1)}%'); - } else { - description.add(''); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new PercentProperty('value', value, showName: false, ifNull: '')); } } diff --git a/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index 5cc935716c..40eb082834 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -161,11 +161,11 @@ class Slider extends StatefulWidget { _SliderState createState() => new _SliderState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value.toStringAsFixed(1)}'); - description.add('min: $min'); - description.add('max: $max'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('value', value)); + description.add(new DoubleProperty('min', min)); + description.add(new DoubleProperty('max', max)); } } diff --git a/packages/flutter/lib/src/material/switch.dart b/packages/flutter/lib/src/material/switch.dart index 0cc4f1b72f..34379536f2 100644 --- a/packages/flutter/lib/src/material/switch.dart +++ b/packages/flutter/lib/src/material/switch.dart @@ -99,11 +99,10 @@ class Switch extends StatefulWidget { _SwitchState createState() => new _SwitchState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value ? "on" : "off"}'); - if (onChanged == null) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true)); + description.add(new ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); } } diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 9760e9d6ef..871401109c 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -89,12 +89,10 @@ class Tab extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (text != null) - description.add('text: $text'); - if (icon != null) - description.add('icon: $icon'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('text', text, defaultValue: null)); + description.add(new DiagnosticsProperty('icon', icon, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/material/text_field.dart b/packages/flutter/lib/src/material/text_field.dart index 69852b1afa..01e9d77ac2 100644 --- a/packages/flutter/lib/src/material/text_field.dart +++ b/packages/flutter/lib/src/material/text_field.dart @@ -176,25 +176,17 @@ class TextField extends StatefulWidget { _TextFieldState createState() => new _TextFieldState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (controller != null) - description.add('controller: $controller'); - if (focusNode != null) - description.add('focusNode: $focusNode'); - description.add('decoration: $decoration'); - if (keyboardType != TextInputType.text) - description.add('keyboardType: $keyboardType'); - if (style != null) - description.add('style: $style'); - if (autofocus) - description.add('autofocus: $autofocus'); - if (obscureText) - description.add('obscureText: $obscureText'); - if (autocorrect) - description.add('autocorrect: $autocorrect'); - if (maxLines != 1) - description.add('maxLines: $maxLines'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('controller', controller, defaultValue: null)); + description.add(new DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); + description.add(new DiagnosticsProperty('decoration', decoration)); + description.add(new EnumProperty('keyboardType', keyboardType, defaultValue: TextInputType.text)); + description.add(new DiagnosticsProperty('style', style, defaultValue: null)); + description.add(new DiagnosticsProperty('autofocus', autofocus, defaultValue: false)); + description.add(new DiagnosticsProperty('obscureText', obscureText, defaultValue: false)); + description.add(new DiagnosticsProperty('autocorrect', autocorrect, defaultValue: false)); + description.add(new IntProperty('maxLines', maxLines, defaultValue: 1)); } } diff --git a/packages/flutter/lib/src/material/theme.dart b/packages/flutter/lib/src/material/theme.dart index c036033cba..9d8f97cdbf 100644 --- a/packages/flutter/lib/src/material/theme.dart +++ b/packages/flutter/lib/src/material/theme.dart @@ -138,9 +138,9 @@ class Theme extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$data'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('data', data, showName: false)); } } @@ -235,9 +235,8 @@ class _AnimatedThemeState extends AnimatedWidgetBaseState { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (_data != null) - description.add('$_data'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('data', _data, showName: false, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/material/toggleable.dart b/packages/flutter/lib/src/material/toggleable.dart index 6d65025eeb..f34db9fce7 100644 --- a/packages/flutter/lib/src/material/toggleable.dart +++ b/packages/flutter/lib/src/material/toggleable.dart @@ -303,10 +303,9 @@ abstract class RenderToggleable extends RenderConstrainedBox implements Semantic } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('value: ${value ? "checked" : "unchecked"}'); - if (!isInteractive) - description.add('disabled'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('value', value: value, ifTrue: 'checked', ifFalse: 'unchecked', showName: true)); + description.add(new FlagProperty('isInteractive', value: isInteractive, ifTrue: 'enabled', ifFalse: 'disabled', defaultValue: true)); } } diff --git a/packages/flutter/lib/src/material/tooltip.dart b/packages/flutter/lib/src/material/tooltip.dart index d131d73cdc..1883784eb0 100644 --- a/packages/flutter/lib/src/material/tooltip.dart +++ b/packages/flutter/lib/src/material/tooltip.dart @@ -86,11 +86,11 @@ class Tooltip extends StatefulWidget { _TooltipState createState() => new _TooltipState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('"$message"'); - description.add('vertical offset: $verticalOffset'); - description.add('position: ${preferBelow ? "below" : "above"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('message', message, showName: false)); + description.add(new DoubleProperty('vertical offset', verticalOffset)); + description.add(new FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true)); } } diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index 6df8d4f45b..e7f0274129 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -1601,38 +1601,24 @@ class BoxDecoration extends Decoration { ); } - /// Stringifies the BoxDecoration. By default, the output will be on one line. - /// If the method is passed a non-empty string argument, then the output will - /// span multiple lines, each prefixed by that argument. @override - String toString([String prefix = '', String indentPrefix]) { - final List result = []; - if (color != null) - result.add('${prefix}color: $color'); - if (image != null) - result.add('${prefix}image: $image'); - if (border != null) - result.add('${prefix}border: $border'); - if (borderRadius != null) - result.add('${prefix}borderRadius: $borderRadius'); - if (boxShadow != null) { - if (indentPrefix != null && boxShadow.length > 1) { - result.add('${prefix}boxShadow:'); - for (BoxShadow shadow in boxShadow) - result.add('$indentPrefix$shadow'); - } else { - result.add('${prefix}boxShadow: ${boxShadow.map((BoxShadow shadow) => shadow.toString()).join(", ")}'); - } - } - if (gradient != null) - result.add('${prefix}gradient: $gradient'); - if (shape != BoxShape.rectangle) - result.add('${prefix}shape: $shape'); - if (prefix == '') - return '$runtimeType(${result.join(', ')})'; - if (result.isEmpty) - return '$prefix'; - return result.join('\n'); + DiagnosticsNode toDiagnosticsNode({ String name, DiagnosticsTreeStyle style: DiagnosticsTreeStyle.whitespace }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + description: '', + style: style, + emptyBodyDescription: '', + fillProperties: (List properties) { + properties.add(new DiagnosticsProperty('color', color, defaultValue: null)); + properties.add(new DiagnosticsProperty('image', image, defaultValue: null)); + properties.add(new DiagnosticsProperty('border', border, defaultValue: null)); + properties.add(new DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); + properties.add(new IterableProperty('boxShadow', boxShadow, defaultValue: null, style: style)); + properties.add(new DiagnosticsProperty('gradient', gradient, defaultValue: null)); + properties.add(new EnumProperty('shape', shape, defaultValue: BoxShape.rectangle)); + }, + ); } @override diff --git a/packages/flutter/lib/src/painting/decoration.dart b/packages/flutter/lib/src/painting/decoration.dart index 9507984b09..0e0a6e290f 100644 --- a/packages/flutter/lib/src/painting/decoration.dart +++ b/packages/flutter/lib/src/painting/decoration.dart @@ -25,7 +25,7 @@ export 'edge_insets.dart' show EdgeInsets; /// shared between boxes; [BoxPainter] objects can cache resources to /// make painting on a particular surface faster. @immutable -abstract class Decoration { +abstract class Decoration extends TreeDiagnostics { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const Decoration(); @@ -81,16 +81,10 @@ abstract class Decoration { /// if it is a [BoxDecoration] with definitely no [DecorationImage]). BoxPainter createBoxPainter([VoidCallback onChanged]); - /// Returns a string representation of this object. - /// - /// Every line of the output should be prefixed by `prefix`. - /// - /// If `indentPrefix` is non-null, then the description can be further split - /// into sublines, and each subline should be prefixed with `indentPrefix` - /// (rather that `prefix`). This is used, for example, by [BoxDecoration] for - /// the otherwise quite verbose [BoxShadow] descriptions. @override - String toString([String prefix = '', String indentPrefix ]) => '$prefix$runtimeType'; + String toString() { + return toDiagnosticsNode(style: DiagnosticsTreeStyle.singleLine).toStringDeep(); + } } /// A stateful class that can paint a particular [Decoration]. diff --git a/packages/flutter/lib/src/painting/flutter_logo.dart b/packages/flutter/lib/src/painting/flutter_logo.dart index 3652febb51..3927c757a5 100644 --- a/packages/flutter/lib/src/painting/flutter_logo.dart +++ b/packages/flutter/lib/src/painting/flutter_logo.dart @@ -7,6 +7,7 @@ import 'dart:typed_data'; import 'dart:ui' as ui show Gradient, TextBox, lerpDouble; import 'package:flutter/services.dart'; +import 'package:flutter/foundation.dart'; import 'basic_types.dart'; import 'box_fit.dart'; @@ -210,9 +211,19 @@ class FlutterLogoDecoration extends Decoration { } @override - String toString([String prefix = '', String prefixIndent ]) { - final String extra = _inTransition ? ', transition $_position:$_opacity' : ''; - return '$prefix$runtimeType($lightColor/$darkColor on $textColor, $style$extra)'; + DiagnosticsNode toDiagnosticsNode({ String name, DiagnosticsTreeStyle style }) { + return new DiagnosticsNode.lazy( + name: name, + description: '$runtimeType', + object: this, + style: style, + fillProperties: (List properties) { + properties.add(new DiagnosticsNode.message('$lightColor/$darkColor on $textColor')); + properties.add(new EnumProperty('style', this.style)); + if (_inTransition) + properties.add(new DiagnosticsNode.message('transition $_position:$_opacity')); + } + ); } } diff --git a/packages/flutter/lib/src/painting/text_span.dart b/packages/flutter/lib/src/painting/text_span.dart index 0738f3defb..81208fe45e 100644 --- a/packages/flutter/lib/src/painting/text_span.dart +++ b/packages/flutter/lib/src/painting/text_span.dart @@ -47,7 +47,7 @@ import 'text_style.dart'; /// * [RichText], a widget for finer control of text rendering. /// * [TextPainter], a class for painting [TextSpan] objects on a [Canvas]. @immutable -class TextSpan { +class TextSpan implements TreeDiagnostics { /// Creates a [TextSpan] with the given values. /// /// For the object to be useful, at least one of [text] or @@ -250,27 +250,7 @@ class TextSpan { @override String toString([String prefix = '']) { - final StringBuffer buffer = new StringBuffer(); - buffer.writeln('$prefix$runtimeType:'); - final String indent = '$prefix '; - if (style != null) - buffer.writeln(style.toString(indent)); - if (recognizer != null) - buffer.writeln('${indent}recognizer: ${recognizer.runtimeType}'); - if (text != null) - buffer.writeln('$indent"$text"'); - if (children != null) { - for (TextSpan child in children) { - if (child != null) { - buffer.write(child.toString(indent)); - } else { - buffer.writeln('$indent'); - } - } - } - if (style == null && text == null && children == null) - buffer.writeln('$indent(empty)'); - return buffer.toString(); + return toStringDeep(prefix, prefix); } /// In checked mode, throws an exception if the object is not in a @@ -337,6 +317,11 @@ class TextSpan { return result; } + @override + String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { + return toDiagnosticsNode().toStringDeep(prefixLineOne, prefixOtherLines); + } + @override bool operator ==(dynamic other) { if (identical(this, other)) @@ -352,4 +337,37 @@ class TextSpan { @override int get hashCode => hashValues(style, text, recognizer, hashList(children)); + @override + DiagnosticsNode toDiagnosticsNode({ + String name, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.whitespace, + }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + description: '$runtimeType', + style: style, + fillProperties: (List properties) { + // Properties on style are added as if they were properties directly on + // this TextSpan. + if (this.style != null) + this.style.debugFillProperties(properties); + + properties.add(new DiagnosticsProperty( + 'recognizer', recognizer, + description: recognizer?.runtimeType?.toString(), + defaultValue: null, + )); + + properties.add(new StringProperty('text', text, showName: false, defaultValue: null)); + if (this.style == null && text == null && children == null) + properties.add(new DiagnosticsNode.message('(empty)')); + }, + getChildren: () { + return children == null ? + [] : + children.map((TextSpan child) => child?.toDiagnosticsNode()).toList(); + }, + ); + } } diff --git a/packages/flutter/lib/src/painting/text_style.dart b/packages/flutter/lib/src/painting/text_style.dart index f260552372..2288f9cefc 100644 --- a/packages/flutter/lib/src/painting/text_style.dart +++ b/packages/flutter/lib/src/painting/text_style.dart @@ -131,7 +131,7 @@ import 'basic_types.dart'; /// * [TextSpan], the class that wraps a [TextStyle] for the purposes of /// passing it to a [RichText]. @immutable -class TextStyle { +class TextStyle extends TreeDiagnostics { /// Creates a text style. const TextStyle({ this.inherit: true, @@ -456,112 +456,100 @@ class TextStyle { } @override - String toString([String prefix = '']) { - final List result = []; - result.add('${prefix}inherit: $inherit'); - if (color != null) - result.add('${prefix}color: $color'); - if (fontFamily != null) - result.add('${prefix}family: "$fontFamily"'); - if (fontSize != null) - result.add('${prefix}size: $fontSize'); + DiagnosticsNode toDiagnosticsNode({ + String name, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.singleLine, + }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + style: style, + description: '$runtimeType', + fillProperties: debugFillProperties, + ); + } + + @override + String toString() => toDiagnosticsNode().toString(); + + /// Adds all properties prefixing property names with the optional `prefix`. + void debugFillProperties(List properties, { String prefix: '' }) { + final List styles = []; + styles.add(new DiagnosticsProperty('${prefix}color', color, defaultValue: null)); + styles.add(new StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false)); + styles.add(new DoubleProperty('${prefix}size', fontSize, defaultValue: null)); + String weightDescription; if (fontWeight != null) { switch (fontWeight) { case FontWeight.w100: - result.add('${prefix}weight: 100'); + weightDescription = '100'; break; case FontWeight.w200: - result.add('${prefix}weight: 200'); + weightDescription = '200'; break; case FontWeight.w300: - result.add('${prefix}weight: 300'); + weightDescription = '300'; break; case FontWeight.w400: - result.add('${prefix}weight: 400'); + weightDescription = '400'; break; case FontWeight.w500: - result.add('${prefix}weight: 500'); + weightDescription = '500'; break; case FontWeight.w600: - result.add('${prefix}weight: 600'); + weightDescription = '600'; break; case FontWeight.w700: - result.add('${prefix}weight: 700'); + weightDescription = '700'; break; case FontWeight.w800: - result.add('${prefix}weight: 800'); + weightDescription = '800'; break; case FontWeight.w900: - result.add('${prefix}weight: 900'); + weightDescription = '900'; break; } } - if (fontStyle != null) { - switch (fontStyle) { - case FontStyle.normal: - result.add('${prefix}style: normal'); - break; - case FontStyle.italic: - result.add('${prefix}style: italic'); - break; - } - } - if (letterSpacing != null) - result.add('${prefix}letterSpacing: ${letterSpacing}x'); - if (wordSpacing != null) - result.add('${prefix}wordSpacing: ${wordSpacing}x'); - if (textBaseline != null) { - switch (textBaseline) { - case TextBaseline.alphabetic: - result.add('${prefix}baseline: alphabetic'); - break; - case TextBaseline.ideographic: - result.add('${prefix}baseline: ideographic'); - break; - } - } - if (height != null) - result.add('${prefix}height: ${height}x'); + // TODO(jacobr): switch this to use enumProperty which will either cause the + // weight description to change to w600 from 600 or require existing + // enumProperty to handle this special case. + styles.add(new DiagnosticsProperty( + '${prefix}weight', + fontWeight, + description: weightDescription, + defaultValue: null, + )); + styles.add(new EnumProperty('${prefix}style', fontStyle, defaultValue: null)); + styles.add(new DoubleProperty('${prefix}letterSpacing', letterSpacing, unit: 'x', defaultValue: null)); + styles.add(new DoubleProperty('${prefix}wordSpacing', wordSpacing, unit: 'x', defaultValue: null)); + styles.add(new EnumProperty('${prefix}baseline', textBaseline, defaultValue: null)); + styles.add(new DoubleProperty('${prefix}height', height, unit: 'x', defaultValue: null)); if (decoration != null || decorationColor != null || decorationStyle != null) { - String decorationDescription = '${prefix}decoration: '; - bool haveDecorationDescription = false; - if (decorationStyle != null) { - switch (decorationStyle) { - case TextDecorationStyle.solid: - decorationDescription += 'solid'; - break; - case TextDecorationStyle.double: - decorationDescription += 'double'; - break; - case TextDecorationStyle.dotted: - decorationDescription += 'dotted'; - break; - case TextDecorationStyle.dashed: - decorationDescription += 'dashed'; - break; - case TextDecorationStyle.wavy: - decorationDescription += 'wavy'; - break; - } - haveDecorationDescription = true; - } - if (decorationColor != null) { - if (haveDecorationDescription) - decorationDescription += ' '; - decorationDescription += '$decorationColor'; - haveDecorationDescription = true; - } - if (decoration != null) { - if (haveDecorationDescription) - decorationDescription += ' '; - decorationDescription += '$decoration'; - haveDecorationDescription = true; - } - assert(haveDecorationDescription); - result.add(decorationDescription); + final List decorationDescription = []; + if (decorationStyle != null) + decorationDescription.add(describeEnum((decorationStyle))); + + // Hide decorationColor from the default text view as it is shown in the + // terse decoration summary as well. + styles.add(new DiagnosticsProperty('${prefix}decorationColor', decorationColor, defaultValue: null, hidden: true)); + + if (decorationColor != null) + decorationDescription.add('$decorationColor'); + + // Intentionally collide with the property 'decoration' added below. + // Tools that show hidden properties could choose the first property + // matching the name to disambiguate. + styles.add(new DiagnosticsProperty('${prefix}decoration', decoration, defaultValue: null, hidden: true)); + if (decoration != null) + decorationDescription.add('$decoration'); + assert(decorationDescription.isNotEmpty); + styles.add(new MessageProperty('${prefix}decoration', decorationDescription.join(' '))); } - if (result.isEmpty) - return '$prefix'; - return result.join('\n'); + + final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.hidden); + properties.add(new DiagnosticsProperty('${prefix}inherit', inherit, hidden: !styleSpecified && inherit)); + properties.addAll(styles); + if (!styleSpecified) + properties.add(new FlagProperty('inherit', value: inherit, ifTrue: '$prefix', ifFalse: '$prefix')); } } diff --git a/packages/flutter/lib/src/rendering/block.dart b/packages/flutter/lib/src/rendering/block.dart index 98c4bda2e4..dffd06f3c9 100644 --- a/packages/flutter/lib/src/rendering/block.dart +++ b/packages/flutter/lib/src/rendering/block.dart @@ -156,9 +156,9 @@ class RenderListBody extends RenderBox } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('mainAxis: $mainAxis'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('mainAxis', mainAxis)); } double _getIntrinsicCrossAxis(_ChildSizingFunction childSize) { diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 5f80fe9400..d023f2b91d 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -836,9 +836,8 @@ class _IntrinsicDimensionsCacheEntry { /// * Implement the [visitChildren] method such that it calls its argument for /// each child, typically in paint order (back-most to front-most). /// -/// * Implement [debugDescribeChildren] such that it outputs a string that -/// describes all the children. In principle, for each child you want to -/// include the results of that child's [toStringDeep] function. +/// * Implement [debugDescribeChildren] such that it outputs a [DiagnosticNode] +/// for each child. /// /// Implementing these seven bullet points is essentially all that the two /// aforementioned mixins do. @@ -1667,22 +1666,17 @@ abstract class RenderBox extends RenderObject { while (!node.constraints.hasBoundedWidth && node.parent is RenderBox) node = node.parent; information.writeln('The nearest ancestor providing an unbounded width constraint is:'); - information.writeln(' $node'); - final List description = []; - node.debugFillDescription(description); - for (String line in description) - information.writeln(' $line'); - } + information.write(' '); + information.writeln(node.toStringShallow('\n ')); + } 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.writeln(' $node'); - final List description = []; - node.debugFillDescription(description); - for (String line in description) - information.writeln(' $line'); + information.write(' '); + information.writeln(node.toStringShallow('\n ')); + } throw new FlutterError( '$runtimeType object was given an infinite size during layout.\n' @@ -2094,9 +2088,9 @@ abstract class RenderBox extends RenderObject { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('size: ${ hasSize ? size : "MISSING" }'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('size', _size, ifNull: 'MISSING')); } } diff --git a/packages/flutter/lib/src/rendering/debug.dart b/packages/flutter/lib/src/rendering/debug.dart index 42430a83a9..7e51d70315 100644 --- a/packages/flutter/lib/src/rendering/debug.dart +++ b/packages/flutter/lib/src/rendering/debug.dart @@ -156,7 +156,7 @@ bool debugProfilePaintsEnabled = false; /// Returns a list of strings representing the given transform in a format -/// useful for [RenderObject.debugFillDescription]. +/// useful for [TransformProperty]. /// /// If the argument is null, returns a list with the single string "null". List debugDescribeTransform(Matrix4 transform) { @@ -167,6 +167,20 @@ List debugDescribeTransform(Matrix4 transform) { return matrix; } +/// Property which handles [Matrix4] that represent transforms. +class TransformProperty extends DiagnosticsProperty { + TransformProperty(String name, Matrix4 value, { + Object defaultValue: kNoDefaultValue, + }) : super( + name, + value, + defaultValue: defaultValue, + ); + + @override + String valueToString() => debugDescribeTransform(value).join('\n'); +} + void _debugDrawDoubleRect(Canvas canvas, Rect outerRect, Rect innerRect, Color color) { final Path path = new Path() ..fillType = PathFillType.evenOdd diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index b28f39ddfa..cc43324dfe 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -546,22 +546,24 @@ class RenderEditable extends RenderBox { Rect describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('cursorColor: $cursorColor'); - description.add('showCursor: $showCursor'); - description.add('maxLines: $maxLines'); - description.add('selectionColor: $selectionColor'); - description.add('textScaleFactor: $textScaleFactor'); - description.add('selection: $selection'); - description.add('offset: $offset'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('cursorColor', cursorColor)); + description.add(new DiagnosticsProperty>('showCursor', showCursor)); + description.add(new IntProperty('maxLines', maxLines)); + description.add(new DiagnosticsProperty('selectionColor', selectionColor)); + description.add(new DoubleProperty('textScaleFactor', textScaleFactor)); + description.add(new DiagnosticsProperty('selection', selection)); + description.add(new DiagnosticsProperty('offset', offset)); } @override - String debugDescribeChildren(String prefix) { - return '$prefix \u2558\u2550\u2566\u2550\u2550 text \u2550\u2550\u2550\n' - '${text.toString("$prefix \u2551 ")}' // TextSpan includes a newline - '$prefix \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n' - '${prefix.trimRight()}\n'; + List debugDescribeChildren() { + return [ + text.toDiagnosticsNode( + name: 'text', + style: DiagnosticsTreeStyle.transition, + ), + ]; } } diff --git a/packages/flutter/lib/src/rendering/flex.dart b/packages/flutter/lib/src/rendering/flex.dart index e85650a5cd..76f9809b05 100644 --- a/packages/flutter/lib/src/rendering/flex.dart +++ b/packages/flutter/lib/src/rendering/flex.dart @@ -490,9 +490,9 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin description = []; - node.debugFillDescription(description); - for (String line in description) + final List description = []; + node.debugFillProperties(description); + for (DiagnosticsNode line in description) information.writeln(' $line'); } information.writeln('See also: https://flutter.io/layout/'); @@ -784,13 +784,13 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin description) { - super.debugFillDescription(description); - description.add('direction: $_direction'); - description.add('mainAxisAlignment: $_mainAxisAlignment'); - description.add('mainAxisSize: $_mainAxisSize'); - description.add('crossAxisAlignment: $_crossAxisAlignment'); - description.add('textBaseline: $_textBaseline'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('direction', _direction)); + description.add(new EnumProperty('mainAxisAlignment', _mainAxisAlignment)); + description.add(new EnumProperty('mainAxisSize', _mainAxisSize)); + description.add(new EnumProperty('crossAxisAlignment', _crossAxisAlignment)); + description.add(new EnumProperty('textBaseline', _textBaseline)); } } diff --git a/packages/flutter/lib/src/rendering/image.dart b/packages/flutter/lib/src/rendering/image.dart index 118fc5bc64..a61d88e7f4 100644 --- a/packages/flutter/lib/src/rendering/image.dart +++ b/packages/flutter/lib/src/rendering/image.dart @@ -259,26 +259,17 @@ class RenderImage extends RenderBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('image: $image'); - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); - if (scale != 1.0) - description.add('scale: $scale'); - if (color != null) - description.add('color: $color'); - if (colorBlendMode != null) - description.add('colorBlendMode: $colorBlendMode'); - if (fit != null) - description.add('fit: $fit'); - if (alignment != null) - description.add('alignment: $alignment'); - if (repeat != ImageRepeat.noRepeat) - description.add('repeat: $repeat'); - if (centerSlice != null) - description.add('centerSlice: $centerSlice'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('image', image)); + description.add(new DoubleProperty('width', width, defaultValue: null)); + description.add(new DoubleProperty('height', height, defaultValue: null)); + description.add(new DoubleProperty('scale', scale, defaultValue: 1.0)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); + description.add(new EnumProperty('colorBlendMode', colorBlendMode, defaultValue: null)); + description.add(new EnumProperty('fit', fit, defaultValue: null)); + description.add(new DiagnosticsProperty('alignment', alignment, defaultValue: null)); + description.add(new EnumProperty('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); + description.add(new DiagnosticsProperty('centerSlice', centerSlice, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index 3398cc5ec4..4ca295c469 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -105,12 +105,10 @@ abstract class Layer extends AbstractNode with TreeDiagnosticsMixin { String toString() => '${super.toString()}${ owner == null ? " DETACHED" : ""}'; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (parent == null && owner != null) - description.add('owner: $owner'); - if (debugCreator != null) - description.add('creator: $debugCreator'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('owner', owner, hidden: parent != null, defaultValue: null)); + description.add(new DiagnosticsProperty('creator', debugCreator, defaultValue: null)); } } @@ -164,9 +162,9 @@ class PictureLayer extends Layer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('paint bounds: $canvasBounds'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('paint bounds', canvasBounds)); } } @@ -414,24 +412,20 @@ class ContainerLayer extends Layer { } @override - String debugDescribeChildren(String prefix) { + List debugDescribeChildren() { + final List children = []; if (firstChild == null) - return ''; - final StringBuffer result = new StringBuffer() - ..write(prefix) - ..write(' \u2502\n'); + return children; Layer child = firstChild; int count = 1; - while (child != lastChild) { - result.write(child.toStringDeep("$prefix \u251C\u2500child $count: ", "$prefix \u2502")); + while (true) { + children.add(child.toDiagnosticsNode(name: 'child $count')); + if (child == lastChild) + break; count += 1; child = child.nextSibling; } - if (child != null) { - assert(child == lastChild); - result.write(child.toStringDeep("$prefix \u2514\u2500child $count: ", "$prefix ")); - } - return result.toString(); + return children; } } @@ -466,9 +460,9 @@ class OffsetLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('offset: $offset'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('offset', offset)); } } @@ -494,9 +488,9 @@ class ClipRectLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('clipRect: $clipRect'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('clipRect', clipRect)); } } @@ -522,9 +516,9 @@ class ClipRRectLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('clipRRect: $clipRRect'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('clipRRect', clipRRect)); } } @@ -550,9 +544,9 @@ class ClipPathLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('clipPath: $clipPath'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('clipPath', clipPath)); } } @@ -602,10 +596,9 @@ class TransformLayer extends OffsetLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('transform:'); - description.addAll(debugDescribeTransform(transform)); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new TransformProperty('transform', transform)); } } @@ -634,9 +627,9 @@ class OpacityLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alpha: $alpha'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new IntProperty('alpha', alpha)); } } @@ -674,11 +667,11 @@ class ShaderMaskLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('shader: $shader'); - description.add('maskRect: $maskRect'); - description.add('blendMode: $blendMode'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('shader', shader)); + description.add(new DiagnosticsProperty('maskRect', maskRect)); + description.add(new DiagnosticsProperty('blendMode', blendMode)); } } @@ -752,11 +745,11 @@ class PhysicalModelLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('clipRRect: $clipRRect'); - description.add('elevation: $elevation'); - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('clipRRect', clipRRect)); + description.add(new DoubleProperty('elevation', elevation)); + description.add(new DiagnosticsProperty('color', color)); } } @@ -778,7 +771,7 @@ class LayerLink { LeaderLayer _leader; @override - String toString() => '$runtimeType#$hashCode(${ _leader != null ? "" : "" })'; + String toString() => '${describeIdentity(this)}(${ _leader != null ? "" : "" })'; } /// A composited layer that can be followed by a [FollowerLayer]. @@ -861,10 +854,10 @@ class LeaderLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('offset: $offset'); - description.add('link: $link'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('offset', offset)); + description.add(new DiagnosticsProperty('link', link)); } } @@ -1050,12 +1043,9 @@ class FollowerLayer extends ContainerLayer { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('link: $link'); - if (_lastTransform != null) { - description.add('transform:'); - description.addAll(debugDescribeTransform(getLastTransform())); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('link', link)); + description.add(new TransformProperty('transform', getLastTransform(), defaultValue: null)); } } diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index d84ca71e43..c650e31155 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -17,7 +17,7 @@ import 'layer.dart'; import 'node.dart'; import 'semantics.dart'; -export 'package:flutter/foundation.dart' show FlutterError, InformationCollector; +export 'package:flutter/foundation.dart' show FlutterError, InformationCollector, DiagnosticsNode, DiagnosticsProperty, StringProperty, DoubleProperty, EnumProperty, IntProperty; export 'package:flutter/gestures.dart' show HitTestEntry, HitTestResult; export 'package:flutter/painting.dart'; @@ -1318,7 +1318,7 @@ class PipelineOwner { /// [RenderObject.markNeedsLayout] so that if a parent has queried the intrinsic /// or baseline information, it gets marked dirty whenever the child's geometry /// changes. -abstract class RenderObject extends AbstractNode implements HitTestTarget { +abstract class RenderObject extends AbstractNode with TreeDiagnosticsMixin implements HitTestTarget { /// Initializes internal fields for subclasses. RenderObject() { _needsCompositing = isRepaintBoundary || alwaysNeedsCompositing; @@ -2748,25 +2748,13 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget { /// Returns a description of the tree rooted at this node. /// If the prefix argument is provided, then every line in the output /// will be prefixed by that string. + @override String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { final RenderObject debugPreviousActiveLayout = _debugActiveLayout; _debugActiveLayout = null; - String result = '$prefixLineOne$this\n'; - final String childrenDescription = debugDescribeChildren(prefixOtherLines); - final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines '; - final List description = []; - debugFillDescription(description); - result += description - .expand((String description) => debugWordWrap(description, 65, wrapIndent: ' ')) - .map((String line) => "$descriptionPrefix$line\n") - .join(); - if (childrenDescription == '') { - final String prefix = prefixOtherLines.trimRight(); - if (prefix != '') - result += '$prefix\n'; - } else { - result += childrenDescription; - } + + final String result = super.toStringDeep(prefixLineOne, prefixOtherLines); + _debugActiveLayout = debugPreviousActiveLayout; return result; } @@ -2776,42 +2764,35 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget { /// /// This includes the same information for this RenderObject as given by /// [toStringDeep], but does not recurse to any children. + @override String toStringShallow([String joiner = '; ']) { final RenderObject debugPreviousActiveLayout = _debugActiveLayout; _debugActiveLayout = null; - final StringBuffer result = new StringBuffer(); - result.write('${this}$joiner'); // TODO(ianh): https://github.com/dart-lang/sdk/issues/28206 - final List description = []; - debugFillDescription(description); - result.write(description.join(joiner)); + final String result = super.toStringShallow(joiner); _debugActiveLayout = debugPreviousActiveLayout; - return result.toString(); + return result; } - /// Accumulates a list of strings describing the current node's fields, one - /// field per string. Subclasses should override this to have their - /// information included in [toStringDeep]. @protected - void debugFillDescription(List description) { - if (debugCreator != null) - description.add('creator: $debugCreator'); - description.add('parentData: $parentData${ _debugCanParentUseSize == true ? " (can use size)" : ""}'); - description.add('constraints: $constraints'); - if (_layer != null) // don't access it via the "layer" getter since that's only valid when we don't need paint - description.add('layer: $_layer'); - if (_semantics != null) - description.add('semantics: $_semantics'); - if (isBlockingSemanticsOfPreviouslyPaintedNodes) - description.add('blocks semantics of earlier render objects below the common boundary'); - if (isSemanticBoundary) - description.add('semantic boundary'); + @override + void debugFillProperties(List description) { + description.add(new DiagnosticsProperty('creator', debugCreator, defaultValue: null)); + description.add(new DiagnosticsProperty('parentData', parentData, tooltip: _debugCanParentUseSize == true ? "can use size" : null)); + description.add(new DiagnosticsProperty('constraints', constraints)); + // don't access it via the "layer" getter since that's only valid when we don't need paint + description.add(new DiagnosticsProperty('layer', _layer, defaultValue: null)); + description.add(new DiagnosticsProperty('_semantics', _semantics, defaultValue: null)); + description.add(new FlagProperty( + 'isBlockingSemanticsOfPreviouslyPaintedNodes', + value: isBlockingSemanticsOfPreviouslyPaintedNodes, + ifTrue: 'blocks semantics of earlier render objects below the common boundary', + )); + description.add(new FlagProperty('isSemanticBoundary', value: isSemanticBoundary, ifTrue: 'semantic boundary')); } - /// Returns a string describing the current node's descendants. Each line of - /// the subtree in the output should be indented by the prefix argument. @protected - String debugDescribeChildren(String prefix) => ''; - + @override + List debugDescribeChildren() => []; /// Attempt to make this or a descendant RenderObject visible on screen. /// @@ -2901,10 +2882,8 @@ abstract class RenderObjectWithChildMixin extend } @override - String debugDescribeChildren(String prefix) { - if (child != null) - return '$prefix \u2502\n${child.toStringDeep('$prefix \u2514\u2500child: ', '$prefix ')}'; - return ''; + List debugDescribeChildren() { + return child != null ? [child.toDiagnosticsNode(name: 'child')] : []; } } @@ -3204,26 +3183,21 @@ abstract class ContainerRenderObjectMixin debugDescribeChildren() { + final List children = []; if (firstChild != null) { - final StringBuffer result = new StringBuffer() - ..write(prefix) - ..write(' \u2502\n'); ChildType child = firstChild; int count = 1; - while (child != lastChild) { - result.write(child.toStringDeep("$prefix \u251C\u2500child $count: ", "$prefix \u2502")); + while (true) { + children.add(child.toDiagnosticsNode(name: 'child $count')); + if (child == lastChild) + break; count += 1; final ParentDataType childParentData = child.parentData; child = childParentData.nextSibling; } - if (child != null) { - assert(child == lastChild); - result.write(child.toStringDeep("$prefix \u2514\u2500child $count: ", "$prefix ")); - } - return result.toString(); } - return ''; + return children; } } diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index 667929c55d..7f254205a3 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -8,6 +8,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; + import 'box.dart'; import 'debug.dart'; import 'object.dart'; @@ -369,10 +370,7 @@ class RenderParagraph extends RenderBox { } @override - String debugDescribeChildren(String prefix) { - return '$prefix \u2558\u2550\u2566\u2550\u2550 text \u2550\u2550\u2550\n' - '${text.toString("$prefix \u2551 ")}' // TextSpan includes a newline - '$prefix \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n' - '${prefix.trimRight()}\n'; + List debugDescribeChildren() { + return [text.toDiagnosticsNode(name: 'text', style: DiagnosticsTreeStyle.transition)]; } } diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index ec0c4e8319..1c57ea745a 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -169,19 +169,9 @@ abstract class RenderProxyBoxWithHitTestBehavior extends RenderProxyBox { bool hitTestSelf(Offset position) => behavior == HitTestBehavior.opaque; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - switch (behavior) { - case HitTestBehavior.translucent: - description.add('behavior: translucent'); - break; - case HitTestBehavior.opaque: - description.add('behavior: opaque'); - break; - case HitTestBehavior.deferToChild: - description.add('behavior: defer-to-child'); - break; - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('behavior', behavior, defaultValue: null)); } } @@ -284,9 +274,9 @@ class RenderConstrainedBox extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('additionalConstraints: $additionalConstraints'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('additionalConstraints', additionalConstraints)); } } @@ -360,12 +350,10 @@ class RenderLimitedBox extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (maxWidth != double.INFINITY) - description.add('maxWidth: $maxWidth'); - if (maxHeight != double.INFINITY) - description.add('maxHeight: $maxHeight'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: double.INFINITY)); + description.add(new DoubleProperty('maxHeight', maxHeight, defaultValue: double.INFINITY)); } } @@ -527,9 +515,9 @@ class RenderAspectRatio extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('aspectRatio: $aspectRatio'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('aspectRatio', aspectRatio)); } } @@ -640,10 +628,10 @@ class RenderIntrinsicWidth extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('stepWidth: $stepWidth'); - description.add('stepHeight: $stepHeight'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('stepWidth', stepWidth)); + description.add(new DoubleProperty('stepHeight', stepHeight)); } } @@ -778,9 +766,9 @@ class RenderOpacity extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('opacity: ${opacity.toStringAsFixed(1)}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('opacity', opacity)); } } @@ -1377,12 +1365,12 @@ class RenderPhysicalModel extends _RenderCustomClip { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('shape: $shape'); - description.add('borderRadius: $borderRadius'); - description.add('elevation: ${elevation.toStringAsFixed(1)}'); - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('shape', shape)); + description.add(new DiagnosticsProperty('borderRadius', borderRadius)); + description.add(new DoubleProperty('elevation', elevation)); + description.add(new DiagnosticsProperty('color', color)); } } @@ -1491,7 +1479,7 @@ class RenderDecoratedBox extends RenderProxyBox { 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' 'Every call to save() or saveLayer() must be matched by a call to restore().\n' 'The decoration was:\n' - '${decoration.toString(" ")}\n' + '${decoration.toStringDeep()}\n' 'The painter was:\n' ' $_painter' ); @@ -1510,11 +1498,10 @@ class RenderDecoratedBox extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('decoration:'); - description.addAll(_decoration.toString(' ', ' ').split('\n')); - description.add('configuration: $configuration'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(_decoration.toDiagnosticsNode(name: 'decoration')); + description.add(new DiagnosticsProperty('configuration', configuration)); } } @@ -1674,13 +1661,12 @@ class RenderTransform extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('transform matrix:'); - description.addAll(debugDescribeTransform(_transform)); - description.add('origin: $origin'); - description.add('alignment: $alignment'); - description.add('transformHitTests: $transformHitTests'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new TransformProperty('transform matrix', _transform)); + description.add(new DiagnosticsProperty('origin', origin)); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new DiagnosticsProperty('transformHitTests', transformHitTests)); } } @@ -1810,10 +1796,10 @@ class RenderFittedBox extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('fit: $fit'); - description.add('alignment: $alignment'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('fit', fit)); + description.add(new DiagnosticsProperty('alignment', alignment)); } } @@ -1875,10 +1861,10 @@ class RenderFractionalTranslation extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('translation: $translation'); - description.add('transformHitTests: $transformHitTests'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('translation', translation)); + description.add(new DiagnosticsProperty('transformHitTests', transformHitTests)); } } @@ -2319,8 +2305,8 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); final List listeners = []; if (onPointerDown != null) listeners.add('down'); @@ -2332,7 +2318,8 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { listeners.add('cancel'); if (listeners.isEmpty) listeners.add(''); - description.add('listeners: ${listeners.join(", ")}'); + description.add(new IterableProperty('listeners', listeners)); + // TODO(jacobr): add raw listeners to the diagnostics data. } } @@ -2422,38 +2409,38 @@ class RenderRepaintBoundary extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); bool inReleaseMode = true; assert(() { inReleaseMode = false; if (debugSymmetricPaintCount + debugAsymmetricPaintCount == 0) { - description.add('usefulness ratio: no metrics collected yet (never painted)'); + description.add(new MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)')); } else { - final double percentage = 100.0 * debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount); + final double fraction = debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount); String diagnosis; if (debugSymmetricPaintCount + debugAsymmetricPaintCount < 5) { diagnosis = 'insufficient data to draw conclusion (less than five repaints)'; - } else if (percentage > 90.0) { + } else if (fraction > 0.9) { diagnosis = 'this is an outstandingly useful repaint boundary and should definitely be kept'; - } else if (percentage > 50.0) { + } else if (fraction > 0.5) { diagnosis = 'this is a useful repaint boundary and should be kept'; - } else if (percentage > 30.0) { + } else if (fraction > 0.30) { diagnosis = 'this repaint boundary is probably useful, but maybe it would be more useful in tandem with adding more repaint boundaries elsewhere'; - } else if (percentage > 10.0) { + } else if (fraction > 0.1) { diagnosis = 'this repaint boundary does sometimes show value, though currently not that often'; } else if (debugAsymmetricPaintCount == 0) { diagnosis = 'this repaint boundary is astoundingly ineffectual and should be removed'; } else { diagnosis = 'this repaint boundary is not very effective and should probably be removed'; } - description.add('metrics: ${percentage.toStringAsFixed(1)}% useful ($debugSymmetricPaintCount bad vs $debugAsymmetricPaintCount good)'); - description.add('diagnosis: $diagnosis'); + description.add(new PercentProperty('metrics', fraction, unit: 'useful', tooltip: '$debugSymmetricPaintCount bad vs $debugAsymmetricPaintCount good')); + description.add(new MessageProperty('diagnosis', diagnosis)); } return true; }); if (inReleaseMode) - description.add('(run in checked mode to collect repaint boundary statistics)'); + description.add(new DiagnosticsNode.message('(run in checked mode to collect repaint boundary statistics)')); } } @@ -2533,10 +2520,16 @@ class RenderIgnorePointer extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('ignoring: $ignoring'); - description.add('ignoringSemantics: ${ ignoringSemantics == null ? "implicitly " : "" }$_effectiveIgnoringSemantics'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('ignoring', ignoring)); + description.add( + new DiagnosticsProperty( + 'ignoringSemantics', + _effectiveIgnoringSemantics, + description: ignoringSemantics == null ? 'implicitly $_effectiveIgnoringSemantics' : null, + ) + ); } } @@ -2642,9 +2635,21 @@ class RenderOffstage extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('offstage: $offstage'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('offstage', offstage)); + } + + @override + List debugDescribeChildren() { + if (child == null) + return []; + return [ + child.toDiagnosticsNode( + name: 'child', + style: offstage ? DiagnosticsTreeStyle.offstage : DiagnosticsTreeStyle.sparse, + ), + ]; } } @@ -2683,9 +2688,9 @@ class RenderAbsorbPointer extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('absorbing: $absorbing'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('absorbing', absorbing)); } } @@ -2709,9 +2714,9 @@ class RenderMetaData extends RenderProxyBoxWithHitTestBehavior { dynamic metaData; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('metaData: $metaData'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('metaData', metaData)); } } @@ -2904,8 +2909,8 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); final List gestures = []; if (onTap != null) gestures.add('tap'); @@ -2917,7 +2922,7 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA gestures.add('vertical scroll'); if (gestures.isEmpty) gestures.add(''); - description.add('gestures: ${gestures.join(", ")}'); + description.add(new IterableProperty('gestures', gestures)); } } @@ -3081,9 +3086,9 @@ class RenderExcludeSemantics extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('excluding: $excluding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('excluding', excluding)); } } @@ -3129,9 +3134,9 @@ class RenderLeaderLayer extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('link: $link'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('link', link)); } } @@ -3274,12 +3279,11 @@ class RenderFollowerLayer extends RenderProxyBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('link: $link'); - description.add('showWhenUnlinked: $showWhenUnlinked'); - description.add('offset: $offset'); - description.add('current transform matrix:'); - description.addAll(debugDescribeTransform(getCurrentTransform())); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('link', link)); + description.add(new DiagnosticsProperty('showWhenUnlinked', showWhenUnlinked)); + description.add(new DiagnosticsProperty('offset', offset)); + description.add(new TransformProperty('current transform matrix', getCurrentTransform())); } } diff --git a/packages/flutter/lib/src/rendering/shifted_box.dart b/packages/flutter/lib/src/rendering/shifted_box.dart index 0887c39648..c289953ca2 100644 --- a/packages/flutter/lib/src/rendering/shifted_box.dart +++ b/packages/flutter/lib/src/rendering/shifted_box.dart @@ -177,9 +177,9 @@ class RenderPadding extends RenderShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('padding: $padding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('padding', padding)); } } @@ -236,9 +236,9 @@ abstract class RenderAligningShiftedBox extends RenderShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); } } @@ -366,10 +366,10 @@ class RenderPositionedBox extends RenderAligningShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('widthFactor: ${_widthFactor ?? "expand"}'); - description.add('heightFactor: ${_heightFactor ?? "expand"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('widthFactor', _widthFactor, ifNull: 'expand')); + description.add(new DoubleProperty('heightFactor', _heightFactor, ifNull: 'expand')); } } @@ -479,12 +479,12 @@ class RenderConstrainedOverflowBox extends RenderAligningShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('minWidth: ${minWidth ?? "use parent minWidth constraint"}'); - description.add('maxWidth: ${maxWidth ?? "use parent maxWidth constraint"}'); - description.add('minHeight: ${minHeight ?? "use parent minHeight constraint"}'); - description.add('maxHeight: ${maxHeight ?? "use parent maxHeight constraint"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('minWidth', minWidth, ifNull: 'use parent minWidth constraint')); + description.add(new DoubleProperty('maxWidth', maxWidth, ifNull: 'use parent maxWidth constraint')); + description.add(new DoubleProperty('minHeight', minHeight, ifNull: 'use parent minHeight constraint')); + description.add(new DoubleProperty('maxHeight', maxHeight, ifNull: 'use parent maxHeight constraint')); } } @@ -689,10 +689,10 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('widthFactor: ${_widthFactor ?? "pass-through"}'); - description.add('heightFactor: ${_heightFactor ?? "pass-through"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('widthFactor', _widthFactor, ifNull: 'pass-through')); + description.add(new DoubleProperty('heightFactor', _heightFactor, ifNull: 'pass-through')); } } @@ -945,9 +945,9 @@ class RenderBaseline extends RenderShiftedBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('baseline: $baseline'); - description.add('baselineType: $baselineType'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('baseline', baseline)); + description.add(new EnumProperty('baselineType', baselineType)); } } diff --git a/packages/flutter/lib/src/rendering/sliver.dart b/packages/flutter/lib/src/rendering/sliver.dart index b8e2c54ca3..6a1dc3c166 100644 --- a/packages/flutter/lib/src/rendering/sliver.dart +++ b/packages/flutter/lib/src/rendering/sliver.dart @@ -467,7 +467,7 @@ class SliverConstraints extends Constraints { /// A sliver can occupy space in several different ways, which is why this class /// contains multiple values. @immutable -class SliverGeometry { +class SliverGeometry implements TreeDiagnostics { /// Creates an object that describes the amount of space occupied by a sliver. /// /// If the [layoutExtent] argument is null, [layoutExtent] defaults to the @@ -621,37 +621,45 @@ class SliverGeometry { @override String toString() { - final StringBuffer buffer = new StringBuffer(); - buffer.write('SliverGeometry('); - buffer.write('scrollExtent: ${scrollExtent.toStringAsFixed(1)}, '); - if (paintExtent > 0.0) { - if (visible) { - buffer.write('paintExtent: ${paintExtent.toStringAsFixed(1)}, '); + return toDiagnosticsNode(style: DiagnosticsTreeStyle.singleLine).toStringDeep(); + } + + @override + String toStringDeep([String prefix = '', String indentPrefix ]) { + return toDiagnosticsNode().toStringDeep(prefix, indentPrefix); + } + + @override + DiagnosticsNode toDiagnosticsNode({ + String name, + DiagnosticsTreeStyle style: DiagnosticsTreeStyle.whitespace, + }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + description: 'SliverGeometry', + style: style, + emptyBodyDescription: '', + fillProperties: (List properties) { + properties.add(new DoubleProperty('scrollExtent', scrollExtent)); + if (paintExtent > 0.0) { + properties.add(new DoubleProperty('paintExtent', paintExtent, unit : visible ? null : ' but not painting')); + } else if (paintExtent == 0.0) { + if (visible) { + properties.add(new DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but visible')); + } + properties.add(new FlagProperty('visible', value: visible, ifFalse: 'hidden')); } else { - buffer.write('paintExtent: ${paintExtent.toStringAsFixed(1)} but not painting, '); + // Negative paintExtent! + properties.add(new DoubleProperty('paintExtent', paintExtent, tooltip: '!')); } - } else if (paintExtent == 0.0) { - if (visible) { - buffer.write('paintExtent: ${paintExtent.toStringAsFixed(1)} but visible, '); - } else { - buffer.write('hidden, '); - } - } else { - buffer.write('paintExtent: ${paintExtent.toStringAsFixed(1)} (!), '); - } - if (paintOrigin != 0.0) - buffer.write('paintOrigin: ${paintOrigin.toStringAsFixed(1)}, '); - if (layoutExtent != paintExtent) - buffer.write('layoutExtent: ${layoutExtent.toStringAsFixed(1)}, '); - buffer.write('maxPaintExtent: ${maxPaintExtent.toStringAsFixed(1)}, '); - if (hitTestExtent != paintExtent) - buffer.write('hitTestExtent: ${hitTestExtent.toStringAsFixed(1)}, '); - if (hasVisualOverflow) - buffer.write('hasVisualOverflow: true, '); - if (scrollOffsetCorrection != null) - buffer.write('scrollOffsetCorrection: ${scrollOffsetCorrection.toStringAsFixed(1)}'); - buffer.write(')'); - return buffer.toString(); + properties.add(new DoubleProperty('paintOrigin', paintOrigin, defaultValue: 0.0)); + properties.add(new DoubleProperty('layoutExtent', layoutExtent, defaultValue: paintExtent)); + properties.add(new DoubleProperty('maxPaintExtent', maxPaintExtent)); + properties.add(new DoubleProperty('hitTestExtent', hitTestExtent, defaultValue: paintExtent)); + properties.add(new DiagnosticsProperty('hasVisualOverflow', hasVisualOverflow, defaultValue: false)); + properties.add(new DoubleProperty('scrollOffsetCorrection', scrollOffsetCorrection, defaultValue: null)); + }); } } @@ -1321,9 +1329,9 @@ abstract class RenderSliver extends RenderObject { void handleEvent(PointerEvent event, SliverHitTestEntry entry) { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('geometry: $geometry'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('geometry', geometry)); } } diff --git a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart index 0dff9b9877..95e4f2a45e 100644 --- a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart +++ b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart @@ -517,13 +517,9 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (firstChild != null) { - description.add('currently live children: ${indexOf(firstChild)} to ${indexOf(lastChild)}'); - } else { - description.add('no children current live'); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsNode.message(firstChild != null ? 'currently live children: ${indexOf(firstChild)} to ${indexOf(lastChild)}' : 'no children current live')); } /// Asserts that the reified child list is not empty and has a contiguous @@ -546,40 +542,27 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } @override - String debugDescribeChildren(String prefix) { - StringBuffer result; + List debugDescribeChildren() { + final List children = []; if (firstChild != null) { - result = new StringBuffer() - ..write(prefix) - ..write(' \u2502\n'); RenderBox child = firstChild; - while (child != lastChild) { + while (true) { final SliverMultiBoxAdaptorParentData childParentData = child.parentData; - result.write(child.toStringDeep("$prefix \u251C\u2500child with index ${childParentData.index}: ", "$prefix \u2502")); + children.add(child.toDiagnosticsNode(name: "child with index ${childParentData.index}")); + if (child == lastChild) + break; child = childParentData.nextSibling; } - if (child != null) { - assert(child == lastChild); - final SliverMultiBoxAdaptorParentData childParentData = child.parentData; - if (_keepAliveBucket.isEmpty) { - result.write(child.toStringDeep("$prefix \u2514\u2500child with index ${childParentData.index}: ", "$prefix ")); - } else { - result.write(child.toStringDeep("$prefix \u251C\u2500child with index ${childParentData.index}: ", "$prefix \u254E")); - } - } } if (_keepAliveBucket.isNotEmpty) { - result ??= new StringBuffer() - ..write(prefix) - ..write(' \u254E\n'); final List indices = _keepAliveBucket.keys.toList()..sort(); - final int lastIndex = indices.removeLast(); - if (indices.isNotEmpty) { - for (int index in indices) - result.write(_keepAliveBucket[index].toStringDeep("$prefix \u251C\u2500child with index $index (kept alive offstage): ", "$prefix \u254E")); + for (int index in indices) { + children.add(_keepAliveBucket[index].toDiagnosticsNode( + name: "child with index $index (kept alive offstage)", + style: DiagnosticsTreeStyle.offstage, + )); } - result.write(_keepAliveBucket[lastIndex].toStringDeep("$prefix \u2514\u2500child with index $lastIndex (kept alive offstage): ", "$prefix ")); } - return result?.toString() ?? ''; + return children; } } diff --git a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart index 1f5f2b8210..d2c5b380f6 100644 --- a/packages/flutter/lib/src/rendering/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/rendering/sliver_persistent_header.dart @@ -204,18 +204,10 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - try { - description.add('maxExtent: ${maxExtent.toStringAsFixed(1)}'); - } catch (e) { - description.add('maxExtent: EXCEPTION (${e.runtimeType})'); - } - try { - description.add('child position: ${childMainAxisPosition(child).toStringAsFixed(1)}'); - } catch (e) { - description.add('child position: EXCEPTION (${e.runtimeType})'); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty.lazy('maxExtent', () => maxExtent)); + description.add(new DoubleProperty.lazy('child position', () => childMainAxisPosition(child))); } } @@ -465,9 +457,9 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('effective scroll offset: ${_effectiveScrollOffset?.toStringAsFixed(1)}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('effective scroll offset', _effectiveScrollOffset)); } } diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index 0d3ee90cd3..60974b53f2 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -524,11 +524,11 @@ class RenderStack extends RenderBox Rect describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - description.add('fit: $fit'); - description.add('overflow: $overflow'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new EnumProperty('fit', fit)); + description.add(new EnumProperty('overflow', overflow)); } } @@ -600,8 +600,8 @@ class RenderIndexedStack extends RenderStack { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('index: $index'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new IntProperty('index', index)); } } diff --git a/packages/flutter/lib/src/rendering/table.dart b/packages/flutter/lib/src/rendering/table.dart index ee0dfaebbe..e41542bd72 100644 --- a/packages/flutter/lib/src/rendering/table.dart +++ b/packages/flutter/lib/src/rendering/table.dart @@ -1278,46 +1278,34 @@ class RenderTable extends RenderBox { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (border != null) - description.add('border: $border'); - if (_columnWidths.isNotEmpty) - description.add('specified column widths: $_columnWidths'); - description.add('default column width: $defaultColumnWidth'); - description.add('table size: $columns\u00D7$rows'); - description.add('column offsets: ${ _columnLefts ?? "unknown" }'); - description.add('row offsets: ${ _rowTops ?? "unknown" }'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('border', border, defaultValue: null)); + description.add(new DiagnosticsProperty>('specified column widths', _columnWidths, hidden: _columnWidths.isEmpty)); + description.add(new DiagnosticsProperty('default column width', defaultColumnWidth)); + description.add(new MessageProperty('table size', '$columns\u00D7$rows')); + description.add(new IterableProperty('column offsets', _columnLefts, ifNull: 'unknown')); + description.add(new IterableProperty('row offsets', _rowTops, ifNull: "unknown")); } @override - String debugDescribeChildren(String prefix) { - final StringBuffer result = new StringBuffer(); - result.writeln('$prefix \u2502'); - final int lastIndex = _children.length - 1; - if (lastIndex < 0) { - result.writeln('$prefix \u2514\u2500table is empty'); - } else { - for (int y = 0; y < rows; y += 1) { - for (int x = 0; x < columns; x += 1) { - final int xy = x + y * columns; - final RenderBox child = _children[xy]; - if (child != null) { - if (xy < lastIndex) { - result.write('${child.toStringDeep("$prefix \u251C\u2500child ($x, $y): ", "$prefix \u2502")}'); - } else { - result.write('${child.toStringDeep("$prefix \u2514\u2500child ($x, $y): ", "$prefix ")}'); - } - } else { - if (xy < lastIndex) { - result.writeln('$prefix \u251C\u2500child ($x, $y) is null'); - } else { - result.writeln('$prefix \u2514\u2500child ($x, $y) is null'); - } - } - } + List debugDescribeChildren() { + if (_children.isEmpty) { + return [new DiagnosticsNode.message('table is empty')]; + } + + final List children = []; + for (int y = 0; y < rows; y += 1) { + for (int x = 0; x < columns; x += 1) { + final int xy = x + y * columns; + final RenderBox child = _children[xy]; + final String name = 'child ($x, $y)'; + if (child != null) + children.add(child.toDiagnosticsNode(name: name)); + else + children.add(new DiagnosticsProperty(name, null, ifNull: 'is null', showSeparator: false)); } } - return result.toString(); + return children; } } diff --git a/packages/flutter/lib/src/rendering/view.dart b/packages/flutter/lib/src/rendering/view.dart index 391c493daf..8ff1451201 100644 --- a/packages/flutter/lib/src/rendering/view.dart +++ b/packages/flutter/lib/src/rendering/view.dart @@ -211,16 +211,18 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin } @override - void debugFillDescription(List description) { - // call to ${super.debugFillDescription(prefix)} is omitted because the root superclasses don't include any interesting information for this class + void debugFillProperties(List description) { + // call to ${super.debugFillProperties(description)} is omitted because the + // root superclasses don't include any interesting information for this + // class assert(() { - description.add('debug mode enabled - ${Platform.operatingSystem}'); + description.add(new DiagnosticsNode.message('debug mode enabled - ${Platform.operatingSystem}')); return true; }); - description.add('window size: ${ui.window.physicalSize} (in physical pixels)'); - description.add('device pixel ratio: ${ui.window.devicePixelRatio} (physical pixels per logical pixel)'); - description.add('configuration: $configuration (in logical pixels)'); + description.add(new DiagnosticsProperty('window size', ui.window.physicalSize, tooltip: 'in physical pixels')); + description.add(new DoubleProperty('device pixel ratio', ui.window.devicePixelRatio, tooltip: 'physical pixels per logical pixel')); + description.add(new DiagnosticsProperty('configuration', configuration, tooltip: 'in logical pixels')); if (ui.window.semanticsEnabled) - description.add('semantics enabled'); + description.add(new DiagnosticsNode.message('semantics enabled')); } } diff --git a/packages/flutter/lib/src/rendering/viewport.dart b/packages/flutter/lib/src/rendering/viewport.dart index c8243bae61..4e1aff1490 100644 --- a/packages/flutter/lib/src/rendering/viewport.dart +++ b/packages/flutter/lib/src/rendering/viewport.dart @@ -468,29 +468,28 @@ abstract class RenderViewportBase description) { - super.debugFillDescription(description); - description.add('$axisDirection'); - description.add('offset: $offset'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('axisDirection', axisDirection)); + description.add(new DiagnosticsProperty('offset', offset)); } @override - String debugDescribeChildren(String prefix) { - if (firstChild == null) - return '$prefix\n'; - int count = indexOfFirstChild; - final StringBuffer result = new StringBuffer() - ..write(prefix) - ..write(' \u2502\n'); + List debugDescribeChildren() { + final List children = []; RenderSliver child = firstChild; - while (child != lastChild) { - result.write(child.toStringDeep("$prefix \u251C\u2500${labelForChild(count)}: ", "$prefix \u2502")); + if (child == null) + return children; + + int count = indexOfFirstChild; + while (true) { + children.add(child.toDiagnosticsNode(name: labelForChild(count))); + if (child == lastChild) + break; count += 1; child = childAfter(child); } - assert(child == lastChild); - result.write(child.toStringDeep("$prefix \u2514\u2500${labelForChild(count)}: ", "$prefix ")); - return result.toString(); + return children; } // API TO BE IMPLEMENTED BY SUBCLASSES @@ -1046,9 +1045,9 @@ class RenderViewport extends RenderViewportBase description) { - super.debugFillDescription(description); - description.add('anchor: $anchor'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('anchor', anchor)); } } diff --git a/packages/flutter/lib/src/rendering/wrap.dart b/packages/flutter/lib/src/rendering/wrap.dart index f1ec7b178e..440a229092 100644 --- a/packages/flutter/lib/src/rendering/wrap.dart +++ b/packages/flutter/lib/src/rendering/wrap.dart @@ -593,13 +593,13 @@ class RenderWrap extends RenderBox with ContainerRenderObjectMixin description) { - super.debugFillDescription(description); - description.add('direction: $direction'); - description.add('alignment: $alignment'); - description.add('spacing: $spacing'); - description.add('runAlignment: $runAlignment'); - description.add('runSpacing: $runSpacing'); - description.add('crossAxisAlignment: $runSpacing'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('direction', direction)); + description.add(new EnumProperty('alignment', alignment)); + description.add(new DoubleProperty('spacing', spacing)); + description.add(new EnumProperty('runAlignment', runAlignment)); + description.add(new DoubleProperty('runSpacing', runSpacing)); + description.add(new DoubleProperty('crossAxisAlignment', runSpacing)); } } diff --git a/packages/flutter/lib/src/widgets/animated_cross_fade.dart b/packages/flutter/lib/src/widgets/animated_cross_fade.dart index 7311a1df47..daec4c2332 100644 --- a/packages/flutter/lib/src/widgets/animated_cross_fade.dart +++ b/packages/flutter/lib/src/widgets/animated_cross_fade.dart @@ -215,11 +215,10 @@ class AnimatedCrossFade extends StatefulWidget { _AnimatedCrossFadeState createState() => new _AnimatedCrossFadeState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$crossFadeState'); - if (alignment != FractionalOffset.topCenter) - description.add('alignment: $alignment'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('crossFadeState', crossFadeState)); + description.add(new DiagnosticsProperty('alignment', alignment, defaultValue: FractionalOffset.topCenter)); } } @@ -353,11 +352,10 @@ class _AnimatedCrossFadeState extends State with TickerProvid } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('${widget.crossFadeState}'); - description.add('$_controller'); - if (widget.alignment != FractionalOffset.topCenter) - description.add('alignment: ${widget.alignment}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('crossFadeState', widget.crossFadeState)); + description.add(new DiagnosticsProperty('controller', _controller, showName: false)); + description.add(new DiagnosticsProperty('alignment', widget.alignment, defaultValue: FractionalOffset.topCenter)); } } diff --git a/packages/flutter/lib/src/widgets/automatic_keep_alive.dart b/packages/flutter/lib/src/widgets/automatic_keep_alive.dart index 4bb65d81c4..e89960da39 100644 --- a/packages/flutter/lib/src/widgets/automatic_keep_alive.dart +++ b/packages/flutter/lib/src/widgets/automatic_keep_alive.dart @@ -198,15 +198,17 @@ class _AutomaticKeepAliveState extends State { @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (_keepingAlive) - description.add('keeping subtree alive'); - if (_handles == null) { - description.add('no notifications ever received'); - } else { - description.add('${_handles.length} active client${ _handles.length == 1 ? "" : "s" }'); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('_keepingAlive', value: _keepingAlive, ifTrue: 'keeping subtree alive')); + description.add(new DiagnosticsProperty>( + 'handles', + _handles, + description: _handles != null ? + '${_handles.length} active client${ _handles.length == 1 ? "" : "s" }' : + null, + ifNull: 'no notifications ever received', + )); } } diff --git a/packages/flutter/lib/src/widgets/banner.dart b/packages/flutter/lib/src/widgets/banner.dart index 2ca61a8655..bcdb91eea9 100644 --- a/packages/flutter/lib/src/widgets/banner.dart +++ b/packages/flutter/lib/src/widgets/banner.dart @@ -207,12 +207,12 @@ class Banner extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('"$message"'); - description.add('$location'); - description.add('$color'); - '$textStyle'.split('\n').map((String value) => 'text $value').forEach(description.add); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('message', message, showName: false)); + description.add(new EnumProperty('location', location)); + description.add(new DiagnosticsProperty('color', color, showName: false)); + textStyle?.debugFillProperties(description, prefix: 'text '); } } @@ -243,13 +243,13 @@ class CheckedModeBanner extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); String message = 'disabled'; assert(() { message = '"SLOW MODE"'; return true; }); - description.add(message); + description.add(new DiagnosticsNode.message(message)); } } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 77f6fa3e25..a45442d92e 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -120,9 +120,9 @@ class Opacity extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('opacity: $opacity'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('opacity', opacity)); } } @@ -392,10 +392,9 @@ class ClipRect extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (clipper != null) - description.add('clipper: $clipper'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty>('clipper', clipper, defaultValue: null)); } } @@ -448,12 +447,10 @@ class ClipRRect extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (borderRadius != null) - description.add('$borderRadius'); - if (clipper != null) - description.add('clipper: $clipper'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('borderRadius', borderRadius, showName: false, defaultValue: null)); + description.add(new DiagnosticsProperty>('clipper', clipper, defaultValue: null)); } } @@ -502,10 +499,9 @@ class ClipOval extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (clipper != null) - description.add('clipper: $clipper'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty>('clipper', clipper, defaultValue: null)); } } @@ -551,10 +547,9 @@ class ClipPath extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (clipper != null) - description.add('clipper: $clipper'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty>('clipper', clipper, defaultValue: null)); } } @@ -615,12 +610,12 @@ class PhysicalModel extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('shape: $shape'); - description.add('borderRadius: $borderRadius'); - description.add('elevation: ${elevation.toStringAsFixed(1)}'); - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('shape', shape)); + description.add(new DiagnosticsProperty('borderRadius', borderRadius)); + description.add(new DoubleProperty('elevation', elevation)); + description.add(new DiagnosticsProperty('color', color)); } } @@ -1053,9 +1048,9 @@ class Padding extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('padding: $padding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('padding', padding)); } } @@ -1130,13 +1125,11 @@ class Align extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - if (widthFactor != null) - description.add('widthFactor: $widthFactor'); - if (heightFactor != null) - description.add('heightFactor: $heightFactor'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new DoubleProperty('widthFactor', widthFactor, defaultValue: null)); + description.add(new DoubleProperty('heightFactor', heightFactor, defaultValue: null)); } } @@ -1232,9 +1225,9 @@ class LayoutId extends ParentDataWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('id: $id'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('id', id)); } } @@ -1374,14 +1367,11 @@ class SizedBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (width != double.INFINITY || height != double.INFINITY) { - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); - } + void debugFillProperties(List description) { + super.debugFillProperties(description); + final bool hidden = width == double.INFINITY && height == double.INFINITY; + description.add(new DoubleProperty('width', width, defaultValue: null, hidden: hidden)); + description.add(new DoubleProperty('height', height, defaultValue: null, hidden: hidden)); } } @@ -1438,9 +1428,9 @@ class ConstrainedBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$constraints'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('constraints', constraints, showName: false)); } } @@ -1516,13 +1506,11 @@ class FractionallySizedBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - if (widthFactor != null) - description.add('widthFactor: $widthFactor'); - if (heightFactor != null) - description.add('heightFactor: $heightFactor'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new DoubleProperty('widthFactor', widthFactor, defaultValue: null)); + description.add(new DoubleProperty('heightFactor', heightFactor, defaultValue: null)); } } @@ -1586,12 +1574,10 @@ class LimitedBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (maxWidth != double.INFINITY) - description.add('maxWidth: $maxWidth'); - if (maxHeight != double.INFINITY) - description.add('maxHeight: $maxHeight'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: double.INFINITY)); + description.add(new DoubleProperty('maxHeight', maxHeight, defaultValue: double.INFINITY)); } } @@ -1660,17 +1646,13 @@ class OverflowBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - if (minWidth != null) - description.add('minWidth: $minWidth'); - if (maxWidth != null) - description.add('maxWidth: $maxWidth'); - if (minHeight != null) - description.add('minHeight: $minHeight'); - if (maxHeight != null) - description.add('maxHeight: $maxHeight'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new DoubleProperty('minWidth', minWidth, defaultValue: null)); + description.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: null)); + description.add(new DoubleProperty('minHeight', minHeight, defaultValue: null)); + description.add(new DoubleProperty('maxHeight', maxHeight, defaultValue: null)); } } @@ -1719,11 +1701,10 @@ class SizedOverflowBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - if (size != null) - description.add('size: $size'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new DiagnosticsProperty('size', size, defaultValue: null)); } } @@ -1754,9 +1735,9 @@ class Offstage extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('offstage: $offstage'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('offstage', offstage)); } @override @@ -1828,9 +1809,9 @@ class AspectRatio extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('aspectRatio: $aspectRatio'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('aspectRatio', aspectRatio)); } } @@ -2007,9 +1988,9 @@ class SliverPadding extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('padding: $padding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('padding', padding)); } } @@ -2149,11 +2130,11 @@ class Stack extends MultiChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('alignment: $alignment'); - description.add('fit: $fit'); - description.add('overflow: $overflow'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment)); + description.add(new EnumProperty('fit', fit)); + description.add(new EnumProperty('overflow', overflow)); } } @@ -2355,20 +2336,14 @@ class Positioned extends ParentDataWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (left != null) - description.add('left: $left'); - if (top != null) - description.add('top: $top'); - if (right != null) - description.add('right: $right'); - if (bottom != null) - description.add('bottom: $bottom'); - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('left', left, defaultValue: null)); + description.add(new DoubleProperty('top', top, defaultValue: null)); + description.add(new DoubleProperty('right', right, defaultValue: null)); + description.add(new DoubleProperty('bottom', bottom, defaultValue: null)); + description.add(new DoubleProperty('width', width, defaultValue: null)); + description.add(new DoubleProperty('height', height, defaultValue: null)); } } @@ -2877,9 +2852,9 @@ class Flexible extends ParentDataWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('flex: $flex'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new IntProperty('flex', flex)); } } @@ -3379,27 +3354,18 @@ class RawImage extends LeafRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('image: $image'); - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); - if (scale != 1.0) - description.add('scale: $scale'); - if (color != null) - description.add('color: $color'); - if (colorBlendMode != null) - description.add('colorBlendMode: $colorBlendMode'); - if (fit != null) - description.add('fit: $fit'); - if (alignment != null) - description.add('alignment: $alignment'); - if (repeat != ImageRepeat.noRepeat) - description.add('repeat: $repeat'); - if (centerSlice != null) - description.add('centerSlice: $centerSlice'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('image', image)); + description.add(new DoubleProperty('width', width, defaultValue: null)); + description.add(new DoubleProperty('height', height, defaultValue: null)); + description.add(new DoubleProperty('scale', scale, defaultValue: 1.0)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); + description.add(new EnumProperty('colorBlendMode', colorBlendMode, defaultValue: null)); + description.add(new EnumProperty('fit', fit, defaultValue: null)); + description.add(new DiagnosticsProperty('alignment', alignment, defaultValue: null)); + description.add(new EnumProperty('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); + description.add(new DiagnosticsProperty('centerSlice', centerSlice, defaultValue: null)); } } @@ -3546,8 +3512,8 @@ class Listener extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); final List listeners = []; if (onPointerDown != null) listeners.add('down'); @@ -3559,18 +3525,8 @@ class Listener extends SingleChildRenderObjectWidget { listeners.add('cancel'); if (listeners.isEmpty) listeners.add(''); - description.add('listeners: ${listeners.join(", ")}'); - switch (behavior) { - case HitTestBehavior.translucent: - description.add('behavior: translucent'); - break; - case HitTestBehavior.opaque: - description.add('behavior: opaque'); - break; - case HitTestBehavior.deferToChild: - description.add('behavior: defer-to-child'); - break; - } + description.add(new IterableProperty('listeners', listeners)); + description.add(new EnumProperty('behavior', behavior)); } } @@ -3670,11 +3626,10 @@ class IgnorePointer extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('ignoring: $ignoring'); - if (ignoringSemantics != null) - description.add('ignoringSemantics: $ignoringSemantics'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('ignoring', ignoring)); + description.add(new DiagnosticsProperty('ignoringSemantics', ignoringSemantics, defaultValue: null)); } } @@ -3756,10 +3711,10 @@ class MetaData extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('behavior: $behavior'); - description.add('metaData: $metaData'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('behavior', behavior)); + description.add(new DiagnosticsProperty('metaData', metaData)); } } @@ -3847,15 +3802,12 @@ class Semantics extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('container: $container'); - if (checked != null) - description.add('checked: $checked'); - if (selected != null) - description.add('selected: $selected'); - if (label != null) - description.add('label: "$label"'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('container', container)); + description.add(new DiagnosticsProperty('checked', checked, defaultValue: null)); + description.add(new DiagnosticsProperty('selected', selected, defaultValue: null)); + description.add(new StringProperty('label', label)); } } @@ -3941,9 +3893,9 @@ class ExcludeSemantics extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('excluding: $excluding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('excluding', excluding)); } } diff --git a/packages/flutter/lib/src/widgets/container.dart b/packages/flutter/lib/src/widgets/container.dart index 89bf1409b4..3f181c9eb1 100644 --- a/packages/flutter/lib/src/widgets/container.dart +++ b/packages/flutter/lib/src/widgets/container.dart @@ -84,8 +84,8 @@ class DecoratedBox extends SingleChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); String label; if (position != null) { switch (position) { @@ -97,10 +97,15 @@ class DecoratedBox extends SingleChildRenderObjectWidget { break; } } else { - description.add('position: NULL'); label = 'decoration'; } - description.add(decoration != null ? '$label: $decoration' : 'no decoration'); + description.add(new EnumProperty('position', position, hidden: position != null)); + description.add(new DiagnosticsProperty( + label, + decoration, + ifNull: 'no decoration', + showName: decoration != null, + )); } } @@ -355,21 +360,14 @@ class Container extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (alignment != null) - description.add('$alignment'); - if (padding != null) - description.add('padding: $padding'); - if (decoration != null) - description.add('bg: $decoration'); - if (foregroundDecoration != null) - description.add('fg: $foregroundDecoration'); - if (constraints != null) - description.add('$constraints'); - if (margin != null) - description.add('margin: $margin'); - if (transform != null) - description.add('has transform'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment, showName: false, defaultValue: null)); + description.add(new DiagnosticsProperty('padding', padding, defaultValue: null)); + description.add(new DiagnosticsProperty('bg', decoration, defaultValue: null)); + description.add(new DiagnosticsProperty('fg', foregroundDecoration, defaultValue: null)); + description.add(new DiagnosticsProperty('constraints', constraints, defaultValue: null)); + description.add(new DiagnosticsProperty('margin', margin, defaultValue: null)); + description.add(new ObjectFlagProperty.has('transform', transform)); } } diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 1e5f13b1c1..d8a8296dea 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -254,25 +254,18 @@ class EditableText extends StatefulWidget { EditableTextState createState() => new EditableTextState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('controller: $controller'); - description.add('focusNode: $focusNode'); - if (obscureText != false) - description.add('obscureText: $obscureText'); - if (autocorrect != true) - description.add('autocorrect: $autocorrect'); - description.add('${style.toString().split("\n").join(", ")}'); - if (textAlign != null) - description.add('$textAlign'); - if (textScaleFactor != null) - description.add('textScaleFactor: $textScaleFactor'); - if (maxLines != 1) - description.add('maxLines: $maxLines'); - if (autofocus != false) - description.add('autofocus: $autofocus'); - if (keyboardType != null) - description.add('keyboardType: $keyboardType'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('controller', controller)); + description.add(new DiagnosticsProperty('focusNode', focusNode)); + description.add(new DiagnosticsProperty('obscureText', obscureText, defaultValue: false)); + description.add(new DiagnosticsProperty('autocorrect', autocorrect, defaultValue: true)); + style?.debugFillProperties(description); + description.add(new EnumProperty('textAlign', textAlign, defaultValue: null)); + description.add(new DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: null)); + description.add(new IntProperty('maxLines', maxLines, defaultValue: 1)); + description.add(new DiagnosticsProperty('autofocus', autofocus, defaultValue: false)); + description.add(new EnumProperty('keyboardType', keyboardType, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/focus_manager.dart b/packages/flutter/lib/src/widgets/focus_manager.dart index 8090fa5125..d4218e49b8 100644 --- a/packages/flutter/lib/src/widgets/focus_manager.dart +++ b/packages/flutter/lib/src/widgets/focus_manager.dart @@ -354,29 +354,27 @@ class FocusScopeNode extends Object with TreeDiagnosticsMixin { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); if (_focus != null) - description.add('focus: $_focus'); + description.add(new DiagnosticsProperty('focus', _focus)); } @override - String debugDescribeChildren(String prefix) { - final StringBuffer buffer = new StringBuffer(); + List debugDescribeChildren() { + final List children = []; if (_firstChild != null) { FocusScopeNode child = _firstChild; int count = 1; - while (child != _lastChild) { - buffer.write(child.toStringDeep("$prefix \u251C\u2500child $count: ", "$prefix \u2502")); - count += 1; + while (true) { + children.add(child.toDiagnosticsNode(name: "child $count")); + if (child == _lastChild) + break; child = child._nextSibling; - } - if (child != null) { - assert(child == _lastChild); - buffer.write(child.toStringDeep("$prefix \u2514\u2500child $count: ", "$prefix ")); + count += 1; } } - return buffer.toString(); + return children; } } diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 8981c26be1..8965b98096 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -472,8 +472,9 @@ abstract class Widget { @override String toString() { final String name = toStringShort(); - final List data = []; - debugFillDescription(data); + List data = []; + debugFillProperties(data); + data = data.where((DiagnosticsNode n) => !n.hidden).toList(); if (data.isEmpty) return '$name'; return '$name(${data.join("; ")})'; @@ -483,14 +484,14 @@ abstract class Widget { /// /// This method makes it easier for subclasses to coordinate to provide a /// high-quality [toString] implementation. The [toString] implementation on - /// the [State] base class calls [debugFillDescription] to collect useful + /// the [State] base class calls [debugFillProperties] to collect useful /// information from subclasses to incorporate into its return value. /// /// If you override this, make sure to start your method with a call to - /// `super.debugFillDescription(description)`. + /// `super.debugFillProperties(description)`. @protected @mustCallSuper - void debugFillDescription(List description) { } + void debugFillProperties(List description) { } /// Whether the `newWidget` can be used to update an [Element] that currently /// has the `oldWidget` as its configuration. @@ -1369,32 +1370,37 @@ abstract class State { @override String toString() { - final List data = []; - debugFillDescription(data); - return '${describeIdentity(this)}(${data.join("; ")})'; + final List allProperties = []; + debugFillProperties(allProperties); + final Iterable properties = + allProperties.where((DiagnosticsNode n) => !n.hidden); + return '${describeIdentity(this)}(${properties.join("; ")})'; } - /// Add additional information to the given description for use by [toString]. + /// Add additional properties to the given description used by + /// [toDiagnosticNode], [toString] and [toStringDeep]. /// - /// This method makes it easier for subclasses to coordinate to provide a - /// high-quality [toString] implementation. The [toString] implementation on - /// the [State] base class calls [debugFillDescription] to collect useful + /// This method makes it easier for subclasses to coordinate to provide + /// high-quality diagnostic data. The [toString] implementation on + /// the [State] base class calls [debugFillProperties] to collect useful /// information from subclasses to incorporate into its return value. /// /// If you override this, make sure to start your method with a call to - /// `super.debugFillDescription(description)`. + /// `super.debugFillProperties(description)`. + /// + /// See also: + /// + /// * [TreeDiagnosticsMixin.debugFillProperties], which provides detailed + /// best practices for defining diagnostic properties. @protected @mustCallSuper - void debugFillDescription(List description) { + void debugFillProperties(List description) { assert(() { - if (_debugLifecycleState != _StateLifecycle.ready) - description.add('$_debugLifecycleState'); + description.add(new EnumProperty<_StateLifecycle>('lifecycle state', _debugLifecycleState, defaultValue: _StateLifecycle.ready)); return true; }); - if (_widget == null) - description.add('no widget'); - if (_element == null) - description.add('not mounted'); + description.add(new ObjectFlagProperty('_widget', _widget, ifNull: 'no widget')); + description.add(new ObjectFlagProperty('_element', _element, ifNull: 'not mounted')); } } @@ -2516,7 +2522,7 @@ class BuildOwner { /// element. /// * At this point, the element is considered "defunct" and will not be /// incorporated into the tree in the future. -abstract class Element implements BuildContext { +abstract class Element implements BuildContext, TreeDiagnostics { /// Creates an element that uses the given widget as its configuration. /// /// Typically called by an override of [Widget.createElement]. @@ -3291,52 +3297,60 @@ abstract class Element implements BuildContext { @override String toString() { - final List data = []; - debugFillDescription(data); + List data = []; + debugFillProperties(data); + data = data.where((DiagnosticsNode n) => !n.hidden).toList(); final String name = widget != null ? '${widget.runtimeType}' : '[$runtimeType]'; return '$name(${data.join("; ")})'; } - /// Add additional information to the given description for use by [toString]. + /// Add additional properties to the given description used by + /// [toDiagnosticNode], [toString] and [toStringDeep]. /// - /// This method makes it easier for subclasses to coordinate to provide a - /// high-quality [toString] implementation. The [toString] implementation on - /// the [State] base class calls [debugFillDescription] to collect useful + /// This method makes it easier for subclasses to coordinate to provide + /// high-quality diagnostic data. The [toString] implementation on + /// the [State] base class calls [debugFillProperties] to collect useful /// information from subclasses to incorporate into its return value. /// /// If you override this, make sure to start your method with a call to - /// `super.debugFillDescription(description)`. + /// `super.debugFillProperties(description)`. + /// + /// See also: + /// + /// * [TreeDiagnosticsMixin.debugFillProperties], which provides detailed + /// best practices for defining diagnostic properties. @protected @mustCallSuper - void debugFillDescription(List description) { - if (depth == null) - description.add('no depth'); - if (widget == null) { - description.add('no widget'); - } else { - if (widget.key != null) - description.add('${widget.key}'); - widget.debugFillDescription(description); + void debugFillProperties(List description) { + description.add(new ObjectFlagProperty('depth', depth, ifNull: 'no depth')); + description.add(new ObjectFlagProperty('widget', widget, ifNull: 'no widget')); + if (widget != null) { + description.add(new DiagnosticsProperty('key', widget?.key, showName: false, defaultValue: null)); + widget.debugFillProperties(description); } - if (dirty) - description.add('dirty'); + description.add(new FlagProperty('dirty', value: dirty, ifTrue: 'dirty')); } /// A detailed, textual description of this element, includings its children. + @override String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { - final StringBuffer result = new StringBuffer() - ..write(prefixLineOne) - ..write(this) - ..write('\n'); - final List children = []; - visitChildren(children.add); - if (children.isNotEmpty) { - final Element last = children.removeLast(); - for (Element child in children) - result.write(child.toStringDeep("$prefixOtherLines\u251C", "$prefixOtherLines\u2502")); - result.write(last.toStringDeep("$prefixOtherLines\u2514", "$prefixOtherLines ")); - } - return result.toString(); + return toDiagnosticsNode().toStringDeep(prefixLineOne, prefixOtherLines); + } + + @override + DiagnosticsNode toDiagnosticsNode({ String name, DiagnosticsTreeStyle style }) { + return new DiagnosticsNode.lazy( + name: name, + object: this, + getChildren: () { + final List children = []; + visitChildren((Element child) { + children.add(child.toDiagnosticsNode()); + }); + return children; + }, + style: style ?? DiagnosticsTreeStyle.dense, + ); } /// Returns true if the element has been marked as needing rebuilding. @@ -3479,9 +3493,9 @@ class ErrorWidget extends LeafRenderObjectWidget { RenderBox createRenderObject(BuildContext context) => new RenderErrorBox(message); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('message: ' + _stringify(message)); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('message', message, quoted: false)); } } @@ -3760,10 +3774,9 @@ class StatefulElement extends ComponentElement { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (state != null) - description.add('state: $state'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty>('state', state, defaultValue: null)); } } @@ -4428,10 +4441,9 @@ abstract class RenderObjectElement extends Element { void removeChildRenderObject(covariant RenderObject child); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (renderObject != null) - description.add('renderObject: $renderObject'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('renderObject', renderObject, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index 0ea72e1860..2492d8a143 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -613,27 +613,17 @@ class RawGestureDetectorState extends State { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); if (_recognizers == null) { - description.add('DISPOSED'); + description.add(new DiagnosticsNode.message('DISPOSED')); } else { final List gestures = _recognizers.values.map((GestureRecognizer recognizer) => recognizer.toStringShort()).toList(); if (gestures.isEmpty) gestures.add(''); - description.add('gestures: ${gestures.join(", ")}'); - } - switch (widget.behavior) { - case HitTestBehavior.translucent: - description.add('behavior: translucent'); - break; - case HitTestBehavior.opaque: - description.add('behavior: opaque'); - break; - case HitTestBehavior.deferToChild: - description.add('behavior: defer-to-child'); - break; + description.add(new IterableProperty('gestures', gestures)); } + description.add(new EnumProperty('behavior', widget.behavior, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/icon.dart b/packages/flutter/lib/src/widgets/icon.dart index 7161b882ab..8f09cdc2d6 100644 --- a/packages/flutter/lib/src/widgets/icon.dart +++ b/packages/flutter/lib/src/widgets/icon.dart @@ -114,16 +114,10 @@ class Icon extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (icon != null) { - description.add('$icon'); - } else { - description.add(''); - } - if (size != null) - description.add('size: $size'); - if (color != null) - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('icon', icon, ifNull: '', showName: false)); + description.add(new DoubleProperty('size', size, defaultValue: null)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/icon_theme.dart b/packages/flutter/lib/src/widgets/icon_theme.dart index e48a8832ed..f9732b4f7b 100644 --- a/packages/flutter/lib/src/widgets/icon_theme.dart +++ b/packages/flutter/lib/src/widgets/icon_theme.dart @@ -71,8 +71,8 @@ class IconTheme extends InheritedWidget { bool updateShouldNotify(IconTheme old) => data != old.data; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$data'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('data', data, showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/image.dart b/packages/flutter/lib/src/widgets/image.dart index 982f506a28..024c2a3f8b 100644 --- a/packages/flutter/lib/src/widgets/image.dart +++ b/packages/flutter/lib/src/widgets/image.dart @@ -284,25 +284,17 @@ class Image extends StatefulWidget { _ImageState createState() => new _ImageState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('image: $image'); - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); - if (color != null) - description.add('color: $color'); - if (colorBlendMode != null) - description.add('colorBlendMode: $colorBlendMode'); - if (fit != null) - description.add('fit: $fit'); - if (alignment != null) - description.add('alignment: $alignment'); - if (repeat != ImageRepeat.noRepeat) - description.add('repeat: $repeat'); - if (centerSlice != null) - description.add('centerSlice: $centerSlice'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('image', image)); + description.add(new DoubleProperty('width', width, defaultValue: null)); + description.add(new DoubleProperty('height', height, defaultValue: null)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); + description.add(new EnumProperty('colorBlendMode', colorBlendMode, defaultValue: null)); + description.add(new EnumProperty('fit', fit, defaultValue: null)); + description.add(new DiagnosticsProperty('alignment', alignment, defaultValue: null)); + description.add(new EnumProperty('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); + description.add(new DiagnosticsProperty('centerSlice', centerSlice, defaultValue: null)); } } @@ -374,9 +366,9 @@ class _ImageState extends State { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('stream: $_imageStream'); - description.add('pixels: $_imageInfo'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('stream', _imageStream)); + description.add(new DiagnosticsProperty('pixels', _imageInfo)); } } diff --git a/packages/flutter/lib/src/widgets/image_icon.dart b/packages/flutter/lib/src/widgets/image_icon.dart index e7f201cb17..d795f73d26 100644 --- a/packages/flutter/lib/src/widgets/image_icon.dart +++ b/packages/flutter/lib/src/widgets/image_icon.dart @@ -80,16 +80,10 @@ class ImageIcon extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (image != null) { - description.add('$image'); - } else { - description.add(''); - } - if (size != null) - description.add('size: $size'); - if (color != null) - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('image', image, ifNull: '', showName: false)); + description.add(new DoubleProperty('size', size, defaultValue: null)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/implicit_animations.dart b/packages/flutter/lib/src/widgets/implicit_animations.dart index 5aa13f8d47..75a6c517b9 100644 --- a/packages/flutter/lib/src/widgets/implicit_animations.dart +++ b/packages/flutter/lib/src/widgets/implicit_animations.dart @@ -179,9 +179,9 @@ abstract class ImplicitlyAnimatedWidget extends StatefulWidget { AnimatedWidgetBaseState createState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('duration: ${duration.inMilliseconds}ms'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new IntProperty('duration', duration.inMilliseconds, unit: 'ms')); } } @@ -392,22 +392,15 @@ class AnimatedContainer extends ImplicitlyAnimatedWidget { _AnimatedContainerState createState() => new _AnimatedContainerState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (alignment != null) - description.add('$alignment'); - if (padding != null) - description.add('padding: $padding'); - if (decoration != null) - description.add('bg: $decoration'); - if (foregroundDecoration != null) - description.add('fg: $foregroundDecoration'); - if (constraints != null) - description.add('$constraints'); - if (margin != null) - description.add('margin: $margin'); - if (transform != null) - description.add('has transform'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', alignment, showName: false, defaultValue: null)); + description.add(new DiagnosticsProperty('padding', padding, defaultValue: null)); + description.add(new DiagnosticsProperty('bg', decoration, defaultValue: null)); + description.add(new DiagnosticsProperty('fg', foregroundDecoration, defaultValue: null)); + description.add(new DiagnosticsProperty('constraints', constraints, defaultValue: null, showName: false)); + description.add(new DiagnosticsProperty('margin', margin, defaultValue: null)); + description.add(new ObjectFlagProperty.has('transform', transform)); } } @@ -446,22 +439,15 @@ class _AnimatedContainerState extends AnimatedWidgetBaseState } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (_alignment != null) - description.add('$_alignment'); - if (_padding != null) - description.add('padding: $_padding'); - if (_decoration != null) - description.add('bg: $_decoration'); - if (_foregroundDecoration != null) - description.add('fg: $_foregroundDecoration'); - if (_constraints != null) - description.add('$_constraints'); - if (_margin != null) - description.add('margin: $_margin'); - if (_transform != null) - description.add('has transform'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('alignment', _alignment, showName: false, defaultValue: null)); + description.add(new DiagnosticsProperty('padding', _padding, defaultValue: null)); + description.add(new DiagnosticsProperty('bg', _decoration, defaultValue: null)); + description.add(new DiagnosticsProperty('fg', _foregroundDecoration, defaultValue: null)); + description.add(new DiagnosticsProperty('constraints', _constraints, showName: false, defaultValue: null)); + description.add(new DiagnosticsProperty('margin', _margin, defaultValue: null)); + description.add(new ObjectFlagProperty.has('transform', _transform)); } } @@ -541,20 +527,14 @@ class AnimatedPositioned extends ImplicitlyAnimatedWidget { _AnimatedPositionedState createState() => new _AnimatedPositionedState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (left != null) - description.add('left: $left'); - if (top != null) - description.add('top: $top'); - if (right != null) - description.add('right: $right'); - if (bottom != null) - description.add('bottom: $bottom'); - if (width != null) - description.add('width: $width'); - if (height != null) - description.add('height: $height'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('left', left, defaultValue: null)); + description.add(new DoubleProperty('top', top, defaultValue: null)); + description.add(new DoubleProperty('right', right, defaultValue: null)); + description.add(new DoubleProperty('bottom', bottom, defaultValue: null)); + description.add(new DoubleProperty('width', width, defaultValue: null)); + description.add(new DoubleProperty('height', height, defaultValue: null)); } } @@ -590,20 +570,14 @@ class _AnimatedPositionedState extends AnimatedWidgetBaseState description) { - super.debugFillDescription(description); - if (_left != null) - description.add('has left'); - if (_top != null) - description.add('has top'); - if (_right != null) - description.add('has right'); - if (_bottom != null) - description.add('has bottom'); - if (_width != null) - description.add('has width'); - if (_height != null) - description.add('has height'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new ObjectFlagProperty>.has('left', _left)); + description.add(new ObjectFlagProperty>.has('top', _top)); + description.add(new ObjectFlagProperty>.has('right', _right)); + description.add(new ObjectFlagProperty>.has('bottom', _bottom)); + description.add(new ObjectFlagProperty>.has('width', _width)); + description.add(new ObjectFlagProperty>.has('height', _height)); } } @@ -641,9 +615,9 @@ class AnimatedOpacity extends ImplicitlyAnimatedWidget { _AnimatedOpacityState createState() => new _AnimatedOpacityState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('opacity: $opacity'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('opacity', opacity)); } } @@ -694,9 +668,9 @@ class AnimatedDefaultTextStyle extends ImplicitlyAnimatedWidget { _AnimatedDefaultTextStyleState createState() => new _AnimatedDefaultTextStyleState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - '$style'.split('\n').forEach(description.add); + void debugFillProperties(List description) { + super.debugFillProperties(description); + style?.debugFillProperties(description); } } @@ -775,13 +749,13 @@ class AnimatedPhysicalModel extends ImplicitlyAnimatedWidget { _AnimatedPhysicalModelState createState() => new _AnimatedPhysicalModelState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('shape: $shape'); - description.add('borderRadius: $borderRadius'); - description.add('elevation: ${elevation.toStringAsFixed(1)}'); - description.add('color: $color'); - description.add('animateColor: $animateColor'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('shape', shape)); + description.add(new DiagnosticsProperty('borderRadius', borderRadius)); + description.add(new DoubleProperty('elevation', elevation)); + description.add(new DiagnosticsProperty('color', color)); + description.add(new DiagnosticsProperty('animateColor', animateColor)); } } diff --git a/packages/flutter/lib/src/widgets/locale_query.dart b/packages/flutter/lib/src/widgets/locale_query.dart index bc156bd0e2..2e5c74380b 100644 --- a/packages/flutter/lib/src/widgets/locale_query.dart +++ b/packages/flutter/lib/src/widgets/locale_query.dart @@ -38,8 +38,8 @@ class LocaleQuery extends InheritedWidget { bool updateShouldNotify(LocaleQuery old) => data != old.data; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$data'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('data', data, showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/media_query.dart b/packages/flutter/lib/src/widgets/media_query.dart index 8d9fcc46ec..0ab43c7da9 100644 --- a/packages/flutter/lib/src/widgets/media_query.dart +++ b/packages/flutter/lib/src/widgets/media_query.dart @@ -193,8 +193,8 @@ class MediaQuery extends InheritedWidget { bool updateShouldNotify(MediaQuery old) => data != old.data; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$data'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('data', data, showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/overlay.dart b/packages/flutter/lib/src/widgets/overlay.dart index 54e5978afa..7ef0a579aa 100644 --- a/packages/flutter/lib/src/widgets/overlay.dart +++ b/packages/flutter/lib/src/widgets/overlay.dart @@ -370,9 +370,11 @@ class OverlayState extends State with TickerProviderStateMixin { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('entries: $_entries'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + // TODO(jacobr): use IterableProperty instead as that would + // provide a slightly more consistent string summary of the List. + description.add(new DiagnosticsProperty>('entries', _entries)); } } @@ -557,33 +559,39 @@ class _RenderTheatre extends RenderBox } @override - String debugDescribeChildren(String prefix) { - final StringBuffer result = new StringBuffer(); + List debugDescribeChildren() { + final List children = []; + if (child != null) - result - ..write(prefix) - ..write(' \u2502\n') - ..write(child.toStringDeep('$prefix \u251C\u2500onstage: ', '$prefix \u254E')); - if (firstChild != null) { + children.add(child.toDiagnosticsNode(name: 'onstage')); + + if (firstChild != null) { RenderBox child = firstChild; + int count = 1; - while (child != lastChild) { - result.write(child.toStringDeep("$prefix \u254E\u254Coffstage $count: ", "$prefix \u254E")); - count += 1; + while (true) { + children.add( + child.toDiagnosticsNode( + name: 'offstage $count', + style: DiagnosticsTreeStyle.offstage, + ), + ); + if (child == lastChild) + break; final StackParentData childParentData = child.parentData; child = childParentData.nextSibling; - } - if (child != null) { - assert(child == lastChild); - result.write(child.toStringDeep("$prefix \u2514\u254Coffstage $count: ", "$prefix ")); + count += 1; } } else { - result - ..write(prefix) - ..write(' \u2514\u254Cno offstage children'); + children.add( + new DiagnosticsNode.message( + 'no offstage children', + style: DiagnosticsTreeStyle.offstage, + ), + ); } - return result.toString(); - } + return children; + } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { diff --git a/packages/flutter/lib/src/widgets/overscroll_indicator.dart b/packages/flutter/lib/src/widgets/overscroll_indicator.dart index 266cf2123d..d28571e6d8 100644 --- a/packages/flutter/lib/src/widgets/overscroll_indicator.dart +++ b/packages/flutter/lib/src/widgets/overscroll_indicator.dart @@ -98,19 +98,21 @@ class GlowingOverscrollIndicator extends StatefulWidget { _GlowingOverscrollIndicatorState createState() => new _GlowingOverscrollIndicatorState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$axisDirection'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('axisDirection', axisDirection)); + String showDescription; if (showLeading && showTrailing) { - description.add('show: both sides'); + showDescription = 'both sides'; } else if (showLeading) { - description.add('show: leading side only'); + showDescription = 'leading side only'; } else if (showTrailing) { - description.add('show: trailing side only'); + showDescription = 'trailing side only'; } else { - description.add('show: neither side (!)'); + showDescription = 'neither side (!)'; } - description.add('$color'); + description.add(new MessageProperty('show', showDescription)); + description.add(new DiagnosticsProperty('color', color, showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/page_view.dart b/packages/flutter/lib/src/widgets/page_view.dart index 64be59cc2b..fd6f2647f2 100644 --- a/packages/flutter/lib/src/widgets/page_view.dart +++ b/packages/flutter/lib/src/widgets/page_view.dart @@ -495,12 +495,11 @@ class _PageViewState extends State { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('${widget.scrollDirection}'); - if (widget.reverse) - description.add('reversed'); - description.add('${widget.controller}'); - description.add('${widget.physics}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('scrollDirection', widget.scrollDirection)); + description.add(new FlagProperty('reverse', value: widget.reverse, ifTrue: 'reversed')); + description.add(new DiagnosticsProperty('controller', widget.controller, showName: false)); + description.add(new DiagnosticsProperty('physics', widget.physics, showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/primary_scroll_controller.dart b/packages/flutter/lib/src/widgets/primary_scroll_controller.dart index cc9c831f1b..c91f078ab0 100644 --- a/packages/flutter/lib/src/widgets/primary_scroll_controller.dart +++ b/packages/flutter/lib/src/widgets/primary_scroll_controller.dart @@ -54,8 +54,8 @@ class PrimaryScrollController extends InheritedWidget { bool updateShouldNotify(PrimaryScrollController old) => controller != old.controller; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('${controller ?? "no controller"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('controller', controller, ifNull: 'no controller', showName: false)); } } diff --git a/packages/flutter/lib/src/widgets/raw_keyboard_listener.dart b/packages/flutter/lib/src/widgets/raw_keyboard_listener.dart index 80dac9d000..5eb977a166 100644 --- a/packages/flutter/lib/src/widgets/raw_keyboard_listener.dart +++ b/packages/flutter/lib/src/widgets/raw_keyboard_listener.dart @@ -50,9 +50,9 @@ class RawKeyboardListener extends StatefulWidget { _RawKeyboardListenerState createState() => new _RawKeyboardListenerState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('focusNode: $focusNode'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('focusNode', focusNode)); } } diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index bbbd9b75d5..2da3fe39c6 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -379,11 +379,10 @@ class _ModalScopeStatus extends InheritedWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('${isCurrent ? "active" : "inactive"}'); - if (canPop) - description.add('can pop'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive')); + description.add(new FlagProperty('canPop', value: canPop, ifTrue: 'can pop')); } } diff --git a/packages/flutter/lib/src/widgets/scroll_configuration.dart b/packages/flutter/lib/src/widgets/scroll_configuration.dart index 1438f3b6ce..5a735d0d16 100644 --- a/packages/flutter/lib/src/widgets/scroll_configuration.dart +++ b/packages/flutter/lib/src/widgets/scroll_configuration.dart @@ -112,8 +112,8 @@ class ScrollConfiguration extends InheritedWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('behavior: $behavior'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('behavior', behavior)); } } diff --git a/packages/flutter/lib/src/widgets/scroll_view.dart b/packages/flutter/lib/src/widgets/scroll_view.dart index 50208bf02d..a3479e0871 100644 --- a/packages/flutter/lib/src/widgets/scroll_view.dart +++ b/packages/flutter/lib/src/widgets/scroll_view.dart @@ -222,19 +222,14 @@ abstract class ScrollView extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$scrollDirection'); - if (reverse) - description.add('reversed'); - if (controller != null) - description.add('$controller'); - if (primary) - description.add('using primary controller'); - if (physics != null) - description.add('$physics'); - if (shrinkWrap) - description.add('shrink-wrapping'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('scrollDirection', scrollDirection)); + description.add(new FlagProperty('reverse', value: reverse, ifTrue: 'reversed', showName: true)); + description.add(new DiagnosticsProperty('controller', controller, showName: false, defaultValue: null)); + description.add(new FlagProperty('primary', value: primary, ifTrue: 'using primary controller', showName: true)); + description.add(new DiagnosticsProperty('physics', physics, showName: false, defaultValue: null)); + description.add(new FlagProperty('shrinkWrap', value: shrinkWrap, ifTrue: 'shrink-wrapping', showName: true)); } } @@ -387,10 +382,9 @@ abstract class BoxScrollView extends ScrollView { Widget buildChildLayout(BuildContext context); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (padding != null) - description.add('padding: $padding'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('padding', padding, defaultValue: null)); } } @@ -681,10 +675,9 @@ class ListView extends BoxScrollView { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (itemExtent != null) - description.add('itemExtent: $itemExtent'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DoubleProperty('itemExtent', itemExtent, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 51ec6140b2..80e0dd1c7a 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -156,11 +156,10 @@ class Scrollable extends StatefulWidget { ScrollableState createState() => new ScrollableState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$axisDirection'); - if (physics != null) - description.add('physics: $physics'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('axisDirection', axisDirection)); + description.add(new DiagnosticsProperty('physics', physics)); } /// The state from the closest instance of this class that encloses the given context. @@ -485,8 +484,8 @@ class ScrollableState extends State with TickerProviderStateMixin } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('position: $position'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('position', position)); } } diff --git a/packages/flutter/lib/src/widgets/sliver.dart b/packages/flutter/lib/src/widgets/sliver.dart index fb3bd96bd7..a1026d59d5 100644 --- a/packages/flutter/lib/src/widgets/sliver.dart +++ b/packages/flutter/lib/src/widgets/sliver.dart @@ -355,9 +355,9 @@ abstract class SliverMultiBoxAdaptorWidget extends RenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('delegate: $delegate'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('delegate', delegate)); } } @@ -935,8 +935,8 @@ class KeepAlive extends ParentDataWidget { bool debugCanApplyOutOfTurn() => keepAlive; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('keepAlive: $keepAlive'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('keepAlive', keepAlive)); } } diff --git a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart index 62f6c59471..5e26ce0884 100644 --- a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart @@ -140,9 +140,9 @@ class SliverPersistentHeader extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('delegate: $delegate'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('delegate', delegate)); final List flags = []; if (pinned) flags.add('pinned'); @@ -150,7 +150,7 @@ class SliverPersistentHeader extends StatelessWidget { flags.add('floating'); if (flags.isEmpty) flags.add('normal'); - description.add('mode: ${flags.join(", ")}'); + description.add(new IterableProperty('mode', flags)); } } @@ -244,9 +244,9 @@ abstract class _SliverPersistentHeaderRenderObjectWidget extends RenderObjectWid _RenderSliverPersistentHeaderForWidgetsMixin createRenderObject(BuildContext context); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('delegate: $delegate'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('delegate', delegate)); } } diff --git a/packages/flutter/lib/src/widgets/table.dart b/packages/flutter/lib/src/widgets/table.dart index 6f302b6288..aea2407a70 100644 --- a/packages/flutter/lib/src/widgets/table.dart +++ b/packages/flutter/lib/src/widgets/table.dart @@ -376,8 +376,8 @@ class TableCell extends ParentDataWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('verticalAlignment: $verticalAlignment'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('verticalAlignment', verticalAlignment)); } } diff --git a/packages/flutter/lib/src/widgets/text.dart b/packages/flutter/lib/src/widgets/text.dart index a9b4313538..a82d525751 100644 --- a/packages/flutter/lib/src/widgets/text.dart +++ b/packages/flutter/lib/src/widgets/text.dart @@ -141,9 +141,9 @@ class DefaultTextStyle extends InheritedWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - '$style'.split('\n').forEach(description.add); + void debugFillProperties(List description) { + super.debugFillProperties(description); + style?.debugFillProperties(description); } } @@ -270,10 +270,9 @@ class Text extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('"$data"'); - if (style != null) - '$style'.split('\n').forEach(description.add); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('data', data, showName: false)); + style?.debugFillProperties(description); } } diff --git a/packages/flutter/lib/src/widgets/ticker_provider.dart b/packages/flutter/lib/src/widgets/ticker_provider.dart index 190ce3d404..5b22e85301 100644 --- a/packages/flutter/lib/src/widgets/ticker_provider.dart +++ b/packages/flutter/lib/src/widgets/ticker_provider.dart @@ -57,9 +57,9 @@ class TickerMode extends InheritedWidget { bool updateShouldNotify(TickerMode old) => enabled != old.enabled; @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('mode: ${ enabled ? "enabled" : "disabled" }'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new FlagProperty('mode', value: enabled, ifTrue: 'enabled', ifFalse: 'disabled', showName: true)); } } @@ -127,18 +127,20 @@ abstract class SingleTickerProviderStateMixin extends State implements } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); + void debugFillProperties(List description) { + super.debugFillProperties(description); + String tickerDescription; if (_ticker != null) { if (_ticker.isActive && _ticker.muted) - description.add('ticker active but muted'); + tickerDescription = 'active but muted'; else if (_ticker.isActive) - description.add('ticker active'); + tickerDescription = 'active'; else if (_ticker.muted) - description.add('ticker inactive and muted'); + tickerDescription = 'inactive and muted'; else - description.add('ticker inactive'); + tickerDescription = 'inactive'; } + description.add(new DiagnosticsProperty('ticker', _ticker, description: tickerDescription, showSeparator: false, defaultValue: null)); } } @@ -208,10 +210,16 @@ abstract class TickerProviderStateMixin extends State implements Ticker } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (_tickers != null) - description.add('tracking ${_tickers.length} ticker${_tickers.length == 1 ? "" : "s"}'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty>( + 'tickers', + _tickers, + description: _tickers != null ? + 'tracking ${_tickers.length} ticker${_tickers.length == 1 ? "" : "s"}' : + null, + defaultValue: null, + )); } } diff --git a/packages/flutter/lib/src/widgets/title.dart b/packages/flutter/lib/src/widgets/title.dart index 5ed94f9ef6..a4a869c3b5 100644 --- a/packages/flutter/lib/src/widgets/title.dart +++ b/packages/flutter/lib/src/widgets/title.dart @@ -40,11 +40,9 @@ class Title extends StatelessWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (title != null) - description.add('"$title"'); - if (color != null) - description.add('color: $color'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new StringProperty('title', title, defaultValue: null)); + description.add(new DiagnosticsProperty('color', color, defaultValue: null)); } } diff --git a/packages/flutter/lib/src/widgets/transitions.dart b/packages/flutter/lib/src/widgets/transitions.dart index bfd4ecc7a1..051978b5c5 100644 --- a/packages/flutter/lib/src/widgets/transitions.dart +++ b/packages/flutter/lib/src/widgets/transitions.dart @@ -58,9 +58,9 @@ abstract class AnimatedWidget extends StatefulWidget { _AnimatedState createState() => new _AnimatedState(); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('animation: $listenable'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new DiagnosticsProperty('animation', listenable)); } } diff --git a/packages/flutter/lib/src/widgets/viewport.dart b/packages/flutter/lib/src/widgets/viewport.dart index 71bc915649..c76d3a85dd 100644 --- a/packages/flutter/lib/src/widgets/viewport.dart +++ b/packages/flutter/lib/src/widgets/viewport.dart @@ -116,15 +116,15 @@ class Viewport extends MultiChildRenderObjectWidget { _ViewportElement createElement() => new _ViewportElement(this); @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$axisDirection'); - description.add('anchor: $anchor'); - description.add('offset: $offset'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('axisDirection', axisDirection)); + description.add(new DoubleProperty('anchor', anchor)); + description.add(new DiagnosticsProperty('offset', offset)); if (center != null) { - description.add('center: $center'); + description.add(new DiagnosticsProperty('center', center)); } else if (children.isNotEmpty && children.first.key != null) { - description.add('center: ${children.first.key} (implicit)'); + description.add(new DiagnosticsProperty('center', children.first.key, tooltip: 'implicit')); } } } @@ -239,9 +239,9 @@ class ShrinkWrappingViewport extends MultiChildRenderObjectWidget { } @override - void debugFillDescription(List description) { - super.debugFillDescription(description); - description.add('$axisDirection'); - description.add('offset: $offset'); + void debugFillProperties(List description) { + super.debugFillProperties(description); + description.add(new EnumProperty('axisDirection', axisDirection)); + description.add(new DiagnosticsProperty('offset', offset)); } } diff --git a/packages/flutter/test/foundation/tree_diagnostics_mixin_test.dart b/packages/flutter/test/foundation/tree_diagnostics_mixin_test.dart index 5d13673c6a..920fabe982 100644 --- a/packages/flutter/test/foundation/tree_diagnostics_mixin_test.dart +++ b/packages/flutter/test/foundation/tree_diagnostics_mixin_test.dart @@ -2,64 +2,1385 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; class TestTree extends Object with TreeDiagnosticsMixin { TestTree({ this.name, + this.style, this.children: const [], + this.properties: const [], }); final String name; final List children; + final List properties; + final DiagnosticsTreeStyle style; @override - String debugDescribeChildren(String prefix) { - final StringBuffer buffer = new StringBuffer(); - for (TestTree child in children) - buffer.write(child.toStringDeep('$prefix \u251C\u2500child ${child.name}: ', '$prefix \u2502')); - return buffer.toString(); + List debugDescribeChildren() { + final List children = []; + for (TestTree child in this.children) { + children.add(child.toDiagnosticsNode( + name: 'child ${child.name}', + style: child.style, + )); + } + return children; } + + @override + void debugFillProperties(List properties) { + properties.addAll(this.properties); + } +} + +enum ExampleEnum { + hello, + world, + deferToChild, } void main() { test('TreeDiagnosticsMixin control test', () async { - final TestTree tree = new TestTree( - children: [ - new TestTree(name: 'node A'), + void goldenStyleTest(String description, + {DiagnosticsTreeStyle style, + DiagnosticsTreeStyle lastChildStyle, + String golden = ''}) { + final TestTree tree = new TestTree(children: [ + new TestTree(name: 'node A', style: style), new TestTree( name: 'node B', children: [ - new TestTree(name: 'node B1'), - new TestTree(name: 'node B2'), - new TestTree(name: 'node B3'), + new TestTree(name: 'node B1', style: style), + new TestTree(name: 'node B2', style: style), + new TestTree(name: 'node B3', style: lastChildStyle ?? style), + ], + style: style, + ), + new TestTree(name: 'node C', style: lastChildStyle ?? style), + ], style: lastChildStyle); + + expect(tree, hasAGoodToStringDeep); + expect( + tree.toDiagnosticsNode(style: style).toStringDeep(), + equalsIgnoringHashCodes(golden), + reason: description, + ); + } + + goldenStyleTest( + 'dense', + style: DiagnosticsTreeStyle.dense, + 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' + '└child node C: TestTree#00000\n', + ); + + goldenStyleTest( + 'sparse', + style: DiagnosticsTreeStyle.sparse, + 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' + ' └─child node C: TestTree#00000\n', + ); + + goldenStyleTest( + 'dashed', + style: DiagnosticsTreeStyle.offstage, + 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' + ' └╌child node C: TestTree#00000\n', + ); + + goldenStyleTest( + 'leaf children', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.transition, + 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 ═══\n' + ' │ ║ TestTree#00000\n' + ' │ ╚═══════════\n' + ' ╘═╦══ child node C ═══\n' + ' ║ TestTree#00000\n' + ' ╚═══════════\n', + ); + + // You would never really want to make everything a leaf 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', + style: DiagnosticsTreeStyle.transition, + golden: + 'TestTree#00000:\n' + ' ╞═╦══ child node A ═══\n' + ' │ ║ TestTree#00000\n' + ' │ ╚═══════════\n' + ' ╞═╦══ child node B ═══\n' + ' │ ║ TestTree#00000:\n' + ' │ ║ ╞═╦══ child node B1 ═══\n' + ' │ ║ │ ║ TestTree#00000\n' + ' │ ║ │ ╚═══════════\n' + ' │ ║ ╞═╦══ child node B2 ═══\n' + ' │ ║ │ ║ TestTree#00000\n' + ' │ ║ │ ╚═══════════\n' + ' │ ║ ╘═╦══ child node B3 ═══\n' + ' │ ║ ║ TestTree#00000\n' + ' │ ║ ╚═══════════\n' + ' │ ╚═══════════\n' + ' ╘═╦══ child node C ═══\n' + ' ║ TestTree#00000\n' + ' ╚═══════════\n', + ); + + goldenStyleTest( + 'whitespace', + style: DiagnosticsTreeStyle.whitespace, + 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' + ' child node C: TestTree#00000\n', + ); + + // Single line mode does not display children. + goldenStyleTest( + 'single line', + style: DiagnosticsTreeStyle.singleLine, + golden: 'TestTree#00000', + ); + }); + + test('TreeDiagnosticsMixin tree with properties test', () async { + void goldenStyleTest(String description, { + DiagnosticsTreeStyle style, + DiagnosticsTreeStyle lastChildStyle, + @required String golden, + }) { + final TestTree tree = new TestTree( + properties: [ + new StringProperty('stringProperty1', 'value1', quoted: false), + new DoubleProperty('doubleProperty1', 42.5), + new DoubleProperty('roundedProperty', 1.0 / 3.0), + new StringProperty('DO_NOT_SHOW', 'DO_NOT_SHOW', hidden: true, quoted: false), + new DiagnosticsProperty('DO_NOT_SHOW_NULL', null, defaultValue: null), + new DiagnosticsProperty('nullProperty', null), + new StringProperty('node_type', '', showName: false, quoted: false), + ], + children: [ + new TestTree(name: 'node A', style: style), + new TestTree( + name: 'node B', + properties: [ + new StringProperty('p1', 'v1', quoted: false), + new StringProperty('p2', 'v2', quoted: false), + ], + children: [ + new TestTree(name: 'node B1', style: style), + new TestTree( + name: 'node B2', + properties: [new StringProperty('property1', 'value1', quoted: false)], + style: style, + ), + new TestTree( + name: 'node B3', + properties: [ + new StringProperty('node_type', '', showName: false, quoted: false), + new IntProperty('foo', 42), + ], + style: lastChildStyle ?? style, + ), + ], + style: style, + ), + new TestTree( + name: 'node C', + properties: [ + new StringProperty('foo', 'multi\nline\nvalue!', quoted: false), + ], + style: lastChildStyle ?? style, + ), + ], + style: lastChildStyle, + ); + + expect(tree, hasAGoodToStringDeep); + expect( + tree.toDiagnosticsNode(style: style).toStringDeep(), + equalsIgnoringHashCodes(golden), + reason: description, + ); + } + + goldenStyleTest( + 'sparse', + style: DiagnosticsTreeStyle.sparse, + 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', + ); + + goldenStyleTest( + 'dense', + style: DiagnosticsTreeStyle.dense, + 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' + '│└child node B3: TestTree#00000\n' + '│ \n' + '│ foo: 42\n' + '└child node C: TestTree#00000\n' + ' foo:\n' + ' multi\n' + ' line\n' + ' value!\n', + ); + + goldenStyleTest( + 'dashed', + style: DiagnosticsTreeStyle.offstage, + 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', + ); + + goldenStyleTest( + 'leaf children', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.transition, + 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:\n' + ' │ ║ \n' + ' │ ║ foo: 42\n' + ' │ ╚═══════════\n' + ' ╘═╦══ child node C ═══\n' + ' ║ TestTree#00000:\n' + ' ║ foo:\n' + ' ║ multi\n' + ' ║ line\n' + ' ║ value!\n' + ' ╚═══════════\n', + ); + + // You would never really want to make everything a leaf 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', + style: DiagnosticsTreeStyle.transition, + golden: + 'TestTree#00000:\n' + ' stringProperty1: value1\n' + ' doubleProperty1: 42.5\n' + ' roundedProperty: 0.3\n' + ' nullProperty: null\n' + ' \n' + ' ╞═╦══ child node A ═══\n' + ' │ ║ TestTree#00000\n' + ' │ ╚═══════════\n' + ' ╞═╦══ child node B ═══\n' + ' │ ║ TestTree#00000:\n' + ' │ ║ p1: v1\n' + ' │ ║ p2: v2\n' + ' │ ║ ╞═╦══ child node B1 ═══\n' + ' │ ║ │ ║ TestTree#00000\n' + ' │ ║ │ ╚═══════════\n' + ' │ ║ ╞═╦══ child node B2 ═══\n' + ' │ ║ │ ║ TestTree#00000:\n' + ' │ ║ │ ║ property1: value1\n' + ' │ ║ │ ╚═══════════\n' + ' │ ║ ╘═╦══ child node B3 ═══\n' + ' │ ║ ║ TestTree#00000:\n' + ' │ ║ ║ \n' + ' │ ║ ║ foo: 42\n' + ' │ ║ ╚═══════════\n' + ' │ ╚═══════════\n' + ' ╘═╦══ child node C ═══\n' + ' ║ TestTree#00000:\n' + ' ║ foo:\n' + ' ║ multi\n' + ' ║ line\n' + ' ║ value!\n' + ' ╚═══════════\n', + ); + + goldenStyleTest( + 'whitespace', + style: DiagnosticsTreeStyle.whitespace, + 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', + style: DiagnosticsTreeStyle.singleLine, + golden: 'TestTree#00000(stringProperty1: value1, doubleProperty1: 42.5, roundedProperty: 0.3, nullProperty: null, )', + ); + + // There isn't anything interesting for this case as the children look the + // same with and without children. TODO(jacobr): this is an ugly test case. + // only difference is odd not clearly desirable density of B3 being right + // next to node C. + goldenStyleTest( + 'single line last child', + style: DiagnosticsTreeStyle.sparse, + lastChildStyle: DiagnosticsTreeStyle.singleLine, + 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(, foo: 42)\n' + ' └─child node C: TestTree#00000(foo:\n' + ' multi\n' + ' line\n' + ' value!)\n', + ); + }); + + test('transition test', () { + // Test multiple styles integrating together in the same tree due to using + // transition to go between styles that would otherwise be incompatible. + final TestTree tree = new TestTree( + style: DiagnosticsTreeStyle.sparse, + properties: [ + new StringProperty('stringProperty1', 'value1'), + ], + children: [ + new TestTree( + style: DiagnosticsTreeStyle.transition, + name: 'node transition', + properties: [ + new StringProperty('p1', 'v1'), + new TestTree( + properties: [ + new DiagnosticsProperty('survived', true), + ], + ).toDiagnosticsNode(name: 'tree property', style: DiagnosticsTreeStyle.whitespace), + ], + children: [ + new TestTree(name: 'dense child', style: DiagnosticsTreeStyle.dense), + new TestTree( + name: 'dense', + properties: [new StringProperty('property1', 'value1')], + style: DiagnosticsTreeStyle.dense, + ), + new TestTree( + name: 'node B3', + properties: [ + new StringProperty('node_type', '', showName: false, quoted: false), + new IntProperty('foo', 42), + ], + style: DiagnosticsTreeStyle.dense + ), ], ), - new TestTree(name: 'node C'), + new TestTree( + name: 'node C', + properties: [ + new StringProperty('foo', 'multi\nline\nvalue!', quoted: false), + ], + style: DiagnosticsTreeStyle.sparse, + ), ], ); - // The final line in the tree is a problem as it contains nothing but - // a vertical line character. - expect(tree, isNot(hasAGoodToStringDeep)); + expect(tree, hasAGoodToStringDeep); expect( - tree.toStringDeep(), + tree.toDiagnosticsNode().toStringDeep(), equalsIgnoringHashCodes( - '''TestTree#00000 - ├─child node A: TestTree#00000 - │ - ├─child node B: TestTree#00000 - │ ├─child node B1: TestTree#00000 - │ │ - │ ├─child node B2: TestTree#00000 - │ │ - │ ├─child node B3: TestTree#00000 - │ │ - ├─child node C: TestTree#00000 - │ -''', + 'TestTree#00000\n' + ' │ stringProperty1: "value1"\n' + ' ╞═╦══ child node transition ═══\n' + ' │ ║ TestTree#00000:\n' + ' │ ║ p1: "v1"\n' + ' │ ║ tree property: TestTree#00000:\n' + ' │ ║ survived: true\n' + ' │ ║ ├child dense child: TestTree#00000\n' + ' │ ║ ├child dense: TestTree#00000\n' + ' │ ║ │ property1: "value1"\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', ), ); }); + + test('describeEnum test', () { + expect(describeEnum(ExampleEnum.hello), equals('hello')); + expect(describeEnum(ExampleEnum.world), equals('world')); + expect(describeEnum(ExampleEnum.deferToChild), equals('deferToChild')); + }); + + test('toHyphenedName test', () { + expect(camelCaseToHyphenatedName(''), equals('')); + expect(camelCaseToHyphenatedName('hello'), equals('hello')); + expect(camelCaseToHyphenatedName('Hello'), equals('hello')); + expect(camelCaseToHyphenatedName('HELLO'), equals('h-e-l-l-o')); + expect(camelCaseToHyphenatedName('deferToChild'), equals('defer-to-child')); + expect(camelCaseToHyphenatedName('DeferToChild'), equals('defer-to-child')); + expect(camelCaseToHyphenatedName('helloWorld'), equals('hello-world')); + }); + + test('string property test', () { + expect( + new StringProperty('name', 'value', quoted: false).toString(), + equals('name: value'), + ); + + expect( + new StringProperty( + 'name', + 'value', + description: 'VALUE', + ifEmpty: '', + quoted: false, + ).toString(), + equals('name: VALUE'), + ); + + expect( + new StringProperty( + 'name', + 'value', + showName: false, + ifEmpty: '', + quoted: false, + ).toString(), + equals('value'), + ); + + expect( + new StringProperty('name', '', ifEmpty: '').toString(), + equals('name: '), + ); + + expect( + new StringProperty( + 'name', + '', + ifEmpty: '', + showName: false, + ).toString(), + equals(''), + ); + + expect(new StringProperty('name', null).hidden, isFalse); + expect(new StringProperty('name', 'value', hidden: true).hidden, isTrue); + expect(new StringProperty('name', null, defaultValue: null).hidden, isTrue); + expect( + new StringProperty( + 'name', + 'value', + quoted: true, + ).toString(), + equals('name: "value"'), + ); + + expect( + new StringProperty('name', 'value', showName: false).toString(), + equals('"value"'), + ); + + expect( + new StringProperty( + 'name', + null, + showName: false, + quoted: true, + ).toString(), + equals('null'), + ); + }); + + test('bool property test', () { + final DiagnosticsProperty trueProperty = new DiagnosticsProperty('name', true); + final DiagnosticsProperty falseProperty = new DiagnosticsProperty('name', false); + expect(trueProperty.toString(), equals('name: true')); + expect(trueProperty.hidden, isFalse); + expect(trueProperty.object, isTrue); + expect(falseProperty.toString(), equals('name: false')); + expect(falseProperty.object, isFalse); + expect(falseProperty.hidden, isFalse); + expect( + new DiagnosticsProperty( + 'name', + true, + description: 'truthy', + ).toString(), + equals('name: truthy'), + ); + expect( + new DiagnosticsProperty('name', true, showName: false).toString(), + equals('true'), + ); + + expect(new DiagnosticsProperty('name', null).hidden, isFalse); + expect(new DiagnosticsProperty('name', true, hidden: true).hidden, isTrue); + expect(new DiagnosticsProperty('name', null, defaultValue: null).hidden, isTrue); + expect( + new DiagnosticsProperty('name', null, ifNull: 'missing').toString(), + equals('name: missing'), + ); + }); + + test('flag property test', () { + final FlagProperty trueFlag = new FlagProperty( + 'myFlag', + value: true, + ifTrue: 'myFlag', + ); + final FlagProperty falseFlag = new FlagProperty( + 'myFlag', + value: false, + ifTrue: 'myFlag', + ); + expect(trueFlag.toString(), equals('myFlag')); + + expect(trueFlag.object, isTrue); + expect(falseFlag.object, isFalse); + + expect(trueFlag.hidden, isFalse); + expect(falseFlag.hidden, isTrue); + }); + + test('property with tooltip test', () { + final DiagnosticsProperty withTooltip = new DiagnosticsProperty( + 'name', + 'value', + tooltip: 'tooltip', + ); + expect( + withTooltip.toString(), + equals('name: value (tooltip)'), + ); + expect(withTooltip.object, equals('value')); + expect(withTooltip.hidden, isFalse); + }); + + test('double property test', () { + final DoubleProperty doubleProperty = new DoubleProperty( + 'name', + 42.0, + ); + expect(doubleProperty.toString(), equals('name: 42.0')); + expect(doubleProperty.hidden, isFalse); + expect(doubleProperty.object, equals(42.0)); + + expect(new DoubleProperty('name', 1.3333).toString(), equals('name: 1.3')); + + expect(new DoubleProperty('name', null).toString(), equals('name: null')); + expect(new DoubleProperty('name', null).hidden, equals(false)); + + expect( + new DoubleProperty('name', null, ifNull: 'missing').toString(), + equals('name: missing'), + ); + + expect( + new DoubleProperty('name', 42.0, unit: 'px', + ).toString(), + equals('name: 42.0px'), + ); + }); + + + test('unsafe double property test', () { + final DoubleProperty safe = new DoubleProperty.lazy( + 'name', + () => 42.0, + ); + expect(safe.toString(), equals('name: 42.0')); + expect(safe.hidden, isFalse); + expect(safe.object, equals(42.0)); + + expect( + new DoubleProperty.lazy('name', () => 1.3333).toString(), + equals('name: 1.3'), + ); + + expect( + new DoubleProperty.lazy('name', () => null).toString(), + equals('name: null'), + ); + expect( + new DoubleProperty.lazy('name', () => null).hidden, + equals(false), + ); + + final DoubleProperty throwingProperty = new DoubleProperty.lazy( + 'name', + () => throw new FlutterError('Invalid constraints'), + ); + // TODO(jacobr): it would be better if throwingProperty.object threw an + // exception. + expect(throwingProperty.object, isNull); + expect(throwingProperty.hidden, isFalse); + expect( + throwingProperty.toString(), + equals('name: EXCEPTION (FlutterError)'), + ); + }); + + test('percent property', () { + expect( + new PercentProperty('name', 0.4).toString(), + equals('name: 40.0%'), + ); + + expect( + new PercentProperty('name', 0.99, unit: 'invisible', tooltip: 'almost transparent').toString(), + equals('name: 99.0% invisible (almost transparent)'), + ); + + expect( + new PercentProperty('name', null, unit: 'invisible', tooltip: '!').toString(), + equals('name: null (!)'), + ); + + expect( + new PercentProperty('name', 0.4).object, + 0.4, + ); + expect( + new PercentProperty('name', 0.0).toString(), + equals('name: 0.0%'), + ); + expect( + new PercentProperty('name', -10.0).toString(), + equals('name: 0.0%'), + ); + expect( + new PercentProperty('name', 1.0).toString(), + equals('name: 100.0%'), + ); + expect( + new PercentProperty('name', 3.0).toString(), + equals('name: 100.0%'), + ); + expect( + new PercentProperty('name', null).toString(), + equals('name: null'), + ); + expect( + new PercentProperty( + 'name', + null, + ifNull: 'missing', + ).toString(), + equals('name: missing'), + ); + expect( + new PercentProperty( + 'name', + null, + ifNull: 'missing', + showName: false, + ).toString(), + equals('missing'), + ); + expect( + new PercentProperty( + 'name', + 0.5, + showName: false, + ).toString(), + equals('50.0%'), + ); + }); + + test('callback property test', () { + final Function onClick = () {}; + final ObjectFlagProperty present = new ObjectFlagProperty( + 'onClick', + onClick, + ifPresent: 'clickable', + ); + final ObjectFlagProperty missing = new ObjectFlagProperty( + 'onClick', + null, + ifPresent: 'clickable', + ); + + expect(present.toString(), equals('clickable')); + expect(present.hidden, isFalse); + expect(present.object, equals(onClick)); + expect(missing.toString(), equals('')); + expect(missing.hidden, isTrue); + }); + + test('missing callback property test', () { + final Function onClick = () {}; + final ObjectFlagProperty present = new ObjectFlagProperty( + 'onClick', + onClick, + ifNull: 'disabled', + ); + final ObjectFlagProperty missing = new ObjectFlagProperty( + 'onClick', + null, + ifNull: 'disabled', + ); + + expect(present.toString(), equals('')); + expect(present.hidden, isTrue); + expect(present.object, equals(onClick)); + expect(missing.toString(), equals('disabled')); + expect(missing.hidden, isFalse); + }); + + test('describe bool property', () { + final FlagProperty yes = new FlagProperty( + 'name', + value: true, + ifTrue: 'YES', + ifFalse: 'NO', + showName: true, + ); + final FlagProperty no = new FlagProperty( + 'name', + value: false, + ifTrue: 'YES', + ifFalse: 'NO', + showName: true, + ); + expect(yes.toString(), equals('name: YES')); + expect(yes.hidden, isFalse); + expect(yes.object, isTrue); + expect(no.toString(), equals('name: NO')); + expect(no.hidden, isFalse); + expect(no.object, isFalse); + + expect( + new FlagProperty( + 'name', + value: true, + ifTrue: 'YES', + ifFalse: 'NO', + ).toString(), + equals('YES'), + ); + + expect( + new FlagProperty( + 'name', + value: false, + ifTrue: 'YES', + ifFalse: 'NO', + ).toString(), + equals('NO'), + ); + + expect( + new FlagProperty( + 'name', + value: true, + ifTrue: 'YES', + ifFalse: 'NO', + hidden: true, + showName: true, + ).hidden, + isTrue, + ); + }); + + test('enum property test', () { + final EnumProperty hello = new EnumProperty( + 'name', + ExampleEnum.hello, + ); + final EnumProperty world = new EnumProperty( + 'name', + ExampleEnum.world, + ); + final EnumProperty deferToChild = new EnumProperty( + 'name', + ExampleEnum.deferToChild, + ); + final EnumProperty nullEnum = new EnumProperty( + 'name', + null, + ); + expect(hello.hidden, isFalse); + expect(hello.object, equals(ExampleEnum.hello)); + expect(hello.toString(), equals('name: hello')); + + expect(world.hidden, isFalse); + expect(world.object, equals(ExampleEnum.world)); + expect(world.toString(), equals('name: world')); + + expect(deferToChild.hidden, isFalse); + expect(deferToChild.object, equals(ExampleEnum.deferToChild)); + expect(deferToChild.toString(), equals('name: defer-to-child')); + + expect(nullEnum.hidden, isFalse); + expect(nullEnum.object, isNull); + expect(nullEnum.toString(), equals('name: null')); + + final EnumProperty matchesDefault = new EnumProperty( + 'name', + ExampleEnum.hello, + defaultValue: ExampleEnum.hello, + ); + expect(matchesDefault.toString(), equals('name: hello')); + expect(matchesDefault.object, equals(ExampleEnum.hello)); + expect(matchesDefault.hidden, isTrue); + + + expect( + new EnumProperty( + 'name', + ExampleEnum.hello, + hidden: true, + ).hidden, + isTrue, + ); + }); + + test('int property test', () { + final IntProperty regular = new IntProperty( + 'name', + 42, + ); + expect(regular.toString(), equals('name: 42')); + expect(regular.object, equals(42)); + expect(regular.hidden, isFalse); + + final IntProperty nullValue = new IntProperty( + 'name', + null, + ); + expect(nullValue.toString(), equals('name: null')); + expect(nullValue.object, isNull); + expect(nullValue.hidden, isFalse); + + final IntProperty hideNull = new IntProperty( + 'name', + null, + defaultValue: null + ); + expect(hideNull.toString(), equals('name: null')); + expect(hideNull.object, isNull); + expect(hideNull.hidden, isTrue); + + final IntProperty nullDescription = new IntProperty( + 'name', + null, + ifNull: 'missing', + ); + expect(nullDescription.toString(), equals('name: missing')); + expect(nullDescription.object, isNull); + expect(nullDescription.hidden, isFalse); + + final IntProperty hideName = new IntProperty( + 'name', + 42, + showName: false, + ); + expect(hideName.toString(), equals('42')); + expect(hideName.object, equals(42)); + expect(hideName.hidden, isFalse); + + final IntProperty withUnit = new IntProperty( + 'name', + 42, + unit: 'pt', + ); + expect(withUnit.toString(), equals('name: 42pt')); + expect(withUnit.object, equals(42)); + expect(withUnit.hidden, isFalse); + + final IntProperty defaultValue = new IntProperty( + 'name', + 42, + defaultValue: 42, + ); + expect(defaultValue.toString(), equals('name: 42')); + expect(defaultValue.object, equals(42)); + expect(defaultValue.hidden, isTrue); + + final IntProperty notDefaultValue = new IntProperty( + 'name', + 43, + defaultValue: 42, + ); + expect(notDefaultValue.toString(), equals('name: 43')); + expect(notDefaultValue.object, equals(43)); + expect(notDefaultValue.hidden, isFalse); + + final IntProperty hidden = new IntProperty( + 'name', + 42, + hidden: true, + ); + expect(hidden.toString(), equals('name: 42')); + expect(hidden.object, equals(42)); + expect(hidden.hidden, isTrue); + }); + + test('object property test', () { + final Rect rect = new Rect.fromLTRB(0.0, 0.0, 20.0, 20.0); + final DiagnosticsNode simple = new DiagnosticsProperty( + 'name', + rect, + ); + expect(simple.object, equals(rect)); + expect(simple.hidden, isFalse); + expect(simple.toString(), equals('name: Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)')); + + final DiagnosticsNode withDescription = new DiagnosticsProperty( + 'name', + rect, + description: 'small rect', + ); + expect(withDescription.object, equals(rect)); + expect(withDescription.hidden, isFalse); + expect(withDescription.toString(), equals('name: small rect')); + + final DiagnosticsProperty nullProperty = new DiagnosticsProperty( + 'name', + null, + ); + expect(nullProperty.object, isNull); + expect(nullProperty.hidden, isFalse); + expect(nullProperty.toString(), equals('name: null')); + + final DiagnosticsProperty hideNullProperty = new DiagnosticsProperty( + 'name', + null, + defaultValue: null, + ); + expect(hideNullProperty.object, isNull); + expect(hideNullProperty.hidden, isTrue); + expect(hideNullProperty.toString(), equals('name: null')); + + final DiagnosticsNode nullDescription = new DiagnosticsProperty( + 'name', + null, + ifNull: 'missing', + ); + expect(nullDescription.object, isNull); + expect(nullDescription.hidden, isFalse); + expect(nullDescription.toString(), equals('name: missing')); + + final DiagnosticsProperty hideName = new DiagnosticsProperty( + 'name', + rect, + showName: false, + ); + expect(hideName.object, equals(rect)); + expect(hideName.hidden, isFalse); + expect(hideName.toString(), equals('Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)')); + + final DiagnosticsProperty hideSeparator = new DiagnosticsProperty( + 'Creator', + rect, + showSeparator: false, + ); + expect(hideSeparator.object, equals(rect)); + expect(hideSeparator.hidden, isFalse); + expect( + hideSeparator.toString(), + equals('Creator Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)'), + ); + }); + + test('lazy object property test', () { + final Rect rect = new Rect.fromLTRB(0.0, 0.0, 20.0, 20.0); + final DiagnosticsNode simple = new DiagnosticsProperty.lazy( + 'name', + () => rect, + description: 'small rect', + ); + expect(simple.object, equals(rect)); + expect(simple.hidden, isFalse); + expect(simple.toString(), equals('name: small rect')); + + final DiagnosticsNode nullProperty = new DiagnosticsProperty.lazy( + 'name', + () => null, + description: 'missing', + ); + expect(nullProperty.object, isNull); + expect(nullProperty.hidden, isFalse); + expect(nullProperty.toString(), equals('name: missing')); + + final DiagnosticsNode hideNullProperty = new DiagnosticsProperty.lazy( + 'name', + () => null, + description: 'missing', + defaultValue: null, + ); + expect(hideNullProperty.object, isNull); + expect(hideNullProperty.hidden, isTrue); + expect(hideNullProperty.toString(), equals('name: missing')); + + final DiagnosticsNode hideName = new DiagnosticsProperty.lazy( + 'name', + () => rect, + description: 'small rect', + showName: false, + ); + expect(hideName.object, equals(rect)); + expect(hideName.hidden, isFalse); + expect(hideName.toString(), equals('small rect')); + + final DiagnosticsProperty throwingWithDescription = new DiagnosticsProperty.lazy( + 'name', + () => throw new FlutterError('Property not available'), + description: 'missing', + defaultValue: null, + ); + expect(throwingWithDescription.object, isNull); + expect(throwingWithDescription.exception, isFlutterError); + expect(throwingWithDescription.hidden, false); + expect(throwingWithDescription.toString(), equals('name: missing')); + + final DiagnosticsProperty throwingProperty = new DiagnosticsProperty.lazy( + 'name', + () => throw new FlutterError('Property not available'), + defaultValue: null, + ); + expect(throwingProperty.object, isNull); + expect(throwingProperty.exception, isFlutterError); + expect(throwingProperty.hidden, false); + expect(throwingProperty.toString(), equals('name: EXCEPTION (FlutterError)')); + + }); + + test('color property test', () { + // Add more tests if colorProperty becomes more than a wrapper around + // objectProperty. + final Color color = const Color.fromARGB(255, 255, 255, 255); + final DiagnosticsProperty simple = new DiagnosticsProperty( + 'name', + color, + ); + expect(simple.hidden, isFalse); + expect(simple.object, equals(color)); + expect(simple.toString(), equals('name: Color(0xffffffff)')); + }); + + test('flag property test', () { + final FlagProperty show = new FlagProperty( + 'wasLayout', + value: true, + ifTrue: 'layout computed', + ); + expect(show.name, equals('wasLayout')); + expect(show.object, isTrue); + expect(show.hidden, isFalse); + expect(show.toString(), equals('layout computed')); + + final FlagProperty hide = new FlagProperty( + 'wasLayout', + value: false, + ifTrue: 'layout computed', + ); + expect(hide.name, equals('wasLayout')); + expect(hide.object, isFalse); + expect(hide.hidden, isTrue); + expect(hide.toString(), equals('')); + }); + + test('has property test', () { + final Function onClick = () {}; + final ObjectFlagProperty has = new ObjectFlagProperty.has( + 'onClick', + onClick, + ); + expect(has.name, equals('onClick')); + expect(has.object, equals(onClick)); + expect(has.hidden, isFalse); + expect(has.toString(), equals('has onClick')); + + final ObjectFlagProperty missing = new ObjectFlagProperty.has( + 'onClick', + null, + ); + expect(missing.name, equals('onClick')); + expect(missing.object, isNull); + expect(missing.hidden, isTrue); + expect(missing.toString(), equals('')); + }); + + test('iterable property test', () { + final List ints = [1,2,3]; + final IterableProperty intsProperty = new IterableProperty( + 'ints', + ints, + ); + expect(intsProperty.object, equals(ints)); + expect(intsProperty.hidden, isFalse); + expect(intsProperty.toString(), equals('ints: 1, 2, 3')); + + final IterableProperty emptyProperty = new IterableProperty( + 'name', + [], + ); + expect(emptyProperty.object, isEmpty); + expect(emptyProperty.hidden, isFalse); + expect(emptyProperty.toString(), equals('name: []')); + + final IterableProperty nullProperty = new IterableProperty( + 'list', + null, + ); + expect(nullProperty.object, isNull); + expect(nullProperty.hidden, isFalse); + expect(nullProperty.toString(), equals('list: null')); + + final IterableProperty hideNullProperty = new IterableProperty( + 'list', + null, + defaultValue: null, + ); + expect(hideNullProperty.object, isNull); + expect(hideNullProperty.hidden, isTrue); + expect(hideNullProperty.toString(), equals('list: null')); + + final List objects = [ + new Rect.fromLTRB(0.0, 0.0, 20.0, 20.0), + const Color.fromARGB(255, 255, 255, 255), + ]; + final IterableProperty objectsProperty = new IterableProperty( + 'objects', + objects, + ); + expect(objectsProperty.object, equals(objects)); + expect(objectsProperty.hidden, isFalse); + expect( + objectsProperty.toString(), + equals('objects: Rect.fromLTRB(0.0, 0.0, 20.0, 20.0), Color(0xffffffff)'), + ); + expect( + objectsProperty.toStringDeep(), + equals('objects: Rect.fromLTRB(0.0, 0.0, 20.0, 20.0), Color(0xffffffff)'), + ); + + final IterableProperty multiLineProperty = new IterableProperty( + 'objects', + objects, + style: DiagnosticsTreeStyle.whitespace, + ); + expect(multiLineProperty.object, equals(objects)); + expect(multiLineProperty.hidden, isFalse); + expect( + multiLineProperty.toString(), + equals( + 'objects:\n' + 'Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)\n' + 'Color(0xffffffff)', + ), + ); + expect( + multiLineProperty.toStringDeep(), + equals( + 'objects:\n' + ' Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)\n' + ' Color(0xffffffff)\n', + ), + ); + + expect( + new TestTree( + name: 'root', + properties: [multiLineProperty], + ).toStringDeep(), + equalsIgnoringHashCodes( + 'TestTree#00000\n' + ' objects:\n' + ' Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)\n' + ' Color(0xffffffff)\n', + ), + ); + + // Iterable with a single entry. Verify that rendering is sensible and that + // multi line rendering isn't used even though it is not helpful. + final List singleElementList = [const Color.fromARGB(255, 255, 255, 255)]; + + final IterableProperty objectProperty = new IterableProperty( + 'object', + singleElementList, + style: DiagnosticsTreeStyle.whitespace, + ); + expect(objectProperty.object, equals(singleElementList)); + expect(objectProperty.hidden, isFalse); + expect( + objectProperty.toString(), + equals('object: Color(0xffffffff)'), + ); + expect( + objectProperty.toStringDeep(), + equals('object: Color(0xffffffff)\n'), + ); + expect( + new TestTree( + name: 'root', + properties: [objectProperty], + ).toStringDeep(), + equalsIgnoringHashCodes( + 'TestTree#00000\n' + ' object: Color(0xffffffff)\n', + ), + ); + }); + + test('message test', () { + final DiagnosticsNode message = new DiagnosticsNode.message('hello world'); + expect(message.toString(), equals('hello world')); + expect(message.name, isEmpty); + expect(message.object, isNull); + expect(message.showName, isFalse); + + final DiagnosticsNode messageProperty = new MessageProperty('diagnostics', 'hello world'); + expect(messageProperty.toString(), equals('diagnostics: hello world')); + expect(messageProperty.name, equals('diagnostics')); + expect(messageProperty.object, isNull); + expect(messageProperty.showName, isTrue); + + }); } diff --git a/packages/flutter/test/painting/flutter_logo_test.dart b/packages/flutter/test/painting/flutter_logo_test.dart index 5e7b68e3af..3415b5114d 100644 --- a/packages/flutter/test/painting/flutter_logo_test.dart +++ b/packages/flutter/test/painting/flutter_logo_test.dart @@ -68,13 +68,13 @@ void main() { expect( start.toString(), equals( - 'FlutterLogoDecoration(Color(0xff000000)/Color(0xffffffff) on Color(0xffd4f144), FlutterLogoStyle.stacked)' + 'FlutterLogoDecoration(Color(0xff000000)/Color(0xffffffff) on Color(0xffd4f144), style: stacked)' ), ); expect( FlutterLogoDecoration.lerp(null, end, 0.5).toString(), equals( - 'FlutterLogoDecoration(Color(0xffffffff)/Color(0xff000000) on Color(0xff81d4fa), FlutterLogoStyle.stacked, transition -1.0:0.5)', + 'FlutterLogoDecoration(Color(0xffffffff)/Color(0xff000000) on Color(0xff81d4fa), style: stacked, transition -1.0:0.5)', ), ); }); diff --git a/packages/flutter/test/painting/text_style_test.dart b/packages/flutter/test/painting/text_style_test.dart index 9e43ac9cc2..29d5a65b37 100644 --- a/packages/flutter/test/painting/text_style_test.dart +++ b/packages/flutter/test/painting/text_style_test.dart @@ -9,10 +9,14 @@ import 'package:test/test.dart'; void main() { test("TextStyle control test", () { - expect(const TextStyle(inherit: false).toString(), equals( - 'inherit: false')); - expect(const TextStyle(inherit: true).toString(), equals( - 'inherit: true')); + expect( + const TextStyle(inherit: false).toString(), + equals('TextStyle(inherit: false, )'), + ); + expect( + const TextStyle(inherit: true).toString(), + equals('TextStyle()'), + ); final TextStyle s1 = const TextStyle( fontSize: 10.0, @@ -27,12 +31,7 @@ void main() { expect(s1, equals(s1)); expect( s1.toString(), - equals( - 'inherit: true\n' - 'size: 10.0\n' - 'weight: 800\n' - 'height: 123.0x', - ), + equals('TextStyle(inherit: true, size: 10.0, weight: 800, height: 123.0x)'), ); final TextStyle s2 = s1.copyWith(color: const Color(0xFF00FF00), height: 100.0); @@ -50,11 +49,7 @@ void main() { expect( s2.toString(), equals( - 'inherit: true\n' - 'color: Color(0xff00ff00)\n' - 'size: 10.0\n' - 'weight: 800\n' - 'height: 100.0x', + 'TextStyle(inherit: true, color: Color(0xff00ff00), size: 10.0, weight: 800, height: 100.0x)', ), ); diff --git a/packages/flutter/test/rendering/debug_test.dart b/packages/flutter/test/rendering/debug_test.dart index 10b5cf64c7..148a3733d0 100644 --- a/packages/flutter/test/rendering/debug_test.dart +++ b/packages/flutter/test/rendering/debug_test.dart @@ -21,6 +21,45 @@ void main() { ])); }); + test('transform property test', () { + final Matrix4 transform = new Matrix4.diagonal3(new Vector3.all(2.0)); + final TransformProperty simple = new TransformProperty( + 'transform', + transform, + ); + expect(simple.name, equals('transform')); + expect(simple.object, equals(transform)); + expect(simple.hidden, isFalse); + expect( + simple.toString(), + equals( + 'transform:\n' + ' [0] 2.0,0.0,0.0,0.0\n' + ' [1] 0.0,2.0,0.0,0.0\n' + ' [2] 0.0,0.0,2.0,0.0\n' + ' [3] 0.0,0.0,0.0,1.0', + ), + ); + + final TransformProperty nullProperty = new TransformProperty( + 'transform', + null, + ); + expect(nullProperty.name, equals('transform')); + expect(nullProperty.object, isNull); + expect(nullProperty.hidden, isFalse); + expect(nullProperty.toString(), equals('transform: null')); + + final TransformProperty hideNull = new TransformProperty( + 'transform', + null, + defaultValue: null, + ); + expect(hideNull.object, isNull); + expect(hideNull.hidden, isTrue); + expect(hideNull.toString(), equals('transform: null')); + }); + test('debugPaintPadding', () { expect((Canvas canvas) { debugPaintPadding(canvas, new Rect.fromLTRB(10.0, 10.0, 20.0, 20.0), null); diff --git a/packages/flutter/test/rendering/editable_test.dart b/packages/flutter/test/rendering/editable_test.dart index d9096c28d2..9dd3c579f3 100644 --- a/packages/flutter/test/rendering/editable_test.dart +++ b/packages/flutter/test/rendering/editable_test.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:flutter/rendering.dart'; -import 'package:test/test.dart'; +import 'package:flutter_test/flutter_test.dart'; void main() { test('editable intrinsics', () { @@ -18,5 +18,30 @@ void main() { expect(editable.getMaxIntrinsicWidth(double.INFINITY), 50.0); expect(editable.getMinIntrinsicHeight(double.INFINITY), 10.0); expect(editable.getMaxIntrinsicHeight(double.INFINITY), 10.0); + + expect( + editable.toStringDeep(), + equalsIgnoringHashCodes( + 'RenderEditable#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' + ' │ parentData: null\n' + ' │ constraints: null\n' + ' │ size: MISSING\n' + ' │ cursorColor: null\n' + ' │ showCursor: ValueNotifier#00000(false)\n' + ' │ maxLines: 1\n' + ' │ selectionColor: null\n' + ' │ textScaleFactor: 1.0\n' + ' │ selection: null\n' + ' │ offset: _FixedViewportOffset#00000(offset: 0.0)\n' + ' ╘═╦══ text ═══\n' + ' ║ TextSpan:\n' + ' ║ inherit: true\n' + ' ║ family: Ahem\n' + ' ║ size: 10.0\n' + ' ║ height: 1.0x\n' + ' ║ "12345"\n' + ' ╚═══════════\n' + ), + ); }); } \ No newline at end of file diff --git a/packages/flutter/test/rendering/flex_test.dart b/packages/flutter/test/rendering/flex_test.dart index 09b819085a..d1d45b1a5f 100644 --- a/packages/flutter/test/rendering/flex_test.dart +++ b/packages/flutter/test/rendering/flex_test.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:flutter/rendering.dart'; -import 'package:test/test.dart'; +import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; @@ -82,6 +82,21 @@ void main() { final RenderFlex flex = new RenderFlex(); expect(flex.crossAxisAlignment, equals(CrossAxisAlignment.center)); expect(flex.direction, equals(Axis.horizontal)); + expect(flex, hasAGoodToStringDeep); + expect( + flex.toStringDeep(), + equalsIgnoringHashCodes( + 'RenderFlex#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' + ' parentData: null\n' + ' constraints: null\n' + ' size: MISSING\n' + ' direction: horizontal\n' + ' mainAxisAlignment: start\n' + ' mainAxisSize: max\n' + ' crossAxisAlignment: center\n' + ' textBaseline: null\n' + ), + ); }); test('Parent data', () { diff --git a/packages/flutter/test/rendering/paragraph_test.dart b/packages/flutter/test/rendering/paragraph_test.dart index ed01b1e7d2..9394bd8b49 100644 --- a/packages/flutter/test/rendering/paragraph_test.dart +++ b/packages/flutter/test/rendering/paragraph_test.dart @@ -211,8 +211,7 @@ void main() { final RenderParagraph paragraph = new RenderParagraph( const TextSpan(text: _kText), ); - // TODO(jacobr): fix handling of text spans with line breaks. - expect(paragraph, isNot(hasAGoodToStringDeep)); + expect(paragraph, hasAGoodToStringDeep); expect( paragraph.toStringDeep(), equalsIgnoringHashCodes( @@ -223,9 +222,8 @@ void main() { ' ╘═╦══ text ═══\n' ' ║ TextSpan:\n' ' ║ "I polished up that handle so carefullee\n' - 'That now I am the Ruler of the Queen\'s Navee!"\n' + ' ║ That now I am the Ruler of the Queen\'s Navee!"\n' ' ╚═══════════\n' - '\n', ), ); }); diff --git a/packages/flutter/test/rendering/slivers_test.dart b/packages/flutter/test/rendering/slivers_test.dart index cbd2f2bd48..09138e94b6 100644 --- a/packages/flutter/test/rendering/slivers_test.dart +++ b/packages/flutter/test/rendering/slivers_test.dart @@ -13,36 +13,32 @@ void main() { final RenderViewport root = new RenderViewport( offset: new ViewportOffset.zero(), ); - // TODO(jacobr): remove extra trailing line break. - expect(root, isNot(hasAGoodToStringDeep)); + expect(root, hasAGoodToStringDeep); expect( root.toStringDeep(), equalsIgnoringHashCodes( 'RenderViewport#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' - ' │ parentData: null\n' - ' │ constraints: null\n' - ' │ size: MISSING\n' - ' │ AxisDirection.down\n' - ' │ offset: _FixedViewportOffset#da23b(offset: 0.0)\n' - ' │ anchor: 0.0\n' - '\n' + ' parentData: null\n' + ' constraints: null\n' + ' size: MISSING\n' + ' axisDirection: down\n' + ' offset: _FixedViewportOffset#00000(offset: 0.0)\n' + ' anchor: 0.0\n' ), ); layout(root); root.offset = new ViewportOffset.fixed(900.0); - // TODO(jacobr): remove extra trailing line break. - expect(root, isNot(hasAGoodToStringDeep)); + expect(root, hasAGoodToStringDeep); expect( root.toStringDeep(), equalsIgnoringHashCodes( 'RenderViewport#00000 NEEDS-LAYOUT NEEDS-PAINT\n' - ' │ parentData: \n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ AxisDirection.down\n' - ' │ offset: _FixedViewportOffset#00000(offset: 900.0)\n' - ' │ anchor: 0.0\n' - '\n', + ' parentData: \n' + ' constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' size: Size(800.0, 600.0)\n' + ' axisDirection: down\n' + ' offset: _FixedViewportOffset#00000(offset: 900.0)\n' + ' anchor: 0.0\n', ), ); @@ -75,7 +71,7 @@ void main() { ' │ parentData: \n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' - ' │ AxisDirection.down\n' + ' │ axisDirection: down\n' ' │ offset: _FixedViewportOffset#00000(offset: 0.0)\n' ' │ anchor: 0.0\n' ' │\n' @@ -86,7 +82,7 @@ void main() { ' │ │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ │ viewportMainAxisExtent: 600.0)\n' ' │ │ geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 400.0,\n' - ' │ │ maxPaintExtent: 400.0, )\n' + ' │ │ maxPaintExtent: 400.0)\n' ' │ │\n' ' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n' ' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n' @@ -100,7 +96,7 @@ void main() { ' │ │ 0.0, remainingPaintExtent: 200.0, crossAxisExtent: 800.0,\n' ' │ │ viewportMainAxisExtent: 600.0)\n' ' │ │ geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 200.0,\n' - ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true, )\n' + ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n' ' │ │\n' ' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n' ' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n' @@ -114,7 +110,7 @@ void main() { ' │ │ 0.0, remainingPaintExtent: 0.0, crossAxisExtent: 800.0,\n' ' │ │ viewportMainAxisExtent: 600.0)\n' ' │ │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n' - ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true, )\n' + ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n' ' │ │\n' ' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n' ' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n' @@ -128,7 +124,7 @@ void main() { ' │ │ 0.0, remainingPaintExtent: 0.0, crossAxisExtent: 800.0,\n' ' │ │ viewportMainAxisExtent: 600.0)\n' ' │ │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n' - ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true, )\n' + ' │ │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n' ' │ │\n' ' │ └─child: RenderSizedBox#00000 NEEDS-PAINT\n' ' │ parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n' @@ -142,7 +138,7 @@ void main() { ' │ 0.0, remainingPaintExtent: 0.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 400.0, hidden,\n' - ' │ maxPaintExtent: 400.0, hasVisualOverflow: true, )\n' + ' │ maxPaintExtent: 400.0, hasVisualOverflow: true)\n' ' │\n' ' └─child: RenderSizedBox#00000 NEEDS-PAINT\n' ' parentData: paintOffset=Offset(0.0, -0.0) (can use size)\n' @@ -393,8 +389,7 @@ void main() { final RenderShrinkWrappingViewport root = new RenderShrinkWrappingViewport( offset: new ViewportOffset.zero(), ); - // TODO(jacobr): remove extra trailing line break. - expect(root, isNot(hasAGoodToStringDeep)); + expect(root, hasAGoodToStringDeep); layout(root); root.offset = new ViewportOffset.fixed(900.0); pumpFrame(); @@ -657,15 +652,30 @@ void main() { }); test('SliverGeometry toString', () { - // TODO(jacobr): cleanup the spurious trailing commas from the toString for - // SliverGeometry. expect( - const SliverGeometry().toString(), - equals('SliverGeometry(scrollExtent: 0.0, hidden, maxPaintExtent: 0.0, )')); + const SliverGeometry().toString(), + equals('SliverGeometry(scrollExtent: 0.0, hidden, maxPaintExtent: 0.0)'), + ); expect( - const SliverGeometry(scrollExtent: 100.0, paintExtent: 50.0, layoutExtent: 20.0, visible: true).toString(), - equals('SliverGeometry(scrollExtent: 100.0, paintExtent: 50.0, layoutExtent: 20.0, maxPaintExtent: 0.0, )')); - expect(const SliverGeometry(scrollExtent: 100.0, paintExtent: 0.0, layoutExtent: 20.0).toString(), - equals('SliverGeometry(scrollExtent: 100.0, hidden, layoutExtent: 20.0, maxPaintExtent: 0.0, )')); + const SliverGeometry( + scrollExtent: 100.0, + paintExtent: 50.0, + layoutExtent: 20.0, + visible: true, + ).toString(), + equals( + 'SliverGeometry(scrollExtent: 100.0, paintExtent: 50.0, layoutExtent: 20.0, maxPaintExtent: 0.0)', + ), + ); + expect( + const SliverGeometry( + scrollExtent: 100.0, + paintExtent: 0.0, + layoutExtent: 20.0, + ).toString(), + equals( + 'SliverGeometry(scrollExtent: 100.0, hidden, layoutExtent: 20.0, maxPaintExtent: 0.0)', + ), + ); }); } diff --git a/packages/flutter/test/rendering/table_test.dart b/packages/flutter/test/rendering/table_test.dart index 4c253ce288..38d3521aa2 100644 --- a/packages/flutter/test/rendering/table_test.dart +++ b/packages/flutter/test/rendering/table_test.dart @@ -82,8 +82,8 @@ void main() { ' │ size: Size(130.0, 230.0)\n' ' │ default column width: IntrinsicColumnWidth\n' ' │ table size: 5×5\n' - ' │ column offsets: [0.0, 10.0, 30.0, 130.0, 130.0]\n' - ' │ row offsets: [0.0, 30.0, 30.0, 30.0, 30.0, 230.0]\n' + ' │ column offsets: 0.0, 10.0, 30.0, 130.0, 130.0\n' + ' │ row offsets: 0.0, 30.0, 30.0, 30.0, 30.0, 230.0\n' ' │\n' ' ├─child (0, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' │ parentData: offset=Offset(0.0, 0.0); default vertical alignment\n' diff --git a/packages/flutter/test/rendering/wrap_test.dart b/packages/flutter/test/rendering/wrap_test.dart index 14fb745ee8..650b6d32ea 100644 --- a/packages/flutter/test/rendering/wrap_test.dart +++ b/packages/flutter/test/rendering/wrap_test.dart @@ -16,10 +16,10 @@ void main() { ' parentData: null\n' ' constraints: null\n' ' size: MISSING\n' - ' direction: Axis.horizontal\n' - ' alignment: WrapAlignment.start\n' + ' direction: horizontal\n' + ' alignment: start\n' ' spacing: 0.0\n' - ' runAlignment: WrapAlignment.start\n' + ' runAlignment: start\n' ' runSpacing: 0.0\n' ' crossAxisAlignment: 0.0\n' ), diff --git a/packages/flutter/test/widgets/animated_container_test.dart b/packages/flutter/test/widgets/animated_container_test.dart index 15ec093c3a..45d729f6b6 100644 --- a/packages/flutter/test/widgets/animated_container_test.dart +++ b/packages/flutter/test/widgets/animated_container_test.dart @@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; void main() { - testWidgets('AnimatedContainer.debugFillDescription', (WidgetTester tester) async { + testWidgets('AnimatedContainer.debugFillProperties', (WidgetTester tester) async { final AnimatedContainer container = new AnimatedContainer( constraints: const BoxConstraints.tightFor(width: 17.0, height: 23.0), decoration: const BoxDecoration(color: const Color(0xFF00FF00)), diff --git a/packages/flutter/test/widgets/image_test.dart b/packages/flutter/test/widgets/image_test.dart index 3859cec773..0cdb4aa98c 100644 --- a/packages/flutter/test/widgets/image_test.dart +++ b/packages/flutter/test/widgets/image_test.dart @@ -299,7 +299,7 @@ void main() { await tester.pump(); expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(stream: ImageStream(OneFrameImageStreamCompleter; [100×100] @ 1.0x; 1 listener); pixels: [100×100] @ 1.0x)')); await tester.pumpWidget(new Container()); - expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(_StateLifecycle.defunct; not mounted; stream: ImageStream(OneFrameImageStreamCompleter; [100×100] @ 1.0x; 0 listeners); pixels: [100×100] @ 1.0x)')); + expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(lifecycle state: defunct; not mounted; stream: ImageStream(OneFrameImageStreamCompleter; [100×100] @ 1.0x; 0 listeners); pixels: [100×100] @ 1.0x)')); }); testWidgets('Image.memory control test', (WidgetTester tester) async { diff --git a/packages/flutter/test/widgets/keep_alive_test.dart b/packages/flutter/test/widgets/keep_alive_test.dart index fdb215bbd2..4ef696dc74 100644 --- a/packages/flutter/test/widgets/keep_alive_test.dart +++ b/packages/flutter/test/widgets/keep_alive_test.dart @@ -258,7 +258,7 @@ void main() { ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ layer: OffsetLayer#00000\n' ' │ size: Size(800.0, 600.0)\n' - ' │ AxisDirection.down\n' + ' │ axisDirection: down\n' ' │ offset: ScrollPositionWithSingleContext#00000(offset: 0.0, range:\n' ' │ 0.0..39400.0, viewport: 600.0, ScrollableState,\n' ' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics,\n' @@ -279,7 +279,7 @@ void main() { ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, )\n' + ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true)\n' ' │ currently live children: 0 to 1\n' ' │\n' ' ├─child with index 0: RenderLimitedBox#00000\n' @@ -333,7 +333,6 @@ void main() { ' parentData: (can use size)\n' ' constraints: BoxConstraints(w=800.0, h=400.0)\n' ' size: Size(800.0, 400.0)\n' - '' // TODO(ianh): remove blank line )); const GlobalObjectKey<_LeafState>(0).currentState.setKeepAlive(true); await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); @@ -429,7 +428,7 @@ void main() { ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ layer: OffsetLayer#00000\n' ' │ size: Size(800.0, 600.0)\n' - ' │ AxisDirection.down\n' + ' │ axisDirection: down\n' ' │ offset: ScrollPositionWithSingleContext#00000(offset: 2000.0,\n' ' │ range: 0.0..39400.0, viewport: 600.0, ScrollableState,\n' ' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics,\n' @@ -450,7 +449,7 @@ void main() { ' │ 2000.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, )\n' + ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true)\n' ' │ currently live children: 5 to 6\n' ' │\n' ' ├─child with index 5: RenderLimitedBox#00000\n' // <----- this is index 5, not 0 @@ -505,7 +504,7 @@ void main() { ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' ' ╎ size: Size(800.0, 400.0)\n' ' ╎\n' - ' ├─child with index 0 (kept alive offstage): RenderLimitedBox#00000\n' // <----- this one is index 0 and is marked as being offstage + ' ╎╌child with index 0 (kept alive offstage): RenderLimitedBox#00000\n' // <----- this one is index 0 and is marked as being offstage ' ╎ │ creator: LimitedBox ← Placeholder ← KeepAlive ←\n' ' ╎ │ Leaf-[GlobalObjectKey<_LeafState> int#00000] ←\n' ' ╎ │ SliverFixedExtentList ← Viewport ← _ScrollableScope ←\n' @@ -531,7 +530,7 @@ void main() { ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' ' ╎ size: Size(800.0, 400.0)\n' ' ╎\n' // <----- dashed line ends here - ' └─child with index 3 (kept alive offstage): RenderLimitedBox#00000\n' + ' └╌child with index 3 (kept alive offstage): RenderLimitedBox#00000\n' ' │ creator: LimitedBox ← Placeholder ← KeepAlive ←\n' ' │ Leaf-[GlobalObjectKey<_LeafState> int#00000] ←\n' ' │ SliverFixedExtentList ← Viewport ← _ScrollableScope ←\n' diff --git a/packages/flutter/test/widgets/list_view_viewporting_test.dart b/packages/flutter/test/widgets/list_view_viewporting_test.dart index 62a050aef0..b2d48590ab 100644 --- a/packages/flutter/test/widgets/list_view_viewporting_test.dart +++ b/packages/flutter/test/widgets/list_view_viewporting_test.dart @@ -293,7 +293,7 @@ void main() { ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 300.0, paintExtent: 300.0,\n' - ' │ maxPaintExtent: 300.0, )\n' + ' │ maxPaintExtent: 300.0)\n' ' │ currently live children: 0 to 2\n' ' │\n' ' ├─child with index 0: RenderRepaintBoundary#00000 relayoutBoundary=up2\n' diff --git a/packages/flutter/test/widgets/overflow_box_test.dart b/packages/flutter/test/widgets/overflow_box_test.dart index 933fb5c8b0..4309bc3c94 100644 --- a/packages/flutter/test/widgets/overflow_box_test.dart +++ b/packages/flutter/test/widgets/overflow_box_test.dart @@ -30,14 +30,17 @@ void main() { expect(box.size, equals(const Size(100.0, 50.0))); }); - testWidgets('OverflowBox implements debugFillDescription', (WidgetTester tester) async { - final List description = []; + testWidgets('OverflowBox implements debugFillProperties', (WidgetTester tester) async { + final List properties = []; const OverflowBox( minWidth: 1.0, maxWidth: 2.0, minHeight: 3.0, maxHeight: 4.0 - ).debugFillDescription(description); + ).debugFillProperties(properties); + final List description = properties + .where((DiagnosticsNode n) => !n.hidden) + .map((DiagnosticsNode n) => n.toString()).toList(); expect(description, [ 'alignment: FractionalOffset(0.5, 0.5)', 'minWidth: 1.0', diff --git a/packages/flutter/test/widgets/overlay_test.dart b/packages/flutter/test/widgets/overlay_test.dart index e0a8f337e5..aa28b8960b 100644 --- a/packages/flutter/test/widgets/overlay_test.dart +++ b/packages/flutter/test/widgets/overlay_test.dart @@ -27,8 +27,7 @@ void main() { expect(didBuild, isTrue); final RenderObject theater = overlayKey.currentContext.findRenderObject(); - // TODO(jacobr): toStringDeep is missing a trailing \n on the last line. - expect(theater, isNot(hasAGoodToStringDeep)); + expect(theater, hasAGoodToStringDeep); expect( theater.toStringDeep(), equalsIgnoringHashCodes( @@ -45,8 +44,8 @@ void main() { ' ╎ │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ │ size: Size(800.0, 600.0)\n' ' ╎ │ alignment: FractionalOffset(0.0, 0.0)\n' - ' ╎ │ fit: StackFit.expand\n' - ' ╎ │ overflow: Overflow.clip\n' + ' ╎ │ fit: expand\n' + ' ╎ │ overflow: clip\n' ' ╎ │\n' ' ╎ └─child 1: RenderLimitedBox#00000\n' ' ╎ │ creator: LimitedBox ← Container ←\n' @@ -68,7 +67,7 @@ void main() { ' ╎ size: Size(800.0, 600.0)\n' ' ╎ additionalConstraints: BoxConstraints(biggest)\n' ' ╎\n' - ' └╌no offstage children', + ' └╌no offstage children\n', ), ); }); @@ -114,8 +113,8 @@ void main() { ' ╎ │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ │ size: Size(800.0, 600.0)\n' ' ╎ │ alignment: FractionalOffset(0.0, 0.0)\n' - ' ╎ │ fit: StackFit.expand\n' - ' ╎ │ overflow: Overflow.clip\n' + ' ╎ │ fit: expand\n' + ' ╎ │ overflow: clip\n' ' ╎ │\n' ' ╎ └─child 1: RenderLimitedBox#00000\n' ' ╎ │ creator: LimitedBox ← Container ←\n' diff --git a/packages/flutter/test/widgets/sliver_fill_viewport_test.dart b/packages/flutter/test/widgets/sliver_fill_viewport_test.dart index d633bcda0e..79b5d4ecb6 100644 --- a/packages/flutter/test/widgets/sliver_fill_viewport_test.dart +++ b/packages/flutter/test/widgets/sliver_fill_viewport_test.dart @@ -57,8 +57,7 @@ void main() { expect(find.text('3'), findsNothing); final RenderObject viewport = tester.renderObject(find.byType(SliverFillViewport).first); - // TODO(jacobr): toStringDeep has an extra trailing \n. - expect(viewport, isNot(hasAGoodToStringDeep)); + expect(viewport, hasAGoodToStringDeep); expect( viewport.toStringDeep(), equalsIgnoringHashCodes( @@ -76,7 +75,7 @@ void main() { ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 12000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 12000.0, hasVisualOverflow: true, )\n' + ' │ 600.0, maxPaintExtent: 12000.0, hasVisualOverflow: true)\n' ' │ currently live children: 0 to 0\n' ' │\n' ' └─child with index 0: RenderRepaintBoundary#00000\n' @@ -106,10 +105,9 @@ void main() { ' │ size: Size(800.0, 600.0)\n' ' ╘═╦══ text ═══\n' ' ║ TextSpan:\n' - ' ║ inherit: true\n' + ' ║ \n' ' ║ "0"\n' - ' ╚═══════════\n' - '\n', + ' ╚═══════════\n', ), ); }); diff --git a/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart b/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart index 43c4af992d..9ffd406317 100644 --- a/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart +++ b/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart @@ -92,7 +92,7 @@ void main() { ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' ' │ viewportMainAxisExtent: 600.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 200.0, paintExtent: 200.0,\n' - ' │ maxPaintExtent: 200.0, hasVisualOverflow: true, )\n' + ' │ maxPaintExtent: 200.0, hasVisualOverflow: true)\n' ' │ maxExtent: EXCEPTION (FlutterError)\n' ' │ child position: 0.0\n' ' │\n'