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

5
import 'dart:async';
6
import 'dart:collection' show HashMap;
7
import 'dart:convert';
8 9
import 'dart:developer' as developer;
import 'dart:math' as math;
10 11 12 13 14
import 'dart:typed_data';
import 'dart:ui' as ui
    show
        ClipOp,
        Image,
15
        ImageByteFormat,
16 17 18 19 20 21
        Paragraph,
        Picture,
        PictureRecorder,
        PointMode,
        SceneBuilder,
        Vertices;
22 23 24

import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
25
import 'package:flutter/scheduler.dart';
26

27
import 'app.dart';
28 29
import 'basic.dart';
import 'binding.dart';
30
import 'debug.dart';
31 32 33 34 35
import 'framework.dart';
import 'gesture_detector.dart';

/// Signature for the builder callback used by
/// [WidgetInspector.selectButtonBuilder].
36
typedef InspectorSelectButtonBuilder = Widget Function(BuildContext context, VoidCallback onPressed);
37

38 39 40 41 42 43
/// Signature for a  method that registers the service extension `callback` with
/// the given `name`.
///
/// Used as argument to [WidgetInspectorService.initServiceExtensions]. The
/// [BindingBase.registerServiceExtension] implements this signature.
typedef RegisterServiceExtensionCallback = void Function({
44 45
  required String name,
  required ServiceExtensionCallback callback,
46 47
});

48 49 50 51 52 53 54
/// A layer that mimics the behavior of another layer.
///
/// A proxy layer is used for cases where a layer needs to be placed into
/// multiple trees of layers.
class _ProxyLayer extends Layer {
  _ProxyLayer(this._layer);

55 56
  final Layer _layer;

57
  @override
58 59
  void addToScene(ui.SceneBuilder builder) {
    _layer.addToScene(builder);
60 61 62
  }

  @override
63
  @protected
64
  bool findAnnotations<S extends Object>(
65 66
    AnnotationResult<S> result,
    Offset localPosition, {
67
    required bool onlyFirst,
68 69 70
  }) {
    return _layer.findAnnotations(result, localPosition, onlyFirst: onlyFirst);
  }
71 72 73 74 75 76 77
}

/// A [Canvas] that multicasts all method calls to a main canvas and a
/// secondary screenshot canvas so that a screenshot can be recorded at the same
/// time as performing a normal paint.
class _MulticastCanvas implements Canvas {
  _MulticastCanvas({
78 79
    required Canvas main,
    required Canvas screenshot,
80 81 82 83 84
  }) : assert(main != null),
       assert(screenshot != null),
       _main = main,
       _screenshot = screenshot;

85 86 87
  final Canvas _main;
  final Canvas _screenshot;

88
  @override
89
  void clipPath(Path path, { bool doAntiAlias = true }) {
90 91 92 93 94
    _main.clipPath(path, doAntiAlias: doAntiAlias);
    _screenshot.clipPath(path, doAntiAlias: doAntiAlias);
  }

  @override
95
  void clipRRect(RRect rrect, { bool doAntiAlias = true }) {
96 97 98 99 100
    _main.clipRRect(rrect, doAntiAlias: doAntiAlias);
    _screenshot.clipRRect(rrect, doAntiAlias: doAntiAlias);
  }

  @override
101
  void clipRect(Rect rect, { ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true }) {
102 103 104 105 106 107 108 109 110 111 112
    _main.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias);
    _screenshot.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias);
  }

  @override
  void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, Paint paint) {
    _main.drawArc(rect, startAngle, sweepAngle, useCenter, paint);
    _screenshot.drawArc(rect, startAngle, sweepAngle, useCenter, paint);
  }

  @override
113
  void drawAtlas(ui.Image atlas, List<RSTransform> transforms, List<Rect> rects, List<Color>? colors, BlendMode? blendMode, Rect? cullRect, Paint paint) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    _main.drawAtlas(atlas, transforms, rects, colors, blendMode, cullRect, paint);
    _screenshot.drawAtlas(atlas, transforms, rects, colors, blendMode, cullRect, paint);
  }

  @override
  void drawCircle(Offset c, double radius, Paint paint) {
    _main.drawCircle(c, radius, paint);
    _screenshot.drawCircle(c, radius, paint);
  }

  @override
  void drawColor(Color color, BlendMode blendMode) {
    _main.drawColor(color, blendMode);
    _screenshot.drawColor(color, blendMode);
  }

  @override
  void drawDRRect(RRect outer, RRect inner, Paint paint) {
    _main.drawDRRect(outer, inner, paint);
    _screenshot.drawDRRect(outer, inner, paint);
  }

  @override
  void drawImage(ui.Image image, Offset p, Paint paint) {
    _main.drawImage(image, p, paint);
    _screenshot.drawImage(image, p, paint);
  }

  @override
  void drawImageNine(ui.Image image, Rect center, Rect dst, Paint paint) {
    _main.drawImageNine(image, center, dst, paint);
    _screenshot.drawImageNine(image, center, dst, paint);
  }

  @override
  void drawImageRect(ui.Image image, Rect src, Rect dst, Paint paint) {
    _main.drawImageRect(image, src, dst, paint);
    _screenshot.drawImageRect(image, src, dst, paint);
  }

  @override
  void drawLine(Offset p1, Offset p2, Paint paint) {
    _main.drawLine(p1, p2, paint);
    _screenshot.drawLine(p1, p2, paint);
  }

  @override
  void drawOval(Rect rect, Paint paint) {
    _main.drawOval(rect, paint);
    _screenshot.drawOval(rect, paint);
  }

  @override
  void drawPaint(Paint paint) {
    _main.drawPaint(paint);
    _screenshot.drawPaint(paint);
  }

  @override
  void drawParagraph(ui.Paragraph paragraph, Offset offset) {
    _main.drawParagraph(paragraph, offset);
    _screenshot.drawParagraph(paragraph, offset);
  }

  @override
  void drawPath(Path path, Paint paint) {
    _main.drawPath(path, paint);
    _screenshot.drawPath(path, paint);
  }

  @override
  void drawPicture(ui.Picture picture) {
    _main.drawPicture(picture);
    _screenshot.drawPicture(picture);
  }

  @override
  void drawPoints(ui.PointMode pointMode, List<Offset> points, Paint paint) {
    _main.drawPoints(pointMode, points, paint);
    _screenshot.drawPoints(pointMode, points, paint);
  }

  @override
  void drawRRect(RRect rrect, Paint paint) {
    _main.drawRRect(rrect, paint);
    _screenshot.drawRRect(rrect, paint);
  }

  @override
203
  void drawRawAtlas(ui.Image atlas, Float32List rstTransforms, Float32List rects, Int32List? colors, BlendMode? blendMode, Rect? cullRect, Paint paint) {
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    _main.drawRawAtlas(atlas, rstTransforms, rects, colors, blendMode, cullRect, paint);
    _screenshot.drawRawAtlas(atlas, rstTransforms, rects, colors, blendMode, cullRect, paint);
  }

  @override
  void drawRawPoints(ui.PointMode pointMode, Float32List points, Paint paint) {
    _main.drawRawPoints(pointMode, points, paint);
    _screenshot.drawRawPoints(pointMode, points, paint);
  }

  @override
  void drawRect(Rect rect, Paint paint) {
    _main.drawRect(rect, paint);
    _screenshot.drawRect(rect, paint);
  }

  @override
  void drawShadow(Path path, Color color, double elevation, bool transparentOccluder) {
    _main.drawShadow(path, color, elevation, transparentOccluder);
    _screenshot.drawShadow(path, color, elevation, transparentOccluder);
  }

  @override
  void drawVertices(ui.Vertices vertices, BlendMode blendMode, Paint paint) {
    _main.drawVertices(vertices, blendMode, paint);
    _screenshot.drawVertices(vertices, blendMode, paint);
  }

  @override
  int getSaveCount() {
    // The main canvas is used instead of the screenshot canvas as the main
    // canvas is guaranteed to be consistent with the canvas expected by the
    // normal paint pipeline so any logic depending on getSaveCount() will
    // behave the same as for the regular paint pipeline.
    return _main.getSaveCount();
  }

  @override
  void restore() {
    _main.restore();
    _screenshot.restore();
  }

  @override
  void rotate(double radians) {
    _main.rotate(radians);
    _screenshot.rotate(radians);
  }

  @override
  void save() {
    _main.save();
    _screenshot.save();
  }

  @override
260
  void saveLayer(Rect? bounds, Paint paint) {
261 262 263 264 265
    _main.saveLayer(bounds, paint);
    _screenshot.saveLayer(bounds, paint);
  }

  @override
266
  void scale(double sx, [ double? sy ]) {
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    _main.scale(sx, sy);
    _screenshot.scale(sx, sy);
  }

  @override
  void skew(double sx, double sy) {
    _main.skew(sx, sy);
    _screenshot.skew(sx, sy);
  }

  @override
  void transform(Float64List matrix4) {
    _main.transform(matrix4);
    _screenshot.transform(matrix4);
  }

  @override
  void translate(double dx, double dy) {
    _main.translate(dx, dy);
    _screenshot.translate(dx, dy);
  }
288 289 290 291 292

  @override
  dynamic noSuchMethod(Invocation invocation) {
    super.noSuchMethod(invocation);
  }
293 294 295 296 297 298 299 300 301
}

Rect _calculateSubtreeBoundsHelper(RenderObject object, Matrix4 transform) {
  Rect bounds = MatrixUtils.transformRect(transform, object.semanticBounds);

  object.visitChildren((RenderObject child) {
    final Matrix4 childTransform = transform.clone();
    object.applyPaintTransform(child, childTransform);
    Rect childBounds = _calculateSubtreeBoundsHelper(child, childTransform);
302
    final Rect? paintClip = object.describeApproximatePaintClip(child);
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    if (paintClip != null) {
      final Rect transformedPaintClip = MatrixUtils.transformRect(
        transform,
        paintClip,
      );
      childBounds = childBounds.intersect(transformedPaintClip);
    }

    if (childBounds.isFinite && !childBounds.isEmpty) {
      bounds = bounds.isEmpty ? childBounds : bounds.expandToInclude(childBounds);
    }
  });

  return bounds;
}

/// Calculate bounds for a render object and all of its descendants.
Rect _calculateSubtreeBounds(RenderObject object) {
321
  return _calculateSubtreeBoundsHelper(object, Matrix4.identity());
322 323 324 325 326 327
}

/// A layer that omits its own offset when adding children to the scene so that
/// screenshots render to the scene in the local coordinate system of the layer.
class _ScreenshotContainerLayer extends OffsetLayer {
  @override
328 329
  void addToScene(ui.SceneBuilder builder) {
    addChildrenToScene(builder);
330 331 332 333 334 335 336
  }
}

/// Data shared between nested [_ScreenshotPaintingContext] objects recording
/// a screenshot.
class _ScreenshotData {
  _ScreenshotData({
337
    required this.target,
338
  }) : assert(target != null),
339
       containerLayer = _ScreenshotContainerLayer();
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

  /// Target to take a screenshot of.
  final RenderObject target;

  /// Root of the layer tree containing the screenshot.
  final OffsetLayer containerLayer;

  /// Whether the screenshot target has already been found in the render tree.
  bool foundTarget = false;

  /// Whether paint operations should record to the screenshot.
  ///
  /// At least one of [includeInScreenshot] and [includeInRegularContext] must
  /// be true.
  bool includeInScreenshot = false;

  /// Whether paint operations should record to the regular context.
  ///
  /// This should only be set to false before paint operations that should only
  /// apply to the screenshot such rendering debug information about the
  /// [target].
  ///
  /// At least one of [includeInScreenshot] and [includeInRegularContext] must
  /// be true.
  bool includeInRegularContext = true;

  /// Offset of the screenshot corresponding to the offset [target] was given as
  /// part of the regular paint.
  Offset get screenshotOffset {
    assert(foundTarget);
    return containerLayer.offset;
  }
  set screenshotOffset(Offset offset) {
    containerLayer.offset = offset;
  }
}

/// A place to paint to build screenshots of [RenderObject]s.
///
/// Requires that the render objects have already painted successfully as part
/// of the regular rendering pipeline.
/// This painting context behaves the same as standard [PaintingContext] with
/// instrumentation added to compute a screenshot of a specified [RenderObject]
383
/// added. To correctly mimic the behavior of the regular rendering pipeline, the
384 385 386 387 388
/// full subtree of the first [RepaintBoundary] ancestor of the specified
/// [RenderObject] will also be rendered rather than just the subtree of the
/// render object.
class _ScreenshotPaintingContext extends PaintingContext {
  _ScreenshotPaintingContext({
389 390 391
    required ContainerLayer containerLayer,
    required Rect estimatedBounds,
    required _ScreenshotData screenshotData,
392 393 394 395 396 397
  }) : _data = screenshotData,
       super(containerLayer, estimatedBounds);

  final _ScreenshotData _data;

  // Recording state
398 399 400 401
  PictureLayer? _screenshotCurrentLayer;
  ui.PictureRecorder? _screenshotRecorder;
  Canvas? _screenshotCanvas;
  _MulticastCanvas? _multicastCanvas;
402 403 404 405 406 407 408 409

  @override
  Canvas get canvas {
    if (_data.includeInScreenshot) {
      if (_screenshotCanvas == null) {
        _startRecordingScreenshot();
      }
      assert(_screenshotCanvas != null);
410
      return _data.includeInRegularContext ? _multicastCanvas! : _screenshotCanvas!;
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    } else {
      assert(_data.includeInRegularContext);
      return super.canvas;
    }
  }

  bool get _isScreenshotRecording {
    final bool hasScreenshotCanvas = _screenshotCanvas != null;
    assert(() {
      if (hasScreenshotCanvas) {
        assert(_screenshotCurrentLayer != null);
        assert(_screenshotRecorder != null);
        assert(_screenshotCanvas != null);
      } else {
        assert(_screenshotCurrentLayer == null);
        assert(_screenshotRecorder == null);
        assert(_screenshotCanvas == null);
      }
      return true;
    }());
    return hasScreenshotCanvas;
  }

  void _startRecordingScreenshot() {
    assert(_data.includeInScreenshot);
    assert(!_isScreenshotRecording);
437 438
    _screenshotCurrentLayer = PictureLayer(estimatedBounds);
    _screenshotRecorder = ui.PictureRecorder();
439 440
    _screenshotCanvas = Canvas(_screenshotRecorder!);
    _data.containerLayer.append(_screenshotCurrentLayer!);
441
    if (_data.includeInRegularContext) {
442
      _multicastCanvas = _MulticastCanvas(
443
        main: super.canvas,
444
        screenshot: _screenshotCanvas!,
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
      );
    } else {
      _multicastCanvas = null;
    }
  }

  @override
  void stopRecordingIfNeeded() {
    super.stopRecordingIfNeeded();
    _stopRecordingScreenshotIfNeeded();
  }

  void _stopRecordingScreenshotIfNeeded() {
    if (!_isScreenshotRecording)
      return;
    // There is no need to ever draw repaint rainbows as part of the screenshot.
461
    _screenshotCurrentLayer!.picture = _screenshotRecorder!.endRecording();
462 463 464 465 466 467 468 469 470 471 472 473 474 475
    _screenshotCurrentLayer = null;
    _screenshotRecorder = null;
    _multicastCanvas = null;
    _screenshotCanvas = null;
  }

  @override
  void appendLayer(Layer layer) {
    if (_data.includeInRegularContext) {
      super.appendLayer(layer);
      if (_data.includeInScreenshot) {
        assert(!_isScreenshotRecording);
        // We must use a proxy layer here as the layer is already attached to
        // the regular layer tree.
476
        _data.containerLayer.append(_ProxyLayer(layer));
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
      }
    } else {
      // Only record to the screenshot.
      assert(!_isScreenshotRecording);
      assert(_data.includeInScreenshot);
      layer.remove();
      _data.containerLayer.append(layer);
      return;
    }
  }

  @override
  PaintingContext createChildContext(ContainerLayer childLayer, Rect bounds) {
    if (_data.foundTarget) {
      // We have already found the screenshotTarget in the layer tree
      // so we can optimize and use a standard PaintingContext.
      return super.createChildContext(childLayer, bounds);
    } else {
495
      return _ScreenshotPaintingContext(
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        containerLayer: childLayer,
        estimatedBounds: bounds,
        screenshotData: _data,
      );
    }
  }

  @override
  void paintChild(RenderObject child, Offset offset) {
    final bool isScreenshotTarget = identical(child, _data.target);
    if (isScreenshotTarget) {
      assert(!_data.includeInScreenshot);
      assert(!_data.foundTarget);
      _data.foundTarget = true;
      _data.screenshotOffset = offset;
      _data.includeInScreenshot = true;
    }
    super.paintChild(child, offset);
    if (isScreenshotTarget) {
      _stopRecordingScreenshotIfNeeded();
      _data.includeInScreenshot = false;
    }
  }

  /// Captures an image of the current state of [renderObject] and its children.
  ///
  /// The returned [ui.Image] has uncompressed raw RGBA bytes, will be offset
  /// by the top-left corner of [renderBounds], and have dimensions equal to the
  /// size of [renderBounds] multiplied by [pixelRatio].
  ///
  /// To use [toImage], the render object must have gone through the paint phase
  /// (i.e. [debugNeedsPaint] must be false).
  ///
  /// The [pixelRatio] describes the scale between the logical pixels and the
  /// size of the output image. It is independent of the
  /// [window.devicePixelRatio] for the device, so specifying 1.0 (the default)
  /// will give you a 1:1 mapping between logical pixels and the output pixels
533
  /// in the image.
534 535 536
  ///
  /// The [debugPaint] argument specifies whether the image should include the
  /// output of [RenderObject.debugPaint] for [renderObject] with
537
  /// [debugPaintSizeEnabled] set to true. Debug paint information is not
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  /// included for the children of [renderObject] so that it is clear precisely
  /// which object the debug paint information references.
  ///
  /// See also:
  ///
  ///  * [RenderRepaintBoundary.toImage] for a similar API for [RenderObject]s
  ///    that are repaint boundaries that can be used outside of the inspector.
  ///  * [OffsetLayer.toImage] for a similar API at the layer level.
  ///  * [dart:ui.Scene.toImage] for more information about the image returned.
  static Future<ui.Image> toImage(
    RenderObject renderObject,
    Rect renderBounds, {
    double pixelRatio = 1.0,
    bool debugPaint = false,
  }) {
    RenderObject repaintBoundary = renderObject;
    while (repaintBoundary != null && !repaintBoundary.isRepaintBoundary) {
555
      repaintBoundary = repaintBoundary.parent! as RenderObject;
556 557
    }
    assert(repaintBoundary != null);
558 559
    final _ScreenshotData data = _ScreenshotData(target: renderObject);
    final _ScreenshotPaintingContext context = _ScreenshotPaintingContext(
560
      containerLayer: repaintBoundary.debugLayer!,
561 562 563 564 565 566 567 568
      estimatedBounds: repaintBoundary.paintBounds,
      screenshotData: data,
    );

    if (identical(renderObject, repaintBoundary)) {
      // Painting the existing repaint boundary to the screenshot is sufficient.
      // We don't just take a direct screenshot of the repaint boundary as we
      // want to capture debugPaint information as well.
569
      data.containerLayer.append(_ProxyLayer(repaintBoundary.debugLayer!));
570
      data.foundTarget = true;
571
      final OffsetLayer offsetLayer = repaintBoundary.debugLayer! as OffsetLayer;
572
      data.screenshotOffset = offsetLayer.offset;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    } else {
      // Repaint everything under the repaint boundary.
      // We call debugInstrumentRepaintCompositedChild instead of paintChild as
      // we need to force everything under the repaint boundary to repaint.
      PaintingContext.debugInstrumentRepaintCompositedChild(
        repaintBoundary,
        customContext: context,
      );
    }

    // The check that debugPaintSizeEnabled is false exists to ensure we only
    // call debugPaint when it wasn't already called.
    if (debugPaint && !debugPaintSizeEnabled) {
      data.includeInRegularContext = false;
      // Existing recording may be to a canvas that draws to both the normal and
      // screenshot canvases.
      context.stopRecordingIfNeeded();
      assert(data.foundTarget);
      data.includeInScreenshot = true;

      debugPaintSizeEnabled = true;
      try {
        renderObject.debugPaint(context, data.screenshotOffset);
      } finally {
        debugPaintSizeEnabled = false;
        context.stopRecordingIfNeeded();
      }
    }

    // We must build the regular scene before we can build the screenshot
    // scene as building the screenshot scene assumes addToScene has already
    // been called successfully for all layers in the regular scene.
605
    repaintBoundary.debugLayer!.buildScene(ui.SceneBuilder());
606 607 608 609 610

    return data.containerLayer.toImage(renderBounds, pixelRatio: pixelRatio);
  }
}

611 612 613 614 615 616 617 618 619 620
/// A class describing a step along a path through a tree of [DiagnosticsNode]
/// objects.
///
/// This class is used to bundle all data required to display the tree with just
/// the nodes along a path expanded into a single JSON payload.
class _DiagnosticsPathNode {
  /// Creates a full description of a step in a path through a tree of
  /// [DiagnosticsNode] objects.
  ///
  /// The [node] and [child] arguments must not be null.
621
  _DiagnosticsPathNode({
622 623
    required this.node,
    required this.children,
624 625 626
    this.childIndex,
  }) : assert(node != null),
       assert(children != null);
627 628 629 630 631 632 633 634 635 636 637 638 639 640

  /// Node at the point in the path this [_DiagnosticsPathNode] is describing.
  final DiagnosticsNode node;

  /// Children of the [node] being described.
  ///
  /// This value is cached instead of relying on `node.getChildren()` as that
  /// method call might create new [DiagnosticsNode] objects for each child
  /// and we would prefer to use the identical [DiagnosticsNode] for each time
  /// a node exists in the path.
  final List<DiagnosticsNode> children;

  /// Index of the child that the path continues on.
  ///
641
  /// Equal to null if the path does not continue.
642
  final int? childIndex;
643 644
}

645
List<_DiagnosticsPathNode>? _followDiagnosticableChain(
646
  List<Diagnosticable> chain, {
647 648
  String? name,
  DiagnosticsTreeStyle? style,
649 650 651 652 653 654
}) {
  final List<_DiagnosticsPathNode> path = <_DiagnosticsPathNode>[];
  if (chain.isEmpty)
    return path;
  DiagnosticsNode diagnostic = chain.first.toDiagnosticsNode(name: name, style: style);
  for (int i = 1; i < chain.length; i += 1) {
655
    final Diagnosticable target = chain[i];
656 657 658 659 660 661
    bool foundMatch = false;
    final List<DiagnosticsNode> children = diagnostic.getChildren();
    for (int j = 0; j < children.length; j += 1) {
      final DiagnosticsNode child = children[j];
      if (child.value == target) {
        foundMatch = true;
662
        path.add(_DiagnosticsPathNode(
663 664 665 666 667 668 669 670 671 672
          node: diagnostic,
          children: children,
          childIndex: j,
        ));
        diagnostic = child;
        break;
      }
    }
    assert(foundMatch);
  }
673
  path.add(_DiagnosticsPathNode(node: diagnostic, children: diagnostic.getChildren()));
674 675 676 677 678
  return path;
}

/// Signature for the selection change callback used by
/// [WidgetInspectorService.selectionChangedCallback].
679
typedef InspectorSelectionChangedCallback = void Function();
680 681 682 683 684 685 686 687 688 689

/// Structure to help reference count Dart objects referenced by a GUI tool
/// using [WidgetInspectorService].
class _InspectorReferenceData {
  _InspectorReferenceData(this.object);

  final Object object;
  int count = 1;
}

690 691
// Production implementation of [WidgetInspectorService].
class _WidgetInspectorService = Object with WidgetInspectorService;
692

693 694 695 696
/// Service used by GUI tools to interact with the [WidgetInspector].
///
/// Calls to this object are typically made from GUI tools such as the [Flutter
/// IntelliJ Plugin](https://github.com/flutter/flutter-intellij/blob/master/README.md)
697
/// using the [Dart VM Service](https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md).
698
/// This class uses its own object id and manages object lifecycles itself
699
/// instead of depending on the [object ids](https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#getobject)
700 701 702 703 704 705 706 707 708 709 710 711 712
/// specified by the VM Service Protocol because the VM Service Protocol ids
/// expire unpredictably. Object references are tracked in groups so that tools
/// that clients can use dereference all objects in a group with a single
/// operation making it easier to avoid memory leaks.
///
/// All methods in this class are appropriate to invoke from debugging tools
/// using the Observatory service protocol to evaluate Dart expressions of the
/// form `WidgetInspectorService.instance.methodName(arg1, arg2, ...)`. If you
/// make changes to any instance method of this class you need to verify that
/// the [Flutter IntelliJ Plugin](https://github.com/flutter/flutter-intellij/blob/master/README.md)
/// widget inspector support still works with the changes.
///
/// All methods returning String values return JSON.
713
mixin WidgetInspectorService {
714
  /// Ring of cached JSON values to prevent JSON from being garbage
715
  /// collected before it can be requested over the Observatory protocol.
716
  final List<String?> _serializeRing = List<String?>.filled(20, null);
717 718
  int _serializeRingIndex = 0;

719 720
  /// The current [WidgetInspectorService].
  static WidgetInspectorService get instance => _instance;
721
  static WidgetInspectorService _instance = _WidgetInspectorService();
722 723 724 725 726 727
  @protected
  static set instance(WidgetInspectorService instance) {
    _instance = instance;
  }

  static bool _debugServiceExtensionsRegistered = false;
728 729 730 731

  /// Ground truth tracking what object(s) are currently selected used by both
  /// GUI tools such as the Flutter IntelliJ Plugin and the [WidgetInspector]
  /// displayed on the device.
732
  final InspectorSelection selection = InspectorSelection();
733 734 735 736 737 738 739

  /// Callback typically registered by the [WidgetInspector] to receive
  /// notifications when [selection] changes.
  ///
  /// The Flutter IntelliJ Plugin does not need to listen for this event as it
  /// instead listens for `dart:developer` `inspect` events which also trigger
  /// when the inspection target changes on device.
740
  InspectorSelectionChangedCallback? selectionChangedCallback;
741 742 743 744 745 746

  /// The Observatory protocol does not keep alive object references so this
  /// class needs to manually manage groups of objects that should be kept
  /// alive.
  final Map<String, Set<_InspectorReferenceData>> _groups = <String, Set<_InspectorReferenceData>>{};
  final Map<String, _InspectorReferenceData> _idToReferenceData = <String, _InspectorReferenceData>{};
747
  final Map<Object, String> _objectToId = Map<Object, String>.identity();
748 749
  int _nextId = 0;

750
  List<String>? _pubRootDirectories;
751 752
  /// Memoization for [_isLocalCreationLocation].
  final HashMap<String, bool> _isLocalCreationCache = HashMap<String, bool>();
753

754 755 756
  bool _trackRebuildDirtyWidgets = false;
  bool _trackRepaintWidgets = false;

757
  late RegisterServiceExtensionCallback _registerServiceExtensionCallback;
758 759 760 761 762 763 764 765 766 767
  /// Registers a service extension method with the given name (full
  /// name "ext.flutter.inspector.name").
  ///
  /// The given callback is called when the extension method is called. The
  /// callback must return a value that can be converted to JSON using
  /// `json.encode()` (see [JsonEncoder]). The return value is stored as a
  /// property named `result` in the JSON. In case of failure, the failure is
  /// reported to the remote caller and is dumped to the logs.
  @protected
  void registerServiceExtension({
768 769
    required String name,
    required ServiceExtensionCallback callback,
770 771 772 773 774 775 776 777 778 779
  }) {
    _registerServiceExtensionCallback(
      name: 'inspector.$name',
      callback: callback,
    );
  }

  /// Registers a service extension method with the given name (full
  /// name "ext.flutter.inspector.name"), which takes no arguments.
  void _registerSignalServiceExtension({
780
    required String name,
781
    required FutureOr<Object?> Function() callback,
782 783 784 785
  }) {
    registerServiceExtension(
      name: name,
      callback: (Map<String, String> parameters) async {
786
        return <String, Object?>{'result': await callback()};
787 788 789 790 791
      },
    );
  }

  /// Registers a service extension method with the given name (full
792
  /// name "ext.flutter.inspector.name"), which takes a single optional argument
793 794
  /// "objectGroup" specifying what group is used to manage lifetimes of
  /// object references in the returned JSON (see [disposeGroup]).
795 796
  /// If "objectGroup" is omitted, the returned JSON will not include any object
  /// references to avoid leaking memory.
797
  void _registerObjectGroupServiceExtension({
798
    required String name,
799
    required FutureOr<Object?> Function(String objectGroup) callback,
800 801 802 803
  }) {
    registerServiceExtension(
      name: name,
      callback: (Map<String, String> parameters) async {
804
        return <String, Object?>{'result': await callback(parameters['objectGroup']!)};
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
      },
    );
  }

  /// Registers a service extension method with the given name (full
  /// name "ext.flutter.inspector.name"), which takes a single argument
  /// "enabled" which can have the value "true" or the value "false"
  /// or can be omitted to read the current value. (Any value other
  /// than "true" is considered equivalent to "false". Other arguments
  /// are ignored.)
  ///
  /// Calls the `getter` callback to obtain the value when
  /// responding to the service extension method being called.
  ///
  /// Calls the `setter` callback with the new value when the
  /// service extension method is called with a new value.
  void _registerBoolServiceExtension({
822 823 824
    required String name,
    required AsyncValueGetter<bool> getter,
    required AsyncValueSetter<bool> setter,
825 826 827 828 829 830 831
  }) {
    assert(name != null);
    assert(getter != null);
    assert(setter != null);
    registerServiceExtension(
      name: name,
      callback: (Map<String, String> parameters) async {
832 833 834 835 836
        if (parameters.containsKey('enabled')) {
          final bool value = parameters['enabled'] == 'true';
          await setter(value);
          _postExtensionStateChangedEvent(name, value);
        }
837
        return <String, dynamic>{'enabled': await getter() ? 'true' : 'false'};
838 839 840 841
      },
    );
  }

842 843 844 845 846 847 848 849 850 851
  /// Sends an event when a service extension's state is changed.
  ///
  /// Clients should listen for this event to stay aware of the current service
  /// extension state. Any service extension that manages a state should call
  /// this method on state change.
  ///
  /// `value` reflects the newly updated service extension value.
  ///
  /// This will be called automatically for service extensions registered via
  /// [registerBoolServiceExtension].
852
  void _postExtensionStateChangedEvent(String name, Object? value) {
853 854
    postEvent(
      'Flutter.ServiceExtensionStateChanged',
855
      <String, Object?>{
856 857 858 859 860 861
        'extension': 'ext.flutter.inspector.$name',
        'value': value,
      },
    );
  }

862 863 864 865 866
  /// Registers a service extension method with the given name (full
  /// name "ext.flutter.inspector.name") which takes an optional parameter named
  /// "arg" and a required parameter named "objectGroup" used to control the
  /// lifetimes of object references in the returned JSON (see [disposeGroup]).
  void _registerServiceExtensionWithArg({
867
    required String name,
868
    required FutureOr<Object?> Function(String? objectId, String objectGroup) callback,
869 870 871 872 873
  }) {
    registerServiceExtension(
      name: name,
      callback: (Map<String, String> parameters) async {
        assert(parameters.containsKey('objectGroup'));
874 875
        return <String, Object?>{
          'result': await callback(parameters['arg'], parameters['objectGroup']!),
876 877 878 879 880 881 882 883 884
        };
      },
    );
  }

  /// Registers a service extension method with the given name (full
  /// name "ext.flutter.inspector.name"), that takes arguments
  /// "arg0", "arg1", "arg2", ..., "argn".
  void _registerServiceExtensionVarArgs({
885
    required String name,
886
    required FutureOr<Object?> Function(List<String> args) callback,
887 888 889 890 891
  }) {
    registerServiceExtension(
      name: name,
      callback: (Map<String, String> parameters) async {
        final List<String> args = <String>[];
892 893 894 895 896 897 898
        int index = 0;
        while (true) {
          final String name = 'arg$index';
          if (parameters.containsKey(name)) {
            args.add(parameters[name]!);
          } else {
            break;
899
          }
900 901
          index++;
        }
902 903 904
        // Verify that the only arguments other than perhaps 'isolateId' are
        // arguments we have already handled.
        assert(index == parameters.length || (index == parameters.length - 1 && parameters.containsKey('isolateId')));
905
        return <String, Object?>{'result': await callback(args)};
906 907 908 909
      },
    );
  }

910 911 912 913 914
  /// Cause the entire tree to be rebuilt. This is used by development tools
  /// when the application code has changed and is being hot-reloaded, to cause
  /// the widget tree to pick up any changed implementations.
  ///
  /// This is expensive and should not be called except during development.
915
  @protected
916
  Future<void> forceRebuild() {
917
    final WidgetsBinding binding = WidgetsBinding.instance;
918
    if (binding.renderViewElement != null) {
919
      binding.buildOwner!.reassemble(binding.renderViewElement!, null);
920 921
      return binding.endOfFrame;
    }
922
    return Future<void>.value();
923 924
  }

925 926
  static const String _consoleObjectGroup = 'console-group';

927 928
  int _errorsSinceReload = 0;

929
  void _reportStructuredError(FlutterErrorDetails details) {
930
    final Map<String, Object?> errorJson = _nodeToJson(
931
      details.toDiagnosticsNode(),
932
      InspectorSerializationDelegate(
933 934 935 936
        groupName: _consoleObjectGroup,
        subtreeDepth: 5,
        includeProperties: true,
        maxDescendentsTruncatableNode: 5,
937
        service: this,
938
      ),
939
    )!;
940 941

    errorJson['errorsSinceReload'] = _errorsSinceReload;
942 943 944 945 946 947 948 949
    if (_errorsSinceReload == 0) {
      errorJson['renderedErrorText'] = TextTreeRenderer(
        wrapWidthProperties: FlutterError.wrapWidth,
        maxDescendentsTruncatableNode: 5,
      ).render(details.toDiagnosticsNode(style: DiagnosticsTreeStyle.error)).trimRight();
    } else {
      errorJson['renderedErrorText'] = 'Another exception was thrown: ${details.summary}';
    }
950

951
    _errorsSinceReload += 1;
952 953 954 955 956 957 958 959 960 961
    postEvent('Flutter.Error', errorJson);
  }

  /// Resets the count of errors since the last hot reload.
  ///
  /// This data is sent to clients as part of the 'Flutter.Error' service
  /// protocol event. Clients may choose to display errors received after the
  /// first error differently.
  void _resetErrorCount() {
    _errorsSinceReload = 0;
962 963
  }

964 965 966 967
  /// Whether structured errors are enabled.
  ///
  /// Structured errors provide semantic information that can be used by IDEs
  /// to enhance the display of errors with rich formatting.
968
  bool isStructuredErrorsEnabled() {
969 970 971 972 973
    // This is a debug mode only feature and will default to false for
    // profile mode.
    bool enabled = false;
    assert(() {
      // TODO(kenz): add support for structured errors on the web.
974
      enabled = const bool.fromEnvironment('flutter.inspector.structuredErrors', defaultValue: !kIsWeb); // ignore: avoid_redundant_argument_values
975 976 977
      return true;
    }());
    return enabled;
978 979
  }

980 981 982 983
  /// Called to register service extensions.
  ///
  /// See also:
  ///
984
  ///  * <https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#rpcs-requests-and-responses>
985 986
  ///  * [BindingBase.initServiceExtensions], which explains when service
  ///    extensions can be used.
987
  void initServiceExtensions(RegisterServiceExtensionCallback registerServiceExtensionCallback) {
988 989
    final FlutterExceptionHandler defaultExceptionHandler = FlutterError.presentError;

990
    if (isStructuredErrorsEnabled()) {
991
      FlutterError.presentError = _reportStructuredError;
992
    }
993 994
    _registerServiceExtensionCallback = registerServiceExtensionCallback;
    assert(!_debugServiceExtensionsRegistered);
995 996 997 998
    assert(() {
      _debugServiceExtensionsRegistered = true;
      return true;
    }());
999

1000
    SchedulerBinding.instance.addPersistentFrameCallback(_onFrameStart);
1001

1002 1003
    _registerBoolServiceExtension(
      name: 'structuredErrors',
1004
      getter: () async => FlutterError.presentError == _reportStructuredError,
1005
      setter: (bool value) {
1006
        FlutterError.presentError = value ? _reportStructuredError : defaultExceptionHandler;
1007 1008 1009 1010
        return Future<void>.value();
      },
    );

1011 1012 1013 1014 1015
    _registerBoolServiceExtension(
      name: 'show',
      getter: () async => WidgetsApp.debugShowWidgetInspectorOverride,
      setter: (bool value) {
        if (WidgetsApp.debugShowWidgetInspectorOverride == value) {
1016
          return Future<void>.value();
1017 1018 1019 1020 1021 1022
        }
        WidgetsApp.debugShowWidgetInspectorOverride = value;
        return forceRebuild();
      },
    );

1023 1024 1025 1026 1027 1028 1029 1030
    if (isWidgetCreationTracked()) {
      // Service extensions that are only supported if widget creation locations
      // are tracked.
      _registerBoolServiceExtension(
        name: 'trackRebuildDirtyWidgets',
        getter: () async => _trackRebuildDirtyWidgets,
        setter: (bool value) async {
          if (value == _trackRebuildDirtyWidgets) {
1031
            return;
1032 1033 1034 1035 1036 1037 1038 1039
          }
          _rebuildStats.resetCounts();
          _trackRebuildDirtyWidgets = value;
          if (value) {
            assert(debugOnRebuildDirtyWidget == null);
            debugOnRebuildDirtyWidget = _onRebuildWidget;
            // Trigger a rebuild so there are baseline stats for rebuilds
            // performed by the app.
1040 1041
            await forceRebuild();
            return;
1042 1043
          } else {
            debugOnRebuildDirtyWidget = null;
1044
            return;
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
          }
        },
      );

      _registerBoolServiceExtension(
        name: 'trackRepaintWidgets',
        getter: () async => _trackRepaintWidgets,
        setter: (bool value) async {
          if (value == _trackRepaintWidgets) {
            return;
          }
          _repaintStats.resetCounts();
          _trackRepaintWidgets = value;
          if (value) {
            assert(debugOnProfilePaint == null);
            debugOnProfilePaint = _onPaint;
            // Trigger an immediate paint so the user has some baseline painting
            // stats to view.
            void markTreeNeedsPaint(RenderObject renderObject) {
              renderObject.markNeedsPaint();
              renderObject.visitChildren(markTreeNeedsPaint);
            }
1067
            final RenderObject root = RendererBinding.instance.renderView;
1068
            markTreeNeedsPaint(root);
1069 1070 1071 1072 1073 1074 1075
          } else {
            debugOnProfilePaint = null;
          }
        },
      );
    }

1076 1077
    _registerSignalServiceExtension(
      name: 'disposeAllGroups',
1078 1079 1080 1081
      callback: () async {
        disposeAllGroups();
        return null;
      },
1082 1083 1084
    );
    _registerObjectGroupServiceExtension(
      name: 'disposeGroup',
1085 1086 1087 1088
      callback: (String name) async {
        disposeGroup(name);
        return null;
      },
1089 1090 1091 1092 1093 1094 1095
    );
    _registerSignalServiceExtension(
      name: 'isWidgetTreeReady',
      callback: isWidgetTreeReady,
    );
    _registerServiceExtensionWithArg(
      name: 'disposeId',
1096 1097 1098 1099
      callback: (String? objectId, String objectGroup) async {
        disposeId(objectId, objectGroup);
        return null;
      },
1100 1101 1102
    );
    _registerServiceExtensionVarArgs(
      name: 'setPubRootDirectories',
1103 1104 1105 1106
      callback: (List<String> args) async {
        setPubRootDirectories(args);
        return null;
      },
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    );
    _registerServiceExtensionWithArg(
      name: 'setSelectionById',
      callback: setSelectionById,
    );
    _registerServiceExtensionWithArg(
      name: 'getParentChain',
      callback: _getParentChain,
    );
    _registerServiceExtensionWithArg(
      name: 'getProperties',
      callback: _getProperties,
    );
    _registerServiceExtensionWithArg(
      name: 'getChildren',
      callback: _getChildren,
    );
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

    _registerServiceExtensionWithArg(
      name: 'getChildrenSummaryTree',
      callback: _getChildrenSummaryTree,
    );

    _registerServiceExtensionWithArg(
      name: 'getChildrenDetailsSubtree',
      callback: _getChildrenDetailsSubtree,
    );

1135 1136 1137 1138 1139 1140 1141 1142
    _registerObjectGroupServiceExtension(
      name: 'getRootWidget',
      callback: _getRootWidget,
    );
    _registerObjectGroupServiceExtension(
      name: 'getRootRenderObject',
      callback: _getRootRenderObject,
    );
1143 1144 1145 1146
    _registerObjectGroupServiceExtension(
      name: 'getRootWidgetSummaryTree',
      callback: _getRootWidgetSummaryTree,
    );
1147
    registerServiceExtension(
1148
      name: 'getDetailsSubtree',
1149 1150
      callback: (Map<String, String> parameters) async {
        assert(parameters.containsKey('objectGroup'));
1151 1152
        final String? subtreeDepth = parameters['subtreeDepth'];
        return <String, Object?>{
1153 1154 1155 1156 1157 1158 1159
          'result': _getDetailsSubtree(
            parameters['arg'],
            parameters['objectGroup'],
            subtreeDepth != null ? int.parse(subtreeDepth) : 2,
          ),
        };
      },
1160
    );
1161 1162 1163 1164 1165 1166 1167 1168
    _registerServiceExtensionWithArg(
      name: 'getSelectedRenderObject',
      callback: _getSelectedRenderObject,
    );
    _registerServiceExtensionWithArg(
      name: 'getSelectedWidget',
      callback: _getSelectedWidget,
    );
1169 1170 1171 1172 1173
    _registerServiceExtensionWithArg(
      name: 'getSelectedSummaryWidget',
      callback: _getSelectedSummaryWidget,
    );

1174 1175 1176 1177
    _registerSignalServiceExtension(
      name: 'isWidgetCreationTracked',
      callback: isWidgetCreationTracked,
    );
1178 1179 1180 1181 1182 1183 1184
    registerServiceExtension(
      name: 'screenshot',
      callback: (Map<String, String> parameters) async {
        assert(parameters.containsKey('id'));
        assert(parameters.containsKey('width'));
        assert(parameters.containsKey('height'));

1185
        final ui.Image? image = await screenshot(
1186
          toObject(parameters['id']),
1187 1188
          width: double.parse(parameters['width']!),
          height: double.parse(parameters['height']!),
1189
          margin: parameters.containsKey('margin') ?
1190
              double.parse(parameters['margin']!) : 0.0,
1191
          maxPixelRatio: parameters.containsKey('maxPixelRatio') ?
1192
              double.parse(parameters['maxPixelRatio']!) : 1.0,
1193 1194 1195
          debugPaint: parameters['debugPaint'] == 'true',
        );
        if (image == null) {
1196
          return <String, Object?>{'result': null};
1197
        }
1198
        final ByteData? byteData = await image.toByteData(format:ui.ImageByteFormat.png);
1199

1200
        return <String, Object>{
1201
          'result': base64.encoder.convert(Uint8List.view(byteData!.buffer)),
1202 1203 1204
        };
      },
    );
1205 1206
  }

1207 1208 1209 1210 1211
  void _clearStats() {
    _rebuildStats.resetCounts();
    _repaintStats.resetCounts();
  }

1212 1213 1214 1215
  /// Clear all InspectorService object references.
  ///
  /// Use this method only for testing to ensure that object references from one
  /// test case do not impact other test cases.
1216
  @visibleForTesting
1217
  @protected
1218 1219 1220 1221 1222 1223 1224
  void disposeAllGroups() {
    _groups.clear();
    _idToReferenceData.clear();
    _objectToId.clear();
    _nextId = 0;
  }

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  /// Reset all InspectorService state.
  ///
  /// Use this method only for testing to write hermetic tests for
  /// WidgetInspectorService.
  @visibleForTesting
  @protected
  @mustCallSuper
  void resetAllState() {
    disposeAllGroups();
    selection.clear();
    setPubRootDirectories(<String>[]);
  }

1238 1239 1240 1241
  /// Free all references to objects in a group.
  ///
  /// Objects and their associated ids in the group may be kept alive by
  /// references from a different group.
1242
  @protected
1243
  void disposeGroup(String name) {
1244
    final Set<_InspectorReferenceData>? references = _groups.remove(name);
1245 1246 1247 1248 1249 1250 1251 1252 1253
    if (references == null)
      return;
    references.forEach(_decrementReferenceCount);
  }

  void _decrementReferenceCount(_InspectorReferenceData reference) {
    reference.count -= 1;
    assert(reference.count >= 0);
    if (reference.count == 0) {
1254
      final String? id = _objectToId.remove(reference.object);
1255 1256 1257 1258 1259 1260
      assert(id != null);
      _idToReferenceData.remove(id);
    }
  }

  /// Returns a unique id for [object] that will remain live at least until
1261
  /// [disposeGroup] is called on [groupName].
1262
  @protected
1263
  String? toId(Object? object, String groupName) {
1264 1265 1266
    if (object == null)
      return null;

1267
    final Set<_InspectorReferenceData> group = _groups.putIfAbsent(groupName, () => Set<_InspectorReferenceData>.identity());
1268
    String? id = _objectToId[object];
1269 1270 1271 1272 1273
    _InspectorReferenceData referenceData;
    if (id == null) {
      id = 'inspector-$_nextId';
      _nextId += 1;
      _objectToId[object] = id;
1274
      referenceData = _InspectorReferenceData(object);
1275 1276 1277
      _idToReferenceData[id] = referenceData;
      group.add(referenceData);
    } else {
1278
      referenceData = _idToReferenceData[id]!;
1279 1280 1281 1282 1283 1284
      if (group.add(referenceData))
        referenceData.count += 1;
    }
    return id;
  }

1285 1286
  /// Returns whether the application has rendered its first frame and it is
  /// appropriate to display the Widget tree in the inspector.
1287
  @protected
1288
  bool isWidgetTreeReady([ String? groupName ]) {
1289
    return WidgetsBinding.instance != null &&
1290
           WidgetsBinding.instance.debugDidSendFirstFrameEvent;
1291 1292
  }

1293 1294 1295 1296 1297
  /// Returns the Dart object associated with a reference id.
  ///
  /// The `groupName` parameter is not required by is added to regularize the
  /// API surface of the methods in this class called from the Flutter IntelliJ
  /// Plugin.
1298
  @protected
1299
  Object? toObject(String? id, [ String? groupName ]) {
1300 1301 1302
    if (id == null)
      return null;

1303
    final _InspectorReferenceData? data = _idToReferenceData[id];
1304
    if (data == null) {
1305
      throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Id does not exist.')]);
1306
    }
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    return data.object;
  }

  /// Returns the object to introspect to determine the source location of an
  /// object's class.
  ///
  /// The Dart object for the id is returned for all cases but [Element] objects
  /// where the [Widget] configuring the [Element] is returned instead as the
  /// class of the [Widget] is more relevant than the class of the [Element].
  ///
  /// The `groupName` parameter is not required by is added to regularize the
  /// API surface of methods called from the Flutter IntelliJ Plugin.
1319
  @protected
1320 1321
  Object? toObjectForSourceLocation(String id, [ String? groupName ]) {
    final Object? object = toObject(id);
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    if (object is Element) {
      return object.widget;
    }
    return object;
  }

  /// Remove the object with the specified `id` from the specified object
  /// group.
  ///
  /// If the object exists in other groups it will remain alive and the object
  /// id will remain valid.
1333
  @protected
1334
  void disposeId(String? id, String groupName) {
1335 1336 1337
    if (id == null)
      return;

1338
    final _InspectorReferenceData? referenceData = _idToReferenceData[id];
1339
    if (referenceData == null)
1340
      throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Id does not exist')]);
1341
    if (_groups[groupName]?.remove(referenceData) != true)
1342
      throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Id is not in group')]);
1343 1344 1345
    _decrementReferenceCount(referenceData);
  }

1346 1347 1348 1349 1350
  /// Set the list of directories that should be considered part of the local
  /// project.
  ///
  /// The local project directories are used to distinguish widgets created by
  /// the local project over widgets created from inside the framework.
1351
  @protected
1352 1353 1354 1355
  void setPubRootDirectories(List<String> pubRootDirectories) {
    _pubRootDirectories = pubRootDirectories
      .map<String>((String directory) => Uri.parse(directory).path)
      .toList();
1356
    _isLocalCreationCache.clear();
1357 1358
  }

1359 1360 1361
  /// Set the [WidgetInspector] selection to the object matching the specified
  /// id if the object is valid object to set as the inspector selection.
  ///
1362
  /// Returns true if the selection was changed.
1363 1364 1365
  ///
  /// The `groupName` parameter is not required by is added to regularize the
  /// API surface of methods called from the Flutter IntelliJ Plugin.
1366
  @protected
1367
  bool setSelectionById(String? id, [ String? groupName ]) {
1368 1369 1370 1371 1372 1373
    return setSelection(toObject(id), groupName);
  }

  /// Set the [WidgetInspector] selection to the specified `object` if it is
  /// a valid object to set as the inspector selection.
  ///
1374
  /// Returns true if the selection was changed.
1375 1376 1377
  ///
  /// The `groupName` parameter is not needed but is specified to regularize the
  /// API surface of methods called from the Flutter IntelliJ Plugin.
1378
  @protected
1379
  bool setSelection(Object? object, [ String? groupName ]) {
1380 1381 1382 1383 1384 1385
    if (object is Element || object is RenderObject) {
      if (object is Element) {
        if (object == selection.currentElement) {
          return false;
        }
        selection.currentElement = object;
1386
        developer.inspect(selection.currentElement);
1387 1388 1389 1390
      } else {
        if (object == selection.current) {
          return false;
        }
1391
        selection.current = object! as RenderObject;
1392
        developer.inspect(selection.current);
1393 1394
      }
      if (selectionChangedCallback != null) {
1395
        if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) {
1396
          selectionChangedCallback!();
1397 1398 1399
        } else {
          // It isn't safe to trigger the selection change callback if we are in
          // the middle of rendering the frame.
1400
          SchedulerBinding.instance.scheduleTask(
1401
            selectionChangedCallback!,
1402 1403 1404
            Priority.touch,
          );
        }
1405 1406 1407 1408 1409 1410
      }
      return true;
    }
    return false;
  }

1411
  /// Returns a DevTools uri linking to a specific element on the inspector page.
1412
  String? _devToolsInspectorUriForElement(Element element) {
1413 1414 1415 1416
    if (activeDevToolsServerAddress != null && connectedVmServiceUri != null) {
      final String? inspectorRef = toId(element, _consoleObjectGroup);
      if (inspectorRef != null) {
        return devToolsInspectorUri(inspectorRef);
1417 1418 1419 1420 1421 1422 1423 1424
      }
    }
    return null;
  }

  /// Returns the DevTools inspector uri for the given vm service connection and
  /// inspector reference.
  @visibleForTesting
1425 1426 1427 1428
  String devToolsInspectorUri(String inspectorRef) {
    assert(activeDevToolsServerAddress != null);
    assert(connectedVmServiceUri != null);

1429 1430
    final Uri uri = Uri.parse(activeDevToolsServerAddress!).replace(
      queryParameters: <String, dynamic>{
1431
        'uri': connectedVmServiceUri,
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
        'inspectorRef': inspectorRef,
      },
    );

    // We cannot add the '/#/inspector' path by means of
    // [Uri.replace(path: '/#/inspector')] because the '#' character will be
    // encoded when we try to print the url as a string. DevTools will not
    // load properly if this character is encoded in the url.
    // Related: https://github.com/flutter/devtools/issues/2475.
    final String devToolsInspectorUri = uri.toString();
    final int startQueryParamIndex = devToolsInspectorUri.indexOf('?');
    // The query parameter character '?' should be present because we manually
    // added query parameters above.
    assert(startQueryParamIndex != -1);
    return '${devToolsInspectorUri.substring(0, startQueryParamIndex)}'
        '/#/inspector'
        '${devToolsInspectorUri.substring(startQueryParamIndex)}';
  }

1451 1452 1453 1454 1455
  /// Returns JSON representing the chain of [DiagnosticsNode] instances from
  /// root of thee tree to the [Element] or [RenderObject] matching `id`.
  ///
  /// The JSON contains all information required to display a tree view with
  /// all nodes other than nodes along the path collapsed.
1456
  @protected
1457
  String getParentChain(String id, String groupName) {
1458
    return _safeJsonEncode(_getParentChain(id, groupName));
1459 1460
  }

1461 1462
  List<Object?> _getParentChain(String? id, String groupName) {
    final Object? value = toObject(id);
1463 1464
    List<_DiagnosticsPathNode> path;
    if (value is RenderObject)
1465
      path = _getRenderObjectParentChain(value, groupName)!;
1466 1467 1468
    else if (value is Element)
      path = _getElementParentChain(value, groupName);
    else
1469
      throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Cannot get parent chain for node of type ${value.runtimeType}')]);
1470

1471
    return path.map<Object?>((_DiagnosticsPathNode node) => _pathNodeToJson(
1472
      node,
1473
      InspectorSerializationDelegate(groupName: groupName, service: this),
1474
    )).toList();
1475 1476
  }

1477
  Map<String, Object?>? _pathNodeToJson(_DiagnosticsPathNode? pathNode, InspectorSerializationDelegate delegate) {
1478 1479
    if (pathNode == null)
      return null;
1480
    return <String, Object?>{
1481 1482
      'node': _nodeToJson(pathNode.node, delegate),
      'children': _nodesToJson(pathNode.children, delegate, parent: pathNode.node),
1483 1484 1485 1486
      'childIndex': pathNode.childIndex,
    };
  }

1487 1488
  List<Element> _getRawElementParentChain(Element element, { required int? numLocalParents }) {
    List<Element> elements = element.debugGetDiagnosticChain();
1489 1490 1491
    if (numLocalParents != null) {
      for (int i = 0; i < elements.length; i += 1) {
        if (_isValueCreatedByLocalProject(elements[i])) {
1492
          numLocalParents = numLocalParents! - 1;
1493 1494 1495 1496 1497 1498 1499
          if (numLocalParents <= 0) {
            elements = elements.take(i + 1).toList();
            break;
          }
        }
      }
    }
1500
    return elements.reversed.toList();
1501 1502
  }

1503
  List<_DiagnosticsPathNode> _getElementParentChain(Element element, String groupName, { int? numLocalParents }) {
1504 1505 1506
    return _followDiagnosticableChain(
      _getRawElementParentChain(element, numLocalParents: numLocalParents),
    ) ?? const <_DiagnosticsPathNode>[];
1507 1508
  }

1509
  List<_DiagnosticsPathNode>? _getRenderObjectParentChain(RenderObject? renderObject, String groupName) {
1510
    final List<RenderObject> chain = <RenderObject>[];
1511
    while (renderObject != null) {
1512
      chain.add(renderObject);
1513
      renderObject = renderObject.parent as RenderObject?;
1514 1515 1516 1517
    }
    return _followDiagnosticableChain(chain.reversed.toList());
  }

1518 1519
  Map<String, Object?>? _nodeToJson(
    DiagnosticsNode? node,
1520
    InspectorSerializationDelegate delegate,
1521
  ) {
1522
    return node?.toJsonMap(delegate);
1523 1524
  }

1525 1526
  bool _isValueCreatedByLocalProject(Object? value) {
    final _Location? creationLocation = _getCreationLocation(value);
1527 1528 1529
    if (creationLocation == null) {
      return false;
    }
1530
    return _isLocalCreationLocation(creationLocation.file);
1531 1532
  }

1533 1534
  bool _isLocalCreationLocationImpl(String locationUri) {
    final String file = Uri.parse(locationUri).path;
1535 1536 1537 1538 1539 1540 1541

    // By default check whether the creation location was within package:flutter.
    if (_pubRootDirectories == null) {
      // TODO(chunhtai): Make it more robust once
      // https://github.com/flutter/flutter/issues/32660 is fixed.
      return !file.contains('packages/flutter/');
    }
1542
    for (final String directory in _pubRootDirectories!) {
1543 1544 1545 1546 1547 1548 1549
      if (file.startsWith(directory)) {
        return true;
      }
    }
    return false;
  }

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  /// Memoized version of [_isLocalCreationLocationImpl].
  bool _isLocalCreationLocation(String locationUri) {
    final bool? cachedValue = _isLocalCreationCache[locationUri];
    if (cachedValue != null) {
      return cachedValue;
    }
    final bool result = _isLocalCreationLocationImpl(locationUri);
    _isLocalCreationCache[locationUri] = result;
    return result;
  }

1561 1562 1563 1564 1565
  /// Wrapper around `json.encode` that uses a ring of cached values to prevent
  /// the Dart garbage collector from collecting objects between when
  /// the value is returned over the Observatory protocol and when the
  /// separate observatory protocol command has to be used to retrieve its full
  /// contents.
1566 1567 1568
  //
  // TODO(jacobr): Replace this with a better solution once
  // https://github.com/dart-lang/sdk/issues/32919 is fixed.
1569
  String _safeJsonEncode(Object? object) {
1570 1571 1572 1573
    final String jsonString = json.encode(object);
    _serializeRing[_serializeRingIndex] = jsonString;
    _serializeRingIndex = (_serializeRingIndex + 1)  % _serializeRing.length;
    return jsonString;
1574 1575
  }

1576
  List<DiagnosticsNode> _truncateNodes(Iterable<DiagnosticsNode> nodes, int maxDescendentsTruncatableNode) {
1577
    if (nodes.every((DiagnosticsNode node) => node.value is Element) && isWidgetCreationTracked()) {
1578 1579 1580
      final List<DiagnosticsNode> localNodes = nodes
        .where((DiagnosticsNode node) => _isValueCreatedByLocalProject(node.value))
        .toList();
1581 1582 1583 1584
      if (localNodes.isNotEmpty) {
        return localNodes;
      }
    }
1585
    return nodes.take(maxDescendentsTruncatableNode).toList();
1586 1587
  }

1588
  List<Map<String, Object?>> _nodesToJson(
1589
    List<DiagnosticsNode> nodes,
1590
    InspectorSerializationDelegate delegate, {
1591
    required DiagnosticsNode? parent,
1592
  }) {
1593
    return DiagnosticsNode.toJsonList(nodes, parent, delegate);
1594 1595 1596 1597
  }

  /// Returns a JSON representation of the properties of the [DiagnosticsNode]
  /// object that `diagnosticsNodeId` references.
1598
  @protected
1599
  String getProperties(String diagnosticsNodeId, String groupName) {
1600
    return _safeJsonEncode(_getProperties(diagnosticsNodeId, groupName));
1601 1602
  }

1603 1604
  List<Object> _getProperties(String? diagnosticsNodeId, String groupName) {
    final DiagnosticsNode? node = toObject(diagnosticsNodeId) as DiagnosticsNode?;
1605
    return _nodesToJson(node == null ? const <DiagnosticsNode>[] : node.getProperties(), InspectorSerializationDelegate(groupName: groupName, service: this), parent: node);
1606 1607 1608 1609 1610
  }

  /// Returns a JSON representation of the children of the [DiagnosticsNode]
  /// object that `diagnosticsNodeId` references.
  String getChildren(String diagnosticsNodeId, String groupName) {
1611
    return _safeJsonEncode(_getChildren(diagnosticsNodeId, groupName));
1612 1613
  }

1614 1615
  List<Object> _getChildren(String? diagnosticsNodeId, String groupName) {
    final DiagnosticsNode? node = toObject(diagnosticsNodeId) as DiagnosticsNode?;
1616
    final InspectorSerializationDelegate delegate = InspectorSerializationDelegate(groupName: groupName, service: this);
1617
    return _nodesToJson(node == null ? const <DiagnosticsNode>[] : _getChildrenFiltered(node, delegate), delegate, parent: node);
1618 1619 1620 1621 1622 1623
  }

  /// Returns a JSON representation of the children of the [DiagnosticsNode]
  /// object that `diagnosticsNodeId` references only including children that
  /// were created directly by user code.
  ///
1624
  /// {@template flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
1625
  /// Requires [Widget] creation locations which are only available for debug
1626 1627 1628
  /// mode builds when the `--track-widget-creation` flag is enabled on the call
  /// to the `flutter` tool. This flag is enabled by default in debug builds.
  /// {@endtemplate}
1629 1630 1631 1632 1633 1634 1635 1636 1637
  ///
  /// See also:
  ///
  ///  * [isWidgetCreationTracked] which indicates whether this method can be
  ///    used.
  String getChildrenSummaryTree(String diagnosticsNodeId, String groupName) {
    return _safeJsonEncode(_getChildrenSummaryTree(diagnosticsNodeId, groupName));
  }

1638 1639
  List<Object> _getChildrenSummaryTree(String? diagnosticsNodeId, String groupName) {
    final DiagnosticsNode? node = toObject(diagnosticsNodeId) as DiagnosticsNode?;
1640
    final InspectorSerializationDelegate delegate = InspectorSerializationDelegate(groupName: groupName, summaryTree: true, service: this);
1641
    return _nodesToJson(node == null ? const <DiagnosticsNode>[] : _getChildrenFiltered(node, delegate), delegate, parent: node);
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  }

  /// Returns a JSON representation of the children of the [DiagnosticsNode]
  /// object that `diagnosticsNodeId` references providing information needed
  /// for the details subtree view.
  ///
  /// The details subtree shows properties inline and includes all children
  /// rather than a filtered set of important children.
  String getChildrenDetailsSubtree(String diagnosticsNodeId, String groupName) {
    return _safeJsonEncode(_getChildrenDetailsSubtree(diagnosticsNodeId, groupName));
  }

1654 1655
  List<Object> _getChildrenDetailsSubtree(String? diagnosticsNodeId, String groupName) {
    final DiagnosticsNode? node = toObject(diagnosticsNodeId) as DiagnosticsNode?;
1656
    // With this value of minDepth we only expand one extra level of important nodes.
1657
    final InspectorSerializationDelegate delegate = InspectorSerializationDelegate(groupName: groupName, includeProperties: true, service: this);
1658
    return _nodesToJson(node == null ? const <DiagnosticsNode>[] : _getChildrenFiltered(node, delegate), delegate, parent: node);
1659 1660 1661
  }

  bool _shouldShowInSummaryTree(DiagnosticsNode node) {
1662 1663 1664
    if (node.level == DiagnosticLevel.error) {
      return true;
    }
1665
    final Object? value = node.value;
1666
    if (value is! Diagnosticable) {
1667 1668 1669
      return true;
    }
    if (value is! Element || !isWidgetCreationTracked()) {
Chris Bracken's avatar
Chris Bracken committed
1670
      // Creation locations are not available so include all nodes in the
1671 1672 1673 1674 1675 1676 1677 1678
      // summary tree.
      return true;
    }
    return _isValueCreatedByLocalProject(value);
  }

  List<DiagnosticsNode> _getChildrenFiltered(
    DiagnosticsNode node,
1679
    InspectorSerializationDelegate delegate,
1680
  ) {
1681 1682
    return _filterChildren(node.getChildren(), delegate);
  }
1683

1684 1685
  List<DiagnosticsNode> _filterChildren(
    List<DiagnosticsNode> nodes,
1686
    InspectorSerializationDelegate delegate,
1687
  ) {
1688
    final List<DiagnosticsNode> children = <DiagnosticsNode>[
1689
      for (final DiagnosticsNode child in nodes)
1690 1691 1692 1693 1694
        if (!delegate.summaryTree || _shouldShowInSummaryTree(child))
          child
        else
          ..._getChildrenFiltered(child, delegate),
    ];
1695
    return children;
1696 1697 1698 1699 1700
  }

  /// Returns a JSON representation of the [DiagnosticsNode] for the root
  /// [Element].
  String getRootWidget(String groupName) {
1701
    return _safeJsonEncode(_getRootWidget(groupName));
1702 1703
  }

1704
  Map<String, Object?>? _getRootWidget(String groupName) {
1705
    return _nodeToJson(WidgetsBinding.instance.renderViewElement?.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this));
1706 1707 1708 1709 1710 1711 1712 1713
  }

  /// Returns a JSON representation of the [DiagnosticsNode] for the root
  /// [Element] showing only nodes that should be included in a summary tree.
  String getRootWidgetSummaryTree(String groupName) {
    return _safeJsonEncode(_getRootWidgetSummaryTree(groupName));
  }

1714
  Map<String, Object?>? _getRootWidgetSummaryTree(String groupName) {
1715
    return _nodeToJson(
1716
      WidgetsBinding.instance.renderViewElement?.toDiagnosticsNode(),
1717
      InspectorSerializationDelegate(groupName: groupName, subtreeDepth: 1000000, summaryTree: true, service: this),
1718
    );
1719 1720 1721 1722
  }

  /// Returns a JSON representation of the [DiagnosticsNode] for the root
  /// [RenderObject].
1723
  @protected
1724
  String getRootRenderObject(String groupName) {
1725
    return _safeJsonEncode(_getRootRenderObject(groupName));
1726 1727
  }

1728
  Map<String, Object?>? _getRootRenderObject(String groupName) {
1729
    return _nodeToJson(RendererBinding.instance.renderView.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this));
1730 1731 1732 1733 1734 1735
  }

  /// Returns a JSON representation of the subtree rooted at the
  /// [DiagnosticsNode] object that `diagnosticsNodeId` references providing
  /// information needed for the details subtree view.
  ///
1736 1737 1738 1739
  /// The number of levels of the subtree that should be returned is specified
  /// by the [subtreeDepth] parameter. This value defaults to 2 for backwards
  /// compatibility.
  ///
1740
  /// See also:
1741
  ///
1742 1743
  ///  * [getChildrenDetailsSubtree], a method to get children of a node
  ///    in the details subtree.
1744
  String getDetailsSubtree(
1745 1746 1747 1748
    String id,
    String groupName, {
    int subtreeDepth = 2,
  }) {
1749 1750 1751
    return _safeJsonEncode(_getDetailsSubtree( id, groupName, subtreeDepth));
  }

1752 1753 1754
  Map<String, Object?>? _getDetailsSubtree(
    String? id,
    String? groupName,
1755
    int subtreeDepth,
1756
  ) {
1757
    final DiagnosticsNode? root = toObject(id) as DiagnosticsNode?;
1758 1759 1760 1761 1762
    if (root == null) {
      return null;
    }
    return _nodeToJson(
      root,
1763
      InspectorSerializationDelegate(
1764
        groupName: groupName,
1765
        subtreeDepth: subtreeDepth,
1766
        includeProperties: true,
1767
        service: this,
1768 1769
      ),
    );
1770 1771 1772 1773 1774 1775 1776
  }

  /// Returns a [DiagnosticsNode] representing the currently selected
  /// [RenderObject].
  ///
  /// If the currently selected [RenderObject] is identical to the
  /// [RenderObject] referenced by `previousSelectionId` then the previous
Dan Field's avatar
Dan Field committed
1777
  /// [DiagnosticsNode] is reused.
1778
  @protected
1779
  String getSelectedRenderObject(String previousSelectionId, String groupName) {
1780
    return _safeJsonEncode(_getSelectedRenderObject(previousSelectionId, groupName));
1781 1782
  }

1783 1784 1785
  Map<String, Object?>? _getSelectedRenderObject(String? previousSelectionId, String groupName) {
    final DiagnosticsNode? previousSelection = toObject(previousSelectionId) as DiagnosticsNode?;
    final RenderObject? current = selection.current;
1786
    return _nodeToJson(current == previousSelection?.value ? previousSelection : current?.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this));
1787 1788 1789 1790 1791
  }

  /// Returns a [DiagnosticsNode] representing the currently selected [Element].
  ///
  /// If the currently selected [Element] is identical to the [Element]
Dan Field's avatar
Dan Field committed
1792
  /// referenced by `previousSelectionId` then the previous [DiagnosticsNode] is
1793
  /// reused.
1794
  @protected
1795
  String getSelectedWidget(String? previousSelectionId, String groupName) {
1796
    return _safeJsonEncode(_getSelectedWidget(previousSelectionId, groupName));
1797 1798
  }

1799 1800 1801 1802 1803 1804 1805
  /// Captures an image of the current state of an [object] that is a
  /// [RenderObject] or [Element].
  ///
  /// The returned [ui.Image] has uncompressed raw RGBA bytes and will be scaled
  /// to be at most [width] pixels wide and [height] pixels tall. The returned
  /// image will never have a scale between logical pixels and the
  /// size of the output image larger than maxPixelRatio.
1806
  /// [margin] indicates the number of pixels relative to the un-scaled size of
1807 1808 1809 1810 1811
  /// the [object] to include as a margin to include around the bounds of the
  /// [object] in the screenshot. Including a margin can be useful to capture
  /// areas that are slightly outside of the normal bounds of an object such as
  /// some debug paint information.
  @protected
1812 1813 1814 1815
  Future<ui.Image?> screenshot(
    Object? object, {
    required double width,
    required double height,
1816 1817 1818 1819 1820 1821 1822
    double margin = 0.0,
    double maxPixelRatio = 1.0,
    bool debugPaint = false,
  }) async {
    if (object is! Element && object is! RenderObject) {
      return null;
    }
1823
    final RenderObject? renderObject = object is Element ? object.renderObject : (object as RenderObject?);
1824 1825 1826 1827 1828
    if (renderObject == null || !renderObject.attached) {
      return null;
    }

    if (renderObject.debugNeedsLayout) {
1829
      final PipelineOwner owner = renderObject.owner!;
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
      assert(owner != null);
      assert(!owner.debugDoingLayout);
      owner
        ..flushLayout()
        ..flushCompositingBits()
        ..flushPaint();

      // If we still need layout, then that means that renderObject was skipped
      // in the layout phase and therefore can't be painted. It is clearer to
      // return null indicating that a screenshot is unavailable than to return
      // an empty image.
      if (renderObject.debugNeedsLayout) {
        return null;
      }
    }

    Rect renderBounds = _calculateSubtreeBounds(renderObject);
    if (margin != 0.0) {
      renderBounds = renderBounds.inflate(margin);
    }
    if (renderBounds.isEmpty) {
      return null;
    }

    final double pixelRatio = math.min(
      maxPixelRatio,
      math.min(
        width / renderBounds.width,
        height / renderBounds.height,
      ),
    );

    return _ScreenshotPaintingContext.toImage(
      renderObject,
      renderBounds,
      pixelRatio: pixelRatio,
      debugPaint: debugPaint,
    );
  }

1870 1871 1872
  Map<String, Object?>? _getSelectedWidget(String? previousSelectionId, String groupName) {
    final DiagnosticsNode? previousSelection = toObject(previousSelectionId) as DiagnosticsNode?;
    final Element? current = selection.currentElement;
1873
    return _nodeToJson(current == previousSelection?.value ? previousSelection : current?.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this));
1874 1875 1876 1877 1878 1879 1880 1881
  }

  /// Returns a [DiagnosticsNode] representing the currently selected [Element]
  /// if the selected [Element] should be shown in the summary tree otherwise
  /// returns the first ancestor of the selected [Element] shown in the summary
  /// tree.
  ///
  /// If the currently selected [Element] is identical to the [Element]
Dan Field's avatar
Dan Field committed
1882
  /// referenced by `previousSelectionId` then the previous [DiagnosticsNode] is
1883 1884 1885 1886 1887
  /// reused.
  String getSelectedSummaryWidget(String previousSelectionId, String groupName) {
    return _safeJsonEncode(_getSelectedSummaryWidget(previousSelectionId, groupName));
  }

1888
  Map<String, Object?>? _getSelectedSummaryWidget(String? previousSelectionId, String groupName) {
1889 1890 1891
    if (!isWidgetCreationTracked()) {
      return _getSelectedWidget(previousSelectionId, groupName);
    }
1892 1893
    final DiagnosticsNode? previousSelection = toObject(previousSelectionId) as DiagnosticsNode?;
    Element? current = selection.currentElement;
1894
    if (current != null && !_isValueCreatedByLocalProject(current)) {
1895
      Element? firstLocal;
1896
      for (final Element candidate in current.debugGetDiagnosticChain()) {
1897 1898 1899 1900 1901 1902 1903
        if (_isValueCreatedByLocalProject(candidate)) {
          firstLocal = candidate;
          break;
        }
      }
      current = firstLocal;
    }
1904
    return _nodeToJson(current == previousSelection?.value ? previousSelection : current?.toDiagnosticsNode(), InspectorSerializationDelegate(groupName: groupName, service: this));
1905
  }
1906 1907 1908

  /// Returns whether [Widget] creation locations are available.
  ///
1909
  /// {@macro flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
1910
  bool isWidgetCreationTracked() {
1911
    _widgetCreationTracked ??= _WidgetForTypeTests() is _HasCreationLocation;
1912
    return _widgetCreationTracked!;
1913 1914
  }

1915
  bool? _widgetCreationTracked;
1916

1917
  late Duration _frameStart;
1918 1919 1920

  void _onFrameStart(Duration timeStamp) {
    _frameStart = timeStamp;
1921
    SchedulerBinding.instance.addPostFrameCallback(_onFrameEnd);
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
  }

  void _onFrameEnd(Duration timeStamp) {
    if (_trackRebuildDirtyWidgets) {
      _postStatsEvent('Flutter.RebuiltWidgets', _rebuildStats);
    }
    if (_trackRepaintWidgets) {
      _postStatsEvent('Flutter.RepaintWidgets', _repaintStats);
    }
  }

  void _postStatsEvent(String eventName, _ElementLocationStatsTracker stats) {
    postEvent(eventName, stats.exportToJson(_frameStart));
  }

  /// All events dispatched by a [WidgetInspectorService] use this method
  /// instead of calling [developer.postEvent] directly so that tests for
  /// [WidgetInspectorService] can track which events were dispatched by
  /// overriding this method.
  @protected
1942
  void postEvent(String eventKind, Map<Object, Object?> eventData) {
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    developer.postEvent(eventKind, eventData);
  }

  final _ElementLocationStatsTracker _rebuildStats = _ElementLocationStatsTracker();
  final _ElementLocationStatsTracker _repaintStats = _ElementLocationStatsTracker();

  void _onRebuildWidget(Element element, bool builtOnce) {
    _rebuildStats.add(element);
  }

  void _onPaint(RenderObject renderObject) {
    try {
1955
      final Element? element = (renderObject.debugCreator as DebugCreator?)?.element;
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
      if (element is! RenderObjectElement) {
        // This branch should not hit as long as all RenderObjects were created
        // by Widgets. It is possible there might be some render objects
        // created directly without using the Widget layer so we add this check
        // to improve robustness.
        return;
      }
      _repaintStats.add(element);

      // Give all ancestor elements credit for repainting as long as they do
      // not have their own associated RenderObject.
      element.visitAncestorElements((Element ancestor) {
        if (ancestor is RenderObjectElement) {
          // This ancestor has its own RenderObject so we can precisely track
          // when it repaints.
          return false;
        }
        _repaintStats.add(ancestor);
        return true;
      });
    }
    catch (exception, stack) {
      FlutterError.reportError(
        FlutterErrorDetails(
          exception: exception,
          stack: stack,
1982 1983
          library: 'widget inspector library',
          context: ErrorDescription('while tracking widget repaints'),
1984 1985 1986 1987 1988
        ),
      );
    }
  }

1989
  /// This method is called by [WidgetsBinding.performReassemble] to flush caches
1990 1991 1992 1993 1994 1995
  /// of obsolete values after a hot reload.
  ///
  /// Do not call this method directly. Instead, use
  /// [BindingBase.reassembleApplication].
  void performReassemble() {
    _clearStats();
1996
    _resetErrorCount();
1997 1998 1999 2000 2001 2002 2003 2004 2005
  }
}

/// Accumulator for a count associated with a specific source location.
///
/// The accumulator stores whether the source location is [local] and what its
/// [id] for efficiency encoding terse JSON payloads describing counts.
class _LocationCount {
  _LocationCount({
2006 2007 2008
    required this.location,
    required this.id,
    required this.local,
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
  });

  /// Location id.
  final int id;

  /// Whether the location is local to the current project.
  final bool local;

  final _Location location;

  int get count => _count;
  int _count = 0;

  /// Reset the count.
  void reset() {
    _count = 0;
  }

  /// Increment the count.
  void increment() {
    _count++;
  }
}

/// A stat tracker that aggregates a performance metric for [Element] objects at
/// the granularity of creation locations in source code.
///
/// This class is optimized to minimize the size of the JSON payloads describing
/// the aggregate statistics, for stable memory usage, and low CPU usage at the
/// expense of somewhat higher overall memory usage. Stable memory usage is more
/// important than peak memory usage to avoid the false impression that the
/// user's app is leaking memory each frame.
///
/// The number of unique widget creation locations tends to be at most in the
/// low thousands for regular flutter apps so the peak memory usage for this
/// class is not an issue.
class _ElementLocationStatsTracker {
  // All known creation location tracked.
  //
  // This could also be stored as a `Map<int, _LocationCount>` but this
  // representation is more efficient as all location ids from 0 to n are
  // typically present.
  //
  // All logic in this class assumes that if `_stats[i]` is not null
  // `_stats[i].id` equals `i`.
2054
  final List<_LocationCount?> _stats = <_LocationCount?>[];
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071

  /// Locations with a non-zero count.
  final List<_LocationCount> active = <_LocationCount>[];

  /// Locations that were added since stats were last exported.
  ///
  /// Only locations local to the current project are included as a performance
  /// optimization.
  final List<_LocationCount> newLocations = <_LocationCount>[];

  /// Increments the count associated with the creation location of [element] if
  /// the creation location is local to the current project.
  void add(Element element) {
    final Object widget = element.widget;
    if (widget is! _HasCreationLocation) {
      return;
    }
2072
    final _HasCreationLocation creationLocationSource = widget;
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    final _Location location = creationLocationSource._location;
    final int id = _toLocationId(location);

    _LocationCount entry;
    if (id >= _stats.length || _stats[id] == null) {
      // After the first frame, almost all creation ids will already be in
      // _stats so this slow path will rarely be hit.
      while (id >= _stats.length) {
        _stats.add(null);
      }
      entry = _LocationCount(
        location: location,
        id: id,
2086
        local: WidgetInspectorService.instance._isLocalCreationLocation(location.file),
2087 2088 2089 2090 2091 2092
      );
      if (entry.local) {
        newLocations.add(entry);
      }
      _stats[id] = entry;
    } else {
2093
      entry = _stats[id]!;
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
    }

    // We could in the future add an option to track stats for all widgets but
    // that would significantly increase the size of the events posted using
    // [developer.postEvent] and current use cases for this feature focus on
    // helping users find problems with their widgets not the platform
    // widgets.
    if (entry.local) {
      if (entry.count == 0) {
        active.add(entry);
      }
      entry.increment();
    }
  }

  /// Clear all aggregated statistics.
  void resetCounts() {
    // We chose to only reset the active counts instead of clearing all data
    // to reduce the number memory allocations performed after the first frame.
    // Once an app has warmed up, location stats tracking should not
    // trigger significant additional memory allocations. Avoiding memory
    // allocations is important to minimize the impact this class has on cpu
    // and memory performance of the running app.
2117
    for (final _LocationCount entry in active) {
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
      entry.reset();
    }
    active.clear();
  }

  /// Exports the current counts and then resets the stats to prepare to track
  /// the next frame of data.
  Map<String, dynamic> exportToJson(Duration startTime) {
    final List<int> events = List<int>.filled(active.length * 2, 0);
    int j = 0;
2128
    for (final _LocationCount stat in active) {
2129 2130 2131 2132 2133 2134 2135 2136 2137
      events[j++] = stat.id;
      events[j++] = stat.count;
    }

    final Map<String, dynamic> json = <String, dynamic>{
      'startTime': startTime.inMicroseconds,
      'events': events,
    };

2138
    // Encode the new locations using the older encoding.
2139 2140 2141
    if (newLocations.isNotEmpty) {
      // Add all newly used location ids to the JSON.
      final Map<String, List<int>> locationsJson = <String, List<int>>{};
2142
      for (final _LocationCount entry in newLocations) {
2143
        final _Location location = entry.location;
2144 2145 2146 2147 2148
        final List<int> jsonForFile = locationsJson.putIfAbsent(
          location.file,
          () => <int>[],
        );
        jsonForFile..add(entry.id)..add(location.line)..add(location.column);
2149 2150 2151
      }
      json['newLocations'] = locationsJson;
    }
2152

2153
    // Encode the new locations using the newer encoding (as of v2.4.0).
2154
    if (newLocations.isNotEmpty) {
2155
      final Map<String, Map<String, List<Object?>>> fileLocationsMap = <String, Map<String, List<Object?>>>{};
2156 2157
      for (final _LocationCount entry in newLocations) {
        final _Location location = entry.location;
2158 2159 2160 2161 2162 2163 2164
        final Map<String, List<Object?>> locations = fileLocationsMap.putIfAbsent(
          location.file, () => <String, List<Object?>>{
            'ids': <int>[],
            'lines': <int>[],
            'columns': <int>[],
            'names': <String?>[],
          },
2165
        );
2166 2167 2168 2169 2170

        locations['ids']!.add(entry.id);
        locations['lines']!.add(location.line);
        locations['columns']!.add(location.column);
        locations['names']!.add(location.name);
2171
      }
2172
      json['locations'] = fileLocationsMap;
2173 2174
    }

2175 2176 2177 2178
    resetCounts();
    newLocations.clear();
    return json;
  }
2179 2180 2181 2182
}

class _WidgetForTypeTests extends Widget {
  @override
2183
  Element createElement() => throw UnimplementedError();
2184 2185
}

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
/// A widget that enables inspecting the child widget's structure.
///
/// Select a location on your device or emulator and view what widgets and
/// render object that best matches the location. An outline of the selected
/// widget and terse summary information is shown on device with detailed
/// information is shown in the observatory or in IntelliJ when using the
/// Flutter Plugin.
///
/// The inspector has a select mode and a view mode.
///
/// In the select mode, tapping the device selects the widget that best matches
/// the location of the touch and switches to view mode. Dragging a finger on
/// the device selects the widget under the drag location but does not switch
/// modes. Touching the very edge of the bounding box of a widget triggers
/// selecting the widget even if another widget that also overlaps that
/// location would otherwise have priority.
///
/// In the view mode, the previously selected widget is outlined, however,
/// touching the device has the same effect it would have if the inspector
/// wasn't present. This allows interacting with the application and viewing how
/// the selected widget changes position. Clicking on the select icon in the
/// bottom left corner of the application switches back to select mode.
class WidgetInspector extends StatefulWidget {
  /// Creates a widget that enables inspection for the child.
  ///
  /// The [child] argument must not be null.
  const WidgetInspector({
2213
    super.key,
2214 2215
    required this.child,
    required this.selectButtonBuilder,
2216
  }) : assert(child != null);
2217 2218 2219 2220 2221 2222 2223 2224

  /// The widget that is being inspected.
  final Widget child;

  /// A builder that is called to create the select button.
  ///
  /// The `onPressed` callback passed as an argument to the builder should be
  /// hooked up to the returned widget.
2225
  final InspectorSelectButtonBuilder? selectButtonBuilder;
2226 2227

  @override
2228
  State<WidgetInspector> createState() => _WidgetInspectorState();
2229 2230 2231 2232 2233
}

class _WidgetInspectorState extends State<WidgetInspector>
    with WidgetsBindingObserver {

2234 2235
  _WidgetInspectorState() : selection = WidgetInspectorService.instance.selection;

2236
  Offset? _lastPointerLocation;
2237

2238
  final InspectorSelection selection;
2239 2240 2241 2242 2243 2244 2245 2246

  /// Whether the inspector is in select mode.
  ///
  /// In select mode, pointer interactions trigger widget selection instead of
  /// normal interactions. Otherwise the previously selected widget is
  /// highlighted but the application can be interacted with normally.
  bool isSelectMode = true;

2247
  final GlobalKey _ignorePointerKey = GlobalKey();
2248

Shi-Hao Hong's avatar
Shi-Hao Hong committed
2249
  /// Distance from the edge of the bounding box for an element to consider
2250
  /// as selecting the edge of the bounding box.
2251
  static const double _edgeHitMargin = 2.0;
2252

2253
  InspectorSelectionChangedCallback? _selectionChangedCallback;
2254 2255 2256
  @override
  void initState() {
    super.initState();
2257 2258

    _selectionChangedCallback = () {
2259 2260 2261 2262 2263
      setState(() {
        // The [selection] property which the build method depends on has
        // changed.
      });
    };
2264 2265 2266 2267 2268 2269 2270 2271 2272
    WidgetInspectorService.instance.selectionChangedCallback = _selectionChangedCallback;
  }

  @override
  void dispose() {
    if (WidgetInspectorService.instance.selectionChangedCallback == _selectionChangedCallback) {
      WidgetInspectorService.instance.selectionChangedCallback = null;
    }
    super.dispose();
2273 2274
  }

2275 2276 2277 2278 2279 2280 2281 2282
  bool _hitTestHelper(
    List<RenderObject> hits,
    List<RenderObject> edgeHits,
    Offset position,
    RenderObject object,
    Matrix4 transform,
  ) {
    bool hit = false;
2283
    final Matrix4? inverse = Matrix4.tryInvert(transform);
2284
    if (inverse == null) {
2285 2286 2287 2288
      // We cannot invert the transform. That means the object doesn't appear on
      // screen and cannot be hit.
      return false;
    }
2289 2290 2291 2292 2293
    final Offset localPosition = MatrixUtils.transformPoint(inverse, position);

    final List<DiagnosticsNode> children = object.debugDescribeChildren();
    for (int i = children.length - 1; i >= 0; i -= 1) {
      final DiagnosticsNode diagnostics = children[i];
2294
      assert(diagnostics != null);
2295 2296 2297
      if (diagnostics.style == DiagnosticsTreeStyle.offstage ||
          diagnostics.value is! RenderObject)
        continue;
2298
      final RenderObject child = diagnostics.value! as RenderObject;
2299
      final Rect? paintClip = object.describeApproximatePaintClip(child);
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
      if (paintClip != null && !paintClip.contains(localPosition))
        continue;

      final Matrix4 childTransform = transform.clone();
      object.applyPaintTransform(child, childTransform);
      if (_hitTestHelper(hits, edgeHits, position, child, childTransform))
        hit = true;
    }

    final Rect bounds = object.semanticBounds;
    if (bounds.contains(localPosition)) {
      hit = true;
      // Hits that occur on the edge of the bounding box of an object are
      // given priority to provide a way to select objects that would
      // otherwise be hard to select.
2315
      if (!bounds.deflate(_edgeHitMargin).contains(localPosition))
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
        edgeHits.add(object);
    }
    if (hit)
      hits.add(object);
    return hit;
  }

  /// Returns the list of render objects located at the given position ordered
  /// by priority.
  ///
  /// All render objects that are not offstage that match the location are
  /// included in the list of matches. Priority is given to matches that occur
  /// on the edge of a render object's bounding box and to matches found by
  /// [RenderBox.hitTest].
  List<RenderObject> hitTest(Offset position, RenderObject root) {
    final List<RenderObject> regularHits = <RenderObject>[];
    final List<RenderObject> edgeHits = <RenderObject>[];

    _hitTestHelper(regularHits, edgeHits, position, root, root.getTransformTo(null));
    // Order matches by the size of the hit area.
2336
    double area(RenderObject object) {
2337 2338
      final Size size = object.semanticBounds.size;
      return size.width * size.height;
2339
    }
2340
    regularHits.sort((RenderObject a, RenderObject b) => area(a).compareTo(area(b)));
2341 2342 2343 2344
    final Set<RenderObject> hits = <RenderObject>{
      ...edgeHits,
      ...regularHits,
    };
2345 2346 2347 2348 2349 2350 2351
    return hits.toList();
  }

  void _inspectAt(Offset position) {
    if (!isSelectMode)
      return;

2352
    final RenderIgnorePointer ignorePointer = _ignorePointerKey.currentContext!.findRenderObject()! as RenderIgnorePointer;
2353
    final RenderObject userRender = ignorePointer.child!;
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
    final List<RenderObject> selected = hitTest(position, userRender);

    setState(() {
      selection.candidates = selected;
    });
  }

  void _handlePanDown(DragDownDetails event) {
    _lastPointerLocation = event.globalPosition;
    _inspectAt(event.globalPosition);
  }

  void _handlePanUpdate(DragUpdateDetails event) {
    _lastPointerLocation = event.globalPosition;
    _inspectAt(event.globalPosition);
  }

  void _handlePanEnd(DragEndDetails details) {
    // If the pan ends on the edge of the window assume that it indicates the
    // pointer is being dragged off the edge of the display not a regular touch
    // on the edge of the display. If the pointer is being dragged off the edge
    // of the display we do not want to select anything. A user can still select
    // a widget that is only at the exact screen margin by tapping.
2377
    final Rect bounds = (Offset.zero & (WidgetsBinding.instance.window.physicalSize / WidgetsBinding.instance.window.devicePixelRatio)).deflate(_kOffScreenMargin);
2378
    if (!bounds.contains(_lastPointerLocation!)) {
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
      setState(() {
        selection.clear();
      });
    }
  }

  void _handleTap() {
    if (!isSelectMode)
      return;
    if (_lastPointerLocation != null) {
2389
      _inspectAt(_lastPointerLocation!);
2390

2391 2392
      // Notify debuggers to open an inspector on the object.
      developer.inspect(selection.current);
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
    }
    setState(() {
      // Only exit select mode if there is a button to return to select mode.
      if (widget.selectButtonBuilder != null)
        isSelectMode = false;
    });
  }

  void _handleEnableSelect() {
    setState(() {
      isSelectMode = true;
    });
  }

  @override
  Widget build(BuildContext context) {
2409 2410 2411
    // Be careful changing this build method. The _InspectorOverlayLayer
    // assumes the root RenderObject for the WidgetInspector will be
    // a RenderStack with a _RenderInspectorOverlay as the last child.
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
    return Stack(children: <Widget>[
      GestureDetector(
        onTap: _handleTap,
        onPanDown: _handlePanDown,
        onPanEnd: _handlePanEnd,
        onPanUpdate: _handlePanUpdate,
        behavior: HitTestBehavior.opaque,
        excludeFromSemantics: true,
        child: IgnorePointer(
          ignoring: isSelectMode,
          key: _ignorePointerKey,
          ignoringSemantics: false,
          child: widget.child,
        ),
2426
      ),
2427 2428 2429 2430
      if (!isSelectMode && widget.selectButtonBuilder != null)
        Positioned(
          left: _kInspectButtonMargin,
          bottom: _kInspectButtonMargin,
2431
          child: widget.selectButtonBuilder!(context, _handleEnableSelect),
2432 2433 2434
        ),
      _InspectorOverlay(selection: selection),
    ]);
2435 2436 2437 2438 2439 2440 2441
  }
}

/// Mutable selection state of the inspector.
class InspectorSelection {
  /// Render objects that are candidates to be selected.
  ///
2442
  /// Tools may wish to iterate through the list of candidates.
2443
  List<RenderObject> get candidates => _candidates;
2444
  List<RenderObject> _candidates = <RenderObject>[];
2445 2446
  set candidates(List<RenderObject> value) {
    _candidates = value;
2447 2448
    _index = 0;
    _computeCurrent();
2449 2450 2451
  }

  /// Index within the list of candidates that is currently selected.
2452 2453 2454 2455 2456 2457
  int get index => _index;
  int _index = 0;
  set index(int value) {
    _index = value;
    _computeCurrent();
  }
2458

2459
  /// Set the selection to empty.
2460 2461
  void clear() {
    _candidates = <RenderObject>[];
2462 2463 2464 2465 2466 2467 2468 2469 2470
    _index = 0;
    _computeCurrent();
  }

  /// Selected render object typically from the [candidates] list.
  ///
  /// Setting [candidates] or calling [clear] resets the selection.
  ///
  /// Returns null if the selection is invalid.
2471 2472
  RenderObject? get current => active ? _current : null;

2473 2474
  RenderObject? _current;
  set current(RenderObject? value) {
2475 2476
    if (_current != value) {
      _current = value;
2477
      _currentElement = (value?.debugCreator as DebugCreator?)?.element;
2478
    }
2479 2480
  }

2481
  /// Selected [Element] consistent with the [current] selected [RenderObject].
2482 2483 2484 2485
  ///
  /// Setting [candidates] or calling [clear] resets the selection.
  ///
  /// Returns null if the selection is invalid.
2486 2487 2488 2489
  Element? get currentElement {
    return _currentElement?.debugIsDefunct ?? true ? null : _currentElement;
  }

2490 2491
  Element? _currentElement;
  set currentElement(Element? element) {
2492
    if (element?.debugIsDefunct ?? false) {
2493 2494 2495 2496
      _currentElement = null;
      _current = null;
      return;
    }
2497 2498
    if (currentElement != element) {
      _currentElement = element;
2499
      _current = element!.findRenderObject();
2500 2501 2502 2503 2504 2505
    }
  }

  void _computeCurrent() {
    if (_index < candidates.length) {
      _current = candidates[index];
2506
      _currentElement = (_current?.debugCreator as DebugCreator?)?.element;
2507 2508 2509 2510
    } else {
      _current = null;
      _currentElement = null;
    }
2511 2512
  }

2513 2514
  /// Whether the selected render object is attached to the tree or has gone
  /// out of scope.
2515
  bool get active => _current != null && _current!.attached;
2516 2517 2518 2519
}

class _InspectorOverlay extends LeafRenderObjectWidget {
  const _InspectorOverlay({
2520
    required this.selection,
2521
  });
2522 2523 2524 2525 2526

  final InspectorSelection selection;

  @override
  _RenderInspectorOverlay createRenderObject(BuildContext context) {
2527
    return _RenderInspectorOverlay(selection: selection);
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
  }

  @override
  void updateRenderObject(BuildContext context, _RenderInspectorOverlay renderObject) {
    renderObject.selection = selection;
  }
}

class _RenderInspectorOverlay extends RenderBox {
  /// The arguments must not be null.
2538
  _RenderInspectorOverlay({ required InspectorSelection selection })
2539 2540
    : _selection = selection,
      assert(selection != null);
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557

  InspectorSelection get selection => _selection;
  InspectorSelection _selection;
  set selection(InspectorSelection value) {
    if (value != _selection) {
      _selection = value;
    }
    markNeedsPaint();
  }

  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
2558
  Size computeDryLayout(BoxConstraints constraints) {
2559
    return constraints.constrain(Size.infinite);
2560 2561 2562 2563 2564
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    assert(needsCompositing);
2565 2566
    context.addLayer(_InspectorOverlayLayer(
      overlayRect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height),
2567
      selection: selection,
2568
      rootRenderObject: parent is RenderObject ? parent! as RenderObject : null,
2569 2570 2571 2572
    ));
  }
}

2573
@immutable
2574
class _TransformedRect {
2575
  _TransformedRect(RenderObject object, RenderObject? ancestor)
2576
    : rect = object.semanticBounds,
2577
      transform = object.getTransformTo(ancestor);
2578 2579 2580 2581 2582

  final Rect rect;
  final Matrix4 transform;

  @override
2583
  bool operator ==(Object other) {
2584 2585
    if (other.runtimeType != runtimeType)
      return false;
2586 2587 2588
    return other is _TransformedRect
        && other.rect == rect
        && other.transform == transform;
2589 2590 2591
  }

  @override
2592
  int get hashCode => Object.hash(rect, transform);
2593 2594 2595 2596 2597 2598
}

/// State describing how the inspector overlay should be rendered.
///
/// The equality operator can be used to determine whether the overlay needs to
/// be rendered again.
2599
@immutable
2600
class _InspectorOverlayRenderState {
2601
  const _InspectorOverlayRenderState({
2602 2603 2604 2605 2606
    required this.overlayRect,
    required this.selected,
    required this.candidates,
    required this.tooltip,
    required this.textDirection,
2607 2608 2609 2610 2611 2612
  });

  final Rect overlayRect;
  final _TransformedRect selected;
  final List<_TransformedRect> candidates;
  final String tooltip;
Ian Hickson's avatar
Ian Hickson committed
2613
  final TextDirection textDirection;
2614 2615

  @override
2616
  bool operator ==(Object other) {
2617 2618
    if (other.runtimeType != runtimeType)
      return false;
2619 2620 2621 2622 2623
    return other is _InspectorOverlayRenderState
        && other.overlayRect == overlayRect
        && other.selected == selected
        && listEquals<_TransformedRect>(other.candidates, candidates)
        && other.tooltip == tooltip;
2624 2625 2626
  }

  @override
2627
  int get hashCode => Object.hash(overlayRect, selected, Object.hashAll(candidates), tooltip);
2628 2629
}

2630
const int _kMaxTooltipLines = 5;
2631 2632 2633
const Color _kTooltipBackgroundColor = Color.fromARGB(230, 60, 60, 60);
const Color _kHighlightedRenderObjectFillColor = Color.fromARGB(128, 128, 128, 255);
const Color _kHighlightedRenderObjectBorderColor = Color.fromARGB(128, 64, 64, 128);
2634 2635 2636 2637 2638 2639 2640 2641 2642

/// A layer that outlines the selected [RenderObject] and candidate render
/// objects that also match the last pointer location.
///
/// This approach is horrific for performance and is only used here because this
/// is limited to debug mode. Do not duplicate the logic in production code.
class _InspectorOverlayLayer extends Layer {
  /// Creates a layer that displays the inspector overlay.
  _InspectorOverlayLayer({
2643 2644 2645
    required this.overlayRect,
    required this.selection,
    required this.rootRenderObject,
2646 2647
  }) : assert(overlayRect != null),
       assert(selection != null) {
2648 2649 2650 2651
    bool inDebugMode = false;
    assert(() {
      inDebugMode = true;
      return true;
2652
    }());
2653
    if (inDebugMode == false) {
2654 2655 2656
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary(
          'The inspector should never be used in production mode due to the '
2657
          'negative performance impact.',
2658
        ),
2659
      ]);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
    }
  }

  InspectorSelection selection;

  /// The rectangle in this layer's coordinate system that the overlay should
  /// occupy.
  ///
  /// The scene must be explicitly recomposited after this property is changed
  /// (as described at [Layer]).
  final Rect overlayRect;

2672 2673
  /// Widget inspector root render object. The selection overlay will be painted
  /// with transforms relative to this render object.
2674
  final RenderObject? rootRenderObject;
2675

2676
  _InspectorOverlayRenderState? _lastState;
2677 2678

  /// Picture generated from _lastState.
2679
  late ui.Picture _picture;
2680

2681 2682
  TextPainter? _textPainter;
  double? _textPainterMaxWidth;
2683 2684

  @override
2685
  void addToScene(ui.SceneBuilder builder) {
2686
    if (!selection.active)
2687
      return;
2688

2689
    final RenderObject selected = selection.current!;
2690 2691 2692 2693

    if (!_isInInspectorRenderObjectTree(selected))
      return;

2694
    final List<_TransformedRect> candidates = <_TransformedRect>[];
2695
    for (final RenderObject candidate in selection.candidates) {
2696 2697
      if (candidate == selected || !candidate.attached
          || !_isInInspectorRenderObjectTree(candidate))
2698
        continue;
2699
      candidates.add(_TransformedRect(candidate, rootRenderObject));
2700 2701
    }

2702
    final _InspectorOverlayRenderState state = _InspectorOverlayRenderState(
2703
      overlayRect: overlayRect,
2704
      selected: _TransformedRect(selected, rootRenderObject),
2705
      tooltip: selection.currentElement!.toStringShort(),
Ian Hickson's avatar
Ian Hickson committed
2706
      textDirection: TextDirection.ltr,
2707 2708 2709 2710 2711 2712 2713
      candidates: candidates,
    );

    if (state != _lastState) {
      _lastState = state;
      _picture = _buildPicture(state);
    }
2714
    builder.addPicture(Offset.zero, _picture);
2715 2716 2717
  }

  ui.Picture _buildPicture(_InspectorOverlayRenderState state) {
2718 2719
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder, state.overlayRect);
2720
    final Size size = state.overlayRect.size;
2721 2722 2723
    // The overlay rect could have an offset if the widget inspector does
    // not take all the screen.
    canvas.translate(state.overlayRect.left, state.overlayRect.top);
2724

2725
    final Paint fillPaint = Paint()
2726 2727 2728
      ..style = PaintingStyle.fill
      ..color = _kHighlightedRenderObjectFillColor;

2729
    final Paint borderPaint = Paint()
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0
      ..color = _kHighlightedRenderObjectBorderColor;

    // Highlight the selected renderObject.
    final Rect selectedPaintRect = state.selected.rect.deflate(0.5);
    canvas
      ..save()
      ..transform(state.selected.transform.storage)
      ..drawRect(selectedPaintRect, fillPaint)
      ..drawRect(selectedPaintRect, borderPaint)
      ..restore();

    // Show all other candidate possibly selected elements. This helps selecting
    // render objects by selecting the edge of the bounding box shows all
    // elements the user could toggle the selection between.
2746
    for (final _TransformedRect transformedRect in state.candidates) {
2747 2748 2749 2750 2751 2752 2753 2754
      canvas
        ..save()
        ..transform(transformedRect.transform.storage)
        ..drawRect(transformedRect.rect.deflate(0.5), borderPaint)
        ..restore();
    }

    final Rect targetRect = MatrixUtils.transformRect(
2755 2756
      state.selected.transform, state.selected.rect,
    );
2757
    final Offset target = Offset(targetRect.left, targetRect.center.dy);
2758
    const double offsetFromWidget = 9.0;
2759 2760
    final double verticalOffset = (targetRect.height) / 2 + offsetFromWidget;

Ian Hickson's avatar
Ian Hickson committed
2761
    _paintDescription(canvas, state.tooltip, state.textDirection, target, verticalOffset, size, targetRect);
2762 2763 2764 2765 2766 2767

    // TODO(jacobr): provide an option to perform a debug paint of just the
    // selected widget.
    return recorder.endRecording();
  }

Ian Hickson's avatar
Ian Hickson committed
2768 2769 2770 2771 2772 2773 2774 2775 2776
  void _paintDescription(
    Canvas canvas,
    String message,
    TextDirection textDirection,
    Offset target,
    double verticalOffset,
    Size size,
    Rect targetRect,
  ) {
2777 2778
    canvas.save();
    final double maxWidth = size.width - 2 * (_kScreenEdgeMargin + _kTooltipPadding);
2779 2780
    final TextSpan? textSpan = _textPainter?.text as TextSpan?;
    if (_textPainter == null || textSpan!.text != message || _textPainterMaxWidth != maxWidth) {
2781
      _textPainterMaxWidth = maxWidth;
2782
      _textPainter = TextPainter()
2783 2784
        ..maxLines = _kMaxTooltipLines
        ..ellipsis = '...'
2785
        ..text = TextSpan(style: _messageStyle, text: message)
Ian Hickson's avatar
Ian Hickson committed
2786
        ..textDirection = textDirection
2787 2788 2789
        ..layout(maxWidth: maxWidth);
    }

2790
    final Size tooltipSize = _textPainter!.size + const Offset(_kTooltipPadding * 2, _kTooltipPadding * 2);
2791 2792 2793 2794 2795 2796 2797 2798
    final Offset tipOffset = positionDependentBox(
      size: size,
      childSize: tooltipSize,
      target: target,
      verticalOffset: verticalOffset,
      preferBelow: false,
    );

2799
    final Paint tooltipBackground = Paint()
2800 2801 2802
      ..style = PaintingStyle.fill
      ..color = _kTooltipBackgroundColor;
    canvas.drawRect(
2803
      Rect.fromPoints(
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
        tipOffset,
        tipOffset.translate(tooltipSize.width, tooltipSize.height),
      ),
      tooltipBackground,
    );

    double wedgeY = tipOffset.dy;
    final bool tooltipBelow = tipOffset.dy > target.dy;
    if (!tooltipBelow)
      wedgeY += tooltipSize.height;

2815
    const double wedgeSize = _kTooltipPadding * 2;
2816 2817 2818
    double wedgeX = math.max(tipOffset.dx, target.dx) + wedgeSize * 2;
    wedgeX = math.min(wedgeX, tipOffset.dx + tooltipSize.width - wedgeSize * 2);
    final List<Offset> wedge = <Offset>[
2819 2820 2821
      Offset(wedgeX - wedgeSize, wedgeY),
      Offset(wedgeX + wedgeSize, wedgeY),
      Offset(wedgeX, wedgeY + (tooltipBelow ? -wedgeSize : wedgeSize)),
2822
    ];
2823
    canvas.drawPath(Path()..addPolygon(wedge, true), tooltipBackground);
2824
    _textPainter!.paint(canvas, tipOffset + const Offset(_kTooltipPadding, _kTooltipPadding));
2825 2826
    canvas.restore();
  }
2827 2828

  @override
2829
  @protected
2830
  bool findAnnotations<S extends Object>(
2831 2832
    AnnotationResult<S> result,
    Offset localPosition, {
2833
    bool? onlyFirst,
2834 2835 2836
  }) {
    return false;
  }
2837 2838 2839 2840 2841 2842 2843

  /// Return whether or not a render object belongs to this inspector widget
  /// tree.
  /// The inspector selection is static, so if there are multiple inspector
  /// overlays in the same app (i.e. an storyboard), a selected or candidate
  /// render object may not belong to this tree.
  bool _isInInspectorRenderObjectTree(RenderObject child) {
2844
    RenderObject? current = child.parent as RenderObject?;
2845 2846 2847 2848 2849 2850
    while (current != null) {
      // We found the widget inspector render object.
      if (current is RenderStack
          && current.lastChild is _RenderInspectorOverlay) {
        return rootRenderObject == current;
      }
2851
      current = current.parent as RenderObject?;
2852 2853 2854
    }
    return false;
  }
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
}

const double _kScreenEdgeMargin = 10.0;
const double _kTooltipPadding = 5.0;
const double _kInspectButtonMargin = 10.0;

/// Interpret pointer up events within with this margin as indicating the
/// pointer is moving off the device.
const double _kOffScreenMargin = 1.0;

2865 2866
const TextStyle _messageStyle = TextStyle(
  color: Color(0xFFFFFFFF),
2867 2868 2869
  fontSize: 10.0,
  height: 1.2,
);
2870 2871 2872 2873

/// Interface for classes that track the source code location the their
/// constructor was called from.
///
2874
/// {@macro flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
2875 2876 2877 2878 2879 2880 2881 2882 2883
// ignore: unused_element
abstract class _HasCreationLocation {
  _Location get _location;
}

/// A tuple with file, line, and column number, for displaying human-readable
/// file locations.
class _Location {
  const _Location({
2884 2885 2886
    required this.file,
    required this.line,
    required this.column,
2887
    // ignore: unused_element
2888
    this.name,
2889 2890 2891
  });

  /// File path of the location.
2892
  final String file;
2893 2894 2895

  /// 1-based line number.
  final int line;
2896

2897 2898 2899 2900
  /// 1-based column number.
  final int column;

  /// Optional name of the parameter or function at this location.
2901
  final String? name;
2902

2903 2904
  Map<String, Object?> toJsonMap() {
    final Map<String, Object?> json = <String, Object?>{
2905 2906 2907 2908
      'file': file,
      'line': line,
      'column': column,
    };
2909 2910 2911
    if (name != null) {
      json['name'] = name;
    }
2912 2913 2914 2915 2916 2917 2918
    return json;
  }

  @override
  String toString() {
    final List<String> parts = <String>[];
    if (name != null) {
2919
      parts.add(name!);
2920
    }
2921
    parts.add(file);
2922 2923 2924 2925 2926
    parts..add('$line')..add('$column');
    return parts.join(':');
  }
}

2927 2928 2929 2930 2931 2932
bool _isDebugCreator(DiagnosticsNode node) => node is DiagnosticsDebugCreator;

/// Transformer to parse and gather information about [DiagnosticsDebugCreator].
///
/// This function will be registered to [FlutterErrorDetails.propertiesTransformers]
/// in [WidgetsBinding.initInstances].
2933 2934
///
/// This is meant to be called only in debug mode. In other modes, it yields an empty list.
2935
Iterable<DiagnosticsNode> debugTransformDebugCreator(Iterable<DiagnosticsNode> properties) {
2936
  if (!kDebugMode) {
2937
    return <DiagnosticsNode>[];
2938
  }
2939
  final List<DiagnosticsNode> pending = <DiagnosticsNode>[];
2940 2941 2942 2943 2944 2945 2946
  ErrorSummary? errorSummary;
  for (final DiagnosticsNode node in properties) {
    if (node is ErrorSummary) {
      errorSummary = node;
      break;
    }
  }
2947
  bool foundStackTrace = false;
2948
  final List<DiagnosticsNode> result = <DiagnosticsNode>[];
2949
  for (final DiagnosticsNode node in properties) {
2950 2951 2952
    if (!foundStackTrace && node is DiagnosticsStackTrace)
      foundStackTrace = true;
    if (_isDebugCreator(node)) {
2953
      result.addAll(_parseDiagnosticsNode(node, errorSummary));
2954 2955 2956 2957
    } else {
      if (foundStackTrace) {
        pending.add(node);
      } else {
2958
        result.add(node);
2959 2960 2961
      }
    }
  }
2962 2963
  result.addAll(pending);
  return result;
2964 2965 2966 2967 2968
}

/// Transform the input [DiagnosticsNode].
///
/// Return null if input [DiagnosticsNode] is not applicable.
2969
Iterable<DiagnosticsNode> _parseDiagnosticsNode(
2970 2971
  DiagnosticsNode node,
  ErrorSummary? errorSummary,
2972
) {
2973 2974 2975 2976
  assert(_isDebugCreator(node));
  try {
    final DebugCreator debugCreator = node.value! as DebugCreator;
    final Element element = debugCreator.element;
2977
    return _describeRelevantUserCode(element, errorSummary);
2978 2979 2980 2981 2982 2983
  } catch (error, stack) {
    scheduleMicrotask(() {
      FlutterError.reportError(FlutterErrorDetails(
        exception: error,
        stack: stack,
        library: 'widget inspector',
2984 2985 2986
        informationCollector: () => <DiagnosticsNode>[
          DiagnosticsNode.message('This exception was caught while trying to describe the user-relevant code of another error.'),
        ],
2987 2988
      ));
    });
2989
    return <DiagnosticsNode>[];
2990
  }
2991 2992
}

2993 2994 2995 2996
Iterable<DiagnosticsNode> _describeRelevantUserCode(
  Element element,
  ErrorSummary? errorSummary,
) {
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
  if (!WidgetInspectorService.instance.isWidgetCreationTracked()) {
    return <DiagnosticsNode>[
      ErrorDescription(
        'Widget creation tracking is currently disabled. Enabling '
        'it enables improved error messages. It can be enabled by passing '
        '`--track-widget-creation` to `flutter run` or `flutter test`.',
      ),
      ErrorSpacer(),
    ];
  }
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017

  bool isOverflowError() {
    if (errorSummary != null && errorSummary.value.isNotEmpty) {
      final Object summary = errorSummary.value.first;
      if (summary is String && summary.startsWith('A RenderFlex overflowed by')) {
        return true;
      }
    }
    return false;
  }

3018
  final List<DiagnosticsNode> nodes = <DiagnosticsNode>[];
3019
  bool processElement(Element target) {
3020 3021
    // TODO(chunhtai): should print out all the widgets that are about to cross
    // package boundaries.
3022
    if (debugIsLocalCreationLocation(target)) {
3023
      DiagnosticsNode? devToolsDiagnostic;
3024 3025 3026 3027 3028 3029

      // TODO(kenz): once the inspector is better at dealing with broken trees,
      // we can enable deep links for more errors than just RenderFlex overflow
      // errors. See https://github.com/flutter/flutter/issues/74918.
      if (isOverflowError()) {
        final String? devToolsInspectorUri =
3030
          WidgetInspectorService.instance._devToolsInspectorUriForElement(target);
3031 3032 3033 3034 3035 3036
        if (devToolsInspectorUri != null) {
          devToolsDiagnostic = DevToolsDeepLinkProperty(
            'To inspect this widget in Flutter DevTools, visit: $devToolsInspectorUri',
            devToolsInspectorUri,
          );
        }
3037 3038 3039
      }

      nodes.addAll(<DiagnosticsNode>[
3040
        DiagnosticsBlock(
3041
          name: 'The relevant error-causing widget was',
3042
          children: <DiagnosticsNode>[
3043
            ErrorDescription('${target.widget.toStringShort()} ${_describeCreationLocation(target)}'),
3044
          ],
3045
        ),
3046 3047 3048
        ErrorSpacer(),
        if (devToolsDiagnostic != null) ...<DiagnosticsNode>[devToolsDiagnostic, ErrorSpacer()],
      ]);
3049 3050 3051
      return false;
    }
    return true;
3052 3053 3054
  }
  if (processElement(element))
    element.visitAncestorElements(processElement);
3055 3056 3057
  return nodes;
}

3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
/// Debugging message for DevTools deep links.
///
/// The [value] for this property is a string representation of the Flutter
/// DevTools url.
///
/// Properties `description` and `url` must not be null.
class DevToolsDeepLinkProperty extends DiagnosticsProperty<String> {
  /// Creates a diagnostics property that displays a deep link to Flutter DevTools.
  ///
  /// The [value] of this property will return a map of data for the Flutter
  /// DevTools deep link, including the full `url`, the Flutter DevTools `screenId`,
  /// and the `objectId` in Flutter DevTools that this diagnostic references.
  ///
  /// The `description` and `url` arguments must not be null.
  DevToolsDeepLinkProperty(String description, String url)
    : assert(description != null),
      assert(url != null),
      super('', url, description: description, level: DiagnosticLevel.info);
}

3078 3079
/// Returns if an object is user created.
///
3080 3081
/// This always returns false if it is not called in debug mode.
///
3082
/// {@macro flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
3083 3084 3085
///
/// Currently is local creation locations are only available for
/// [Widget] and [Element].
3086 3087 3088
bool debugIsLocalCreationLocation(Object object) {
  bool isLocal = false;
  assert(() {
3089
    final _Location? location = _getCreationLocation(object);
3090 3091 3092
    if (location != null) {
      isLocal = WidgetInspectorService.instance._isLocalCreationLocation(location.file);
    }
3093 3094 3095
    return true;
  }());
  return isLocal;
3096 3097
}

3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
/// Returns true if a [Widget] is user created.
///
/// This is a faster variant of `debugIsLocalCreationLocation` that is available
/// in debug and profile builds but only works for [Widget].
bool debugIsWidgetLocalCreation(Widget widget) {
  final _Location? location = _getObjectCreationLocation(widget);
  return location != null &&
      WidgetInspectorService.instance._isLocalCreationLocation(location.file);
}

3108 3109 3110 3111
/// Returns the creation location of an object in String format if one is available.
///
/// ex: "file:///path/to/main.dart:4:3"
///
3112
/// {@macro flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
3113 3114
///
/// Currently creation locations are only available for [Widget] and [Element].
3115 3116
String? _describeCreationLocation(Object object) {
  final _Location? location = _getCreationLocation(object);
3117 3118 3119
  return location?.toString();
}

3120 3121 3122 3123
_Location? _getObjectCreationLocation(Object object) {
  return object is _HasCreationLocation ? object._location : null;
}

3124 3125
/// Returns the creation location of an object if one is available.
///
3126
/// {@macro flutter.widgets.WidgetInspectorService.getChildrenSummaryTree}
3127
///
3128
/// Currently creation locations are only available for [Widget] and [Element].
3129
_Location? _getCreationLocation(Object? object) {
3130 3131
  final Object? candidate = object is Element && !object.debugIsDefunct ? object.widget : object;
  return candidate == null ? null : _getObjectCreationLocation(candidate);
3132
}
3133 3134 3135 3136 3137 3138 3139 3140

// _Location objects are always const so we don't need to worry about the GC
// issues that are a concern for other object ids tracked by
// [WidgetInspectorService].
final Map<_Location, int> _locationToId = <_Location, int>{};
final List<_Location> _locations = <_Location>[];

int _toLocationId(_Location location) {
3141
  int? id = _locationToId[location];
3142 3143 3144 3145 3146 3147 3148 3149
  if (id != null) {
    return id;
  }
  id = _locations.length;
  _locations.add(location);
  _locationToId[location] = id;
  return id;
}
3150

3151 3152 3153 3154 3155 3156 3157
/// A delegate that configures how a hierarchy of [DiagnosticsNode]s are
/// serialized by the Flutter Inspector.
@visibleForTesting
class InspectorSerializationDelegate implements DiagnosticsSerializationDelegate {
  /// Creates an [InspectorSerializationDelegate] that serialize [DiagnosticsNode]
  /// for Flutter Inspector service.
  InspectorSerializationDelegate({
3158 3159 3160 3161 3162 3163
    this.groupName,
    this.summaryTree = false,
    this.maxDescendentsTruncatableNode = -1,
    this.expandPropertyValues = true,
    this.subtreeDepth = 1,
    this.includeProperties = false,
3164
    required this.service,
3165
    this.addAdditionalPropertiesCallback,
3166 3167
  });

3168
  /// Service used by GUI tools to interact with the [WidgetInspector].
3169
  final WidgetInspectorService service;
3170 3171 3172 3173 3174 3175

  /// Optional `groupName` parameter which indicates that the json should
  /// contain live object ids.
  ///
  /// Object ids returned as part of the json will remain live at least until
  /// [WidgetInspectorService.disposeGroup()] is called on [groupName].
3176
  final String? groupName;
3177 3178

  /// Whether the tree should only include nodes created by the local project.
3179
  final bool summaryTree;
3180 3181

  /// Maximum descendents of [DiagnosticsNode] before truncating.
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
  final int maxDescendentsTruncatableNode;

  @override
  final bool includeProperties;

  @override
  final int subtreeDepth;

  @override
  final bool expandPropertyValues;

3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
  /// Callback to add additional experimental serialization properties.
  ///
  /// This callback can be used to customize the serialization of DiagnosticsNode
  /// objects for experimental features in widget inspector clients such as
  /// [Dart DevTools](https://github.com/flutter/devtools).
  /// For example, [Dart DevTools](https://github.com/flutter/devtools)
  /// can evaluate the following expression to register a VM Service API
  /// with a custom serialization to experiment with visualizing layouts.
  ///
  /// The following code samples demonstrates adding the [RenderObject] associated
  /// with an [Element] to the serialized data for all elements in the tree:
  ///
  /// ```dart
  /// Map<String, Object> getDetailsSubtreeWithRenderObject(
  ///   String id,
  ///   String groupName,
  ///   int subtreeDepth,
  /// ) {
  ///   return _nodeToJson(
  ///     root,
  ///     InspectorSerializationDelegate(
  ///       groupName: groupName,
  ///       summaryTree: false,
  ///       subtreeDepth: subtreeDepth,
  ///       includeProperties: true,
  ///       service: this,
  ///       addAdditionalPropertiesCallback: (DiagnosticsNode node, _SerializationDelegate delegate) {
  ///         final Map<String, Object> additionalJson = <String, Object>{};
  ///         final Object value = node.value;
  ///         if (value is Element) {
  ///           final renderObject = value.renderObject;
  ///           additionalJson['renderObject'] = renderObject?.toDiagnosticsNode()?.toJsonMap(
  ///             delegate.copyWith(
  ///               subtreeDepth: 0,
  ///               includeProperties: true,
  ///             ),
  ///           );
  ///         }
  ///         return additionalJson;
  ///       },
  ///     ),
  ///  );
  /// }
  /// ```
3237
  final Map<String, Object>? Function(DiagnosticsNode, InspectorSerializationDelegate)? addAdditionalPropertiesCallback;
3238

3239 3240
  final List<DiagnosticsNode> _nodesCreatedByLocalProject = <DiagnosticsNode>[];

3241
  bool get _interactive => groupName != null;
3242 3243

  @override
3244 3245 3246
  Map<String, Object?> additionalNodeProperties(DiagnosticsNode node) {
    final Map<String, Object?> result = <String, Object?>{};
    final Object? value = node.value;
3247
    if (_interactive) {
3248 3249
      result['objectId'] = service.toId(node, groupName!);
      result['valueId'] = service.toId(value, groupName!);
3250 3251 3252 3253
    }
    if (summaryTree) {
      result['summaryTree'] = true;
    }
3254
    final _Location? creationLocation = _getCreationLocation(value);
3255 3256 3257
    if (creationLocation != null) {
      result['locationId'] = _toLocationId(creationLocation);
      result['creationLocation'] = creationLocation.toJsonMap();
3258
      if (service._isLocalCreationLocation(creationLocation.file)) {
3259 3260 3261 3262
        _nodesCreatedByLocalProject.add(node);
        result['createdByLocalProject'] = true;
      }
    }
3263
    if (addAdditionalPropertiesCallback != null) {
3264
      result.addAll(addAdditionalPropertiesCallback!(node, this) ?? <String, Object>{});
3265
    }
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
    return result;
  }

  @override
  DiagnosticsSerializationDelegate delegateForNode(DiagnosticsNode node) {
    // The tricky special case here is that when in the detailsTree,
    // we keep subtreeDepth from going down to zero until we reach nodes
    // that also exist in the summary tree. This ensures that every time
    // you expand a node in the details tree, you expand the entire subtree
    // up until you reach the next nodes shared with the summary tree.
    return summaryTree || subtreeDepth > 1 || service._shouldShowInSummaryTree(node)
        ? copyWith(subtreeDepth: subtreeDepth - 1)
        : this;
  }

  @override
3282 3283
  List<DiagnosticsNode> filterChildren(List<DiagnosticsNode> nodes, DiagnosticsNode owner) {
    return service._filterChildren(nodes, this);
3284 3285 3286
  }

  @override
3287
  List<DiagnosticsNode> filterProperties(List<DiagnosticsNode> nodes, DiagnosticsNode owner) {
3288
    final bool createdByLocalProject = _nodesCreatedByLocalProject.contains(owner);
3289
    return nodes.where((DiagnosticsNode node) {
3290 3291 3292 3293 3294
      return !node.isFiltered(createdByLocalProject ? DiagnosticLevel.fine : DiagnosticLevel.info);
    }).toList();
  }

  @override
3295
  List<DiagnosticsNode> truncateNodesList(List<DiagnosticsNode> nodes, DiagnosticsNode? owner) {
3296
    if (maxDescendentsTruncatableNode >= 0 &&
3297
        owner!.allowTruncate == true &&
3298 3299 3300 3301 3302 3303 3304
        nodes.length > maxDescendentsTruncatableNode) {
      nodes = service._truncateNodes(nodes, maxDescendentsTruncatableNode);
    }
    return nodes;
  }

  @override
3305
  DiagnosticsSerializationDelegate copyWith({int? subtreeDepth, bool? includeProperties}) {
3306
    return InspectorSerializationDelegate(
3307 3308 3309 3310 3311 3312 3313
      groupName: groupName,
      summaryTree: summaryTree,
      maxDescendentsTruncatableNode: maxDescendentsTruncatableNode,
      expandPropertyValues: expandPropertyValues,
      subtreeDepth: subtreeDepth ?? this.subtreeDepth,
      includeProperties: includeProperties ?? this.includeProperties,
      service: service,
3314
      addAdditionalPropertiesCallback: addAdditionalPropertiesCallback,
3315 3316 3317
    );
  }
}