widget_inspector_test.dart 131 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
@TestOn('!chrome')
6 7 8 9 10 11 12

// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=456"
@Tags(<String>['no-shuffle'])

13
import 'dart:async';
14
import 'dart:convert';
15
import 'dart:math';
16
import 'dart:ui' as ui;
17

18
import 'package:flutter/foundation.dart';
19
import 'package:flutter/gestures.dart' show DragStartBehavior;
20
import 'package:flutter/material.dart';
21 22 23
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';

24 25
import 'widget_inspector_test_utils.dart';

26 27 28 29
// Start of block of code where widget creation location line numbers and
// columns will impact whether tests pass.

class ClockDemo extends StatefulWidget {
30
  const ClockDemo({ Key? key }) : super(key: key);
31
  @override
32
  State<ClockDemo> createState() => _ClockDemoState();
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
}

class _ClockDemoState extends State<ClockDemo> {
  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const Text('World Clock'),
          makeClock('Local', DateTime.now().timeZoneOffset.inHours),
          makeClock('UTC', 0),
          makeClock('New York, NY', -4),
          makeClock('Chicago, IL', -5),
          makeClock('Denver, CO', -6),
          makeClock('Los Angeles, CA', -7),
        ],
      ),
    );
  }

55
  Widget makeClock(String label, int utcOffset) {
56 57 58 59 60 61 62 63 64 65 66 67
    return Stack(
      children: <Widget>[
        const Icon(Icons.watch),
        Text(label),
        ClockText(utcOffset: utcOffset),
      ],
    );
  }
}

class ClockText extends StatefulWidget {
  const ClockText({
68
    Key? key,
69 70 71
    this.utcOffset = 0,
  }) : super(key: key);

72
  final int utcOffset;
73 74

  @override
75
  State<ClockText> createState() => _ClockTextState();
76 77 78
}

class _ClockTextState extends State<ClockText> {
79
  DateTime? currentTime = DateTime.now();
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

  void updateTime() {
    setState(() {
      currentTime = DateTime.now();
    });
  }

  void stopClock() {
    setState(() {
      currentTime = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (currentTime == null) {
      return const Text('stopped');
    }
    return Text(
99
      currentTime!
100 101 102 103 104 105 106 107 108 109
          .toUtc()
          .add(Duration(hours: widget.utcOffset))
          .toIso8601String(),
    );
  }
}

// End of block of code where widget creation location line numbers and
// columns will impact whether tests pass.

110 111 112 113 114 115 116 117
// Class to enable building trees of nodes with cycles between properties of
// nodes and the properties of those properties.
// This exposed a bug in code serializing DiagnosticsNode objects that did not
// handle these sorts of cycles robustly.
class CyclicDiagnostic extends DiagnosticableTree {
  CyclicDiagnostic(this.name);

  // Field used to create cyclic relationships.
118
  CyclicDiagnostic? related;
119 120 121 122 123
  final List<DiagnosticsNode> children = <DiagnosticsNode>[];

  final String name;

  @override
124
  String toStringShort() => '${objectRuntimeType(this, 'CyclicDiagnostic')}-$name';
125 126 127 128

  // We have to override toString to avoid the toString call itself triggering a
  // stack overflow.
  @override
129
  String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
130 131 132 133 134 135 136 137 138 139 140 141 142
    return toStringShort();
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<CyclicDiagnostic>('related', related));
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() => children;
}

143
class _CreationLocation {
144
  _CreationLocation({
145
    required this.id,
146 147 148
    required this.file,
    required this.line,
    required this.column,
149
    required this.name,
150 151
  });

152
  final int id;
153 154 155
  final String file;
  final int line;
  final int column;
156
  String? name;
157 158
}

159
typedef InspectorServiceExtensionCallback = FutureOr<Map<String, Object>> Function(Map<String, String> parameters);
160

161 162 163 164 165 166 167
class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary {
  @override
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      // Draw some debug paint UI interleaving creating layers and drawing
      // directly to the context's canvas.
168
      final Paint paint = Paint()
169 170 171 172
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1.0
        ..color = Colors.red;
      {
173 174 175
        final PictureLayer pictureLayer = PictureLayer(Offset.zero & size);
        final ui.PictureRecorder recorder = ui.PictureRecorder();
        final Canvas pictureCanvas = Canvas(recorder);
176 177 178
        pictureCanvas.drawCircle(Offset.zero, 20.0, paint);
        pictureLayer.picture = recorder.endRecording();
        context.addLayer(
179
          OffsetLayer()
180 181 182 183 184 185 186 187 188 189
            ..offset = offset
            ..append(pictureLayer),
        );
      }
      context.canvas.drawLine(
        offset,
        offset.translate(size.width, size.height),
        paint,
      );
      {
190 191 192
        final PictureLayer pictureLayer = PictureLayer(Offset.zero & size);
        final ui.PictureRecorder recorder = ui.PictureRecorder();
        final Canvas pictureCanvas = Canvas(recorder);
193 194 195
        pictureCanvas.drawCircle(const Offset(20.0, 20.0), 20.0, paint);
        pictureLayer.picture = recorder.endRecording();
        context.addLayer(
196
          OffsetLayer()
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            ..offset = offset
            ..append(pictureLayer),
        );
      }
      paint.color = Colors.blue;
      context.canvas.drawLine(
        offset,
        offset.translate(size.width * 0.5, size.height * 0.5),
        paint,
      );
      return true;
    }());
  }
}

class RepaintBoundaryWithDebugPaint extends RepaintBoundary {
  /// Creates a widget that isolates repaints.
  const RepaintBoundaryWithDebugPaint({
215 216
    Key? key,
    Widget? child,
217 218 219 220
  }) : super(key: key, child: child);

  @override
  RenderRepaintBoundary createRenderObject(BuildContext context) {
221
    return RenderRepaintBoundaryWithDebugPaint();
222 223 224 225
  }
}

int getChildLayerCount(OffsetLayer layer) {
226
  Layer? child = layer.firstChild;
227 228 229 230 231 232 233 234
  int count = 0;
  while (child != null) {
    count++;
    child = child.nextSibling;
  }
  return count;
}

235
void main() {
236
  _TestWidgetInspectorService.runTests();
237 238
}

239
class _TestWidgetInspectorService extends TestWidgetInspectorService {
240 241
  // These tests need access to protected members of WidgetInspectorService.
  static void runTests() {
242
    final TestWidgetInspectorService service = TestWidgetInspectorService();
243 244
    WidgetInspectorService.instance = service;

245 246 247 248
    tearDown(() {
      service.resetAllState();
    });

249 250 251
    testWidgets('WidgetInspector smoke test', (WidgetTester tester) async {
      // This is a smoke test to verify that adding the inspector doesn't crash.
      await tester.pumpWidget(
252
        Directionality(
253
          textDirection: TextDirection.ltr,
254
          child: Stack(
255
            children: const <Widget>[
256 257 258
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
259 260 261
            ],
          ),
        ),
262 263 264
      );

      await tester.pumpWidget(
265
        Directionality(
266
          textDirection: TextDirection.ltr,
267
          child: WidgetInspector(
268
            selectButtonBuilder: null,
269
            child: Stack(
270
              children: const <Widget>[
271 272 273
                Text('a', textDirection: TextDirection.ltr),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
274 275 276 277
              ],
            ),
          ),
        ),
278 279 280 281 282 283 284
      );

      expect(true, isTrue); // Expect that we reach here without crashing.
    });

    testWidgets('WidgetInspector interaction test', (WidgetTester tester) async {
      final List<String> log = <String>[];
285 286 287
      final GlobalKey selectButtonKey = GlobalKey();
      final GlobalKey inspectorKey = GlobalKey();
      final GlobalKey topButtonKey = GlobalKey();
288 289

      Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) {
290
        return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null));
291 292 293
      }
      // State type is private, hence using dynamic.
      dynamic getInspectorState() => inspectorKey.currentState;
294
      String paragraphText(RenderParagraph paragraph) {
295
        final TextSpan textSpan = paragraph.text as TextSpan;
296
        return textSpan.text!;
297
      }
298 299

      await tester.pumpWidget(
300
        Directionality(
301
          textDirection: TextDirection.ltr,
302
          child: WidgetInspector(
303 304
            key: inspectorKey,
            selectButtonBuilder: selectButtonBuilder,
305 306
            child: Material(
              child: ListView(
307
                children: <Widget>[
308
                  ElevatedButton(
309 310 311 312 313 314
                    key: topButtonKey,
                    onPressed: () {
                      log.add('top');
                    },
                    child: const Text('TOP'),
                  ),
315
                  ElevatedButton(
316 317 318 319 320 321
                    onPressed: () {
                      log.add('bottom');
                    },
                    child: const Text('BOTTOM'),
                  ),
                ],
322
              ),
323 324 325 326 327
            ),
          ),
        ),
      );

328
      expect(getInspectorState().selection.current, isNull); // ignore: avoid_dynamic_calls
329
      await tester.tap(find.text('TOP'), warnIfMissed: false);
330 331 332
      await tester.pump();
      // Tap intercepted by the inspector
      expect(log, equals(<String>[]));
333
      // ignore: avoid_dynamic_calls
334
      final InspectorSelection selection = getInspectorState().selection as InspectorSelection;
335 336
      expect(paragraphText(selection.current! as RenderParagraph), equals('TOP'));
      final RenderObject topButton = find.byKey(topButtonKey).evaluate().first.renderObject!;
337
      expect(selection.candidates, contains(topButton));
338 339 340 341 342 343 344 345 346

      await tester.tap(find.text('TOP'));
      expect(log, equals(<String>['top']));
      log.clear();

      await tester.tap(find.text('BOTTOM'));
      expect(log, equals(<String>['bottom']));
      log.clear();
      // Ensure the inspector selection has not changed to bottom.
347
      // ignore: avoid_dynamic_calls
348
      expect(paragraphText(getInspectorState().selection.current as RenderParagraph), equals('TOP'));
349 350 351 352 353 354

      await tester.tap(find.byKey(selectButtonKey));
      await tester.pump();

      // We are now back in select mode so tapping the bottom button will have
      // not trigger a click but will cause it to be selected.
355
      await tester.tap(find.text('BOTTOM'), warnIfMissed: false);
356 357
      expect(log, equals(<String>[]));
      log.clear();
358
      // ignore: avoid_dynamic_calls
359
      expect(paragraphText(getInspectorState().selection.current as RenderParagraph), equals('BOTTOM'));
360 361 362 363
    });

    testWidgets('WidgetInspector non-invertible transform regression test', (WidgetTester tester) async {
      await tester.pumpWidget(
364
        Directionality(
365
          textDirection: TextDirection.ltr,
366
          child: WidgetInspector(
367
            selectButtonBuilder: null,
368 369 370
            child: Transform(
              transform: Matrix4.identity()..scale(0.0),
              child: Stack(
371
                children: const <Widget>[
372 373 374
                  Text('a', textDirection: TextDirection.ltr),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
375 376 377
                ],
              ),
            ),
378
          ),
379
        ),
380 381
      );

382
      await tester.tap(find.byType(Transform), warnIfMissed: false);
383

384 385
      expect(true, isTrue); // Expect that we reach here without crashing.
    });
386

387
    testWidgets('WidgetInspector scroll test', (WidgetTester tester) async {
388 389 390
      final Key childKey = UniqueKey();
      final GlobalKey selectButtonKey = GlobalKey();
      final GlobalKey inspectorKey = GlobalKey();
391

392
      Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) {
393
        return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null));
394 395 396 397 398
      }
      // State type is private, hence using dynamic.
      dynamic getInspectorState() => inspectorKey.currentState;

      await tester.pumpWidget(
399
        Directionality(
400
          textDirection: TextDirection.ltr,
401
          child: WidgetInspector(
402 403
            key: inspectorKey,
            selectButtonBuilder: selectButtonBuilder,
404
            child: ListView(
405
              dragStartBehavior: DragStartBehavior.down,
406
              children: <Widget>[
407
                Container(
408 409 410 411 412 413 414 415 416
                  key: childKey,
                  height: 5000.0,
                ),
              ],
            ),
          ),
        ),
      );
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
417

418
      await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false);
419
      await tester.pump();
420

421 422
      // Fling does nothing as are in inspect mode.
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
423

424
      await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false);
425
      await tester.pump();
426

427 428
      // Fling still does nothing as are in inspect mode.
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
429

430
      await tester.tap(find.byType(ListView), warnIfMissed: false);
431
      await tester.pump();
432
      expect(getInspectorState().selection.current, isNotNull); // ignore: avoid_dynamic_calls
433

434 435 436
      // Now out of inspect mode due to the click.
      await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0);
      await tester.pump();
437

438
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-200.0));
439

440 441 442 443
      await tester.fling(find.byType(ListView), const Offset(0.0, 200.0), 200.0);
      await tester.pump();

      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
444
    });
445 446 447 448 449

    testWidgets('WidgetInspector long press', (WidgetTester tester) async {
      bool didLongPress = false;

      await tester.pumpWidget(
450
        Directionality(
451
          textDirection: TextDirection.ltr,
452
          child: WidgetInspector(
453
            selectButtonBuilder: null,
454
            child: GestureDetector(
455 456 457 458 459 460
              onLongPress: () {
                expect(didLongPress, isFalse);
                didLongPress = true;
              },
              child: const Text('target', textDirection: TextDirection.ltr),
            ),
461
          ),
462
        ),
463 464
      );

465
      await tester.longPress(find.text('target'), warnIfMissed: false);
466 467 468 469 470
      // The inspector will swallow the long press.
      expect(didLongPress, isFalse);
    });

    testWidgets('WidgetInspector offstage', (WidgetTester tester) async {
471 472
      final GlobalKey inspectorKey = GlobalKey();
      final GlobalKey clickTarget = GlobalKey();
473

474
      Widget createSubtree({ double? width, Key? key }) {
475
        return Stack(
476
          children: <Widget>[
477
            Positioned(
478 479 480 481 482
              key: key,
              left: 0.0,
              top: 0.0,
              width: width,
              height: 100.0,
483
              child: Text(width.toString(), textDirection: TextDirection.ltr),
484 485 486 487 488
            ),
          ],
        );
      }
      await tester.pumpWidget(
489
        Directionality(
490
          textDirection: TextDirection.ltr,
491
          child: WidgetInspector(
492 493
            key: inspectorKey,
            selectButtonBuilder: null,
494
            child: Overlay(
495
              initialEntries: <OverlayEntry>[
496
                OverlayEntry(
497 498 499 500
                  opaque: false,
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 94.0),
                ),
501
                OverlayEntry(
502 503 504 505
                  opaque: true,
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 95.0),
                ),
506
                OverlayEntry(
507 508 509 510 511 512
                  opaque: false,
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 96.0, key: clickTarget),
                ),
              ],
            ),
513
          ),
514
        ),
515
      );
516

517
      await tester.longPress(find.byKey(clickTarget), warnIfMissed: false);
518 519 520 521
      // State type is private, hence using dynamic.
      final dynamic inspectorState = inspectorKey.currentState;
      // The object with width 95.0 wins over the object with width 94.0 because
      // the subtree with width 94.0 is offstage.
522
      // ignore: avoid_dynamic_calls
523 524 525 526
      expect(inspectorState.selection.current.semanticBounds.width, equals(95.0));

      // Exactly 2 out of the 3 text elements should be in the candidate list of
      // objects to select as only 2 are onstage.
527
      // ignore: avoid_dynamic_calls
528 529 530
      expect(inspectorState.selection.candidates.where((RenderObject object) => object is RenderParagraph).length, equals(2));
    });

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    testWidgets('WidgetInspector with Transform above', (WidgetTester tester) async {
      final GlobalKey childKey = GlobalKey();
      final GlobalKey repaintBoundaryKey = GlobalKey();

      final Matrix4 mainTransform = Matrix4.identity()
          ..translate(50.0, 30.0)
          ..scale(0.8, 0.8)
          ..translate(100.0, 50.0);

      await tester.pumpWidget(
        RepaintBoundary(
          key: repaintBoundaryKey,
          child: Container(
            color: Colors.grey,
            child: Transform(
              transform: mainTransform,
              child: Directionality(
                textDirection: TextDirection.ltr,
                child: WidgetInspector(
                  selectButtonBuilder: null,
                  child: Container(
                    color: Colors.white,
                    child: Center(
                      child: Container(
                        key: childKey,
                        height: 100.0,
                        width: 50.0,
                        color: Colors.red,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      );

569
      await tester.tap(find.byKey(childKey), warnIfMissed: false);
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      await tester.pump();

      await expectLater(
        find.byKey(repaintBoundaryKey),
        matchesGoldenFile('inspector.overlay_positioning_with_transform.png'),
      );
    });

    testWidgets('Multiple widget inspectors', (WidgetTester tester) async {
      // This test verifies that interacting with different inspectors
      // works correctly. This use case may be an app that displays multiple
      // apps inside (i.e. a storyboard).
      final GlobalKey selectButton1Key = GlobalKey();
      final GlobalKey selectButton2Key = GlobalKey();

      final GlobalKey inspector1Key = GlobalKey();
      final GlobalKey inspector2Key = GlobalKey();

      final GlobalKey child1Key = GlobalKey();
      final GlobalKey child2Key = GlobalKey();

      InspectorSelectButtonBuilder selectButtonBuilder(Key key) {
        return (BuildContext context, VoidCallback onPressed) {
593
          return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null));
594 595 596 597 598 599 600 601
        };
      }

      // State type is private, hence using dynamic.
      // The inspector state is static, so it's enough with reading one of them.
      dynamic getInspectorState() => inspector1Key.currentState;
      String paragraphText(RenderParagraph paragraph) {
        final TextSpan textSpan = paragraph.text as TextSpan;
602
        return textSpan.text!;
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
      }

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Row(
            children: <Widget>[
              Flexible(
                child: WidgetInspector(
                  key: inspector1Key,
                  selectButtonBuilder: selectButtonBuilder(selectButton1Key),
                  child: Container(
                    key: child1Key,
                    child: const Text('Child 1'),
                  ),
                ),
              ),
              Flexible(
                child: WidgetInspector(
                  key: inspector2Key,
                  selectButtonBuilder: selectButtonBuilder(selectButton2Key),
                  child: Container(
                    key: child2Key,
                    child: const Text('Child 2'),
                  ),
                ),
              ),
            ],
          ),
        ),
      );

635
      // ignore: avoid_dynamic_calls
636 637
      final InspectorSelection selection = getInspectorState().selection as InspectorSelection;
      // The selection is static, so it may be initialized from previous tests.
638
      selection.clear();
639

640
      await tester.tap(find.text('Child 1'), warnIfMissed: false);
641
      await tester.pump();
642
      expect(paragraphText(selection.current! as RenderParagraph), equals('Child 1'));
643

644
      await tester.tap(find.text('Child 2'), warnIfMissed: false);
645
      await tester.pump();
646
      expect(paragraphText(selection.current! as RenderParagraph), equals('Child 2'));
647 648
    });

649 650 651 652 653 654 655 656
    test('WidgetInspectorService null id', () {
      service.disposeAllGroups();
      expect(service.toObject(null), isNull);
      expect(service.toId(null, 'test-group'), isNull);
    });

    test('WidgetInspectorService dispose group', () {
      service.disposeAllGroups();
657
      final Object a = Object();
658 659 660
      const String group1 = 'group-1';
      const String group2 = 'group-2';
      const String group3 = 'group-3';
661
      final String? aId = service.toId(a, group1);
662 663 664 665 666 667 668 669 670 671 672
      expect(service.toId(a, group2), equals(aId));
      expect(service.toId(a, group3), equals(aId));
      service.disposeGroup(group1);
      service.disposeGroup(group2);
      expect(service.toObject(aId), equals(a));
      service.disposeGroup(group3);
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    test('WidgetInspectorService dispose id', () {
      service.disposeAllGroups();
673 674
      final Object a = Object();
      final Object b = Object();
675 676
      const String group1 = 'group-1';
      const String group2 = 'group-2';
677 678
      final String? aId = service.toId(a, group1);
      final String? bId = service.toId(b, group1);
679 680 681 682 683 684 685 686 687 688 689
      expect(service.toId(a, group2), equals(aId));
      service.disposeId(bId, group1);
      expect(() => service.toObject(bId), throwsFlutterError);
      service.disposeId(aId, group1);
      expect(service.toObject(aId), equals(a));
      service.disposeId(aId, group2);
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    test('WidgetInspectorService toObjectForSourceLocation', () {
      const String group = 'test-group';
690
      const Text widget = Text('a', textDirection: TextDirection.ltr);
691
      service.disposeAllGroups();
692
      final String id = service.toId(widget, group)!;
693 694
      expect(service.toObjectForSourceLocation(id), equals(widget));
      final Element element = widget.createElement();
695
      final String elementId = service.toId(element, group)!;
696 697 698 699 700 701 702
      expect(service.toObjectForSourceLocation(elementId), equals(widget));
      expect(element, isNot(equals(widget)));
      service.disposeGroup(group);
      expect(() => service.toObjectForSourceLocation(elementId), throwsFlutterError);
    });

    test('WidgetInspectorService object id test', () {
703 704 705 706
      const Text a = Text('a', textDirection: TextDirection.ltr);
      const Text b = Text('b', textDirection: TextDirection.ltr);
      const Text c = Text('c', textDirection: TextDirection.ltr);
      const Text d = Text('d', textDirection: TextDirection.ltr);
707 708 709 710 711 712

      const String group1 = 'group-1';
      const String group2 = 'group-2';
      const String group3 = 'group-3';
      service.disposeAllGroups();

713 714 715 716
      final String? aId = service.toId(a, group1);
      final String? bId = service.toId(b, group2);
      final String? cId = service.toId(c, group3);
      final String? dId = service.toId(d, group1);
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
      // Make sure we get a consistent id if we add the object to a group multiple
      // times.
      expect(aId, equals(service.toId(a, group1)));
      expect(service.toObject(aId), equals(a));
      expect(service.toObject(aId), isNot(equals(b)));
      expect(service.toObject(bId), equals(b));
      expect(service.toObject(cId), equals(c));
      expect(service.toObject(dId), equals(d));
      // Make sure we get a consistent id even if we add the object to a different
      // group.
      expect(aId, equals(service.toId(a, group3)));
      expect(aId, isNot(equals(bId)));
      expect(aId, isNot(equals(cId)));

      service.disposeGroup(group3);
    });

    testWidgets('WidgetInspectorService maybeSetSelection', (WidgetTester tester) async {
      await tester.pumpWidget(
736
        Directionality(
737
          textDirection: TextDirection.ltr,
738
          child: Stack(
739
            children: const <Widget>[
740 741 742
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
743 744
            ],
          ),
745
        ),
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;

      service.disposeAllGroups();
      service.selection.clear();
      int selectionChangedCount = 0;
      service.selectionChangedCallback = () => selectionChangedCount++;
      service.setSelection('invalid selection');
      expect(selectionChangedCount, equals(0));
      expect(service.selection.currentElement, isNull);
      service.setSelection(elementA);
      expect(selectionChangedCount, equals(1));
      expect(service.selection.currentElement, equals(elementA));
      expect(service.selection.current, equals(elementA.renderObject));

      service.setSelection(elementB.renderObject);
      expect(selectionChangedCount, equals(2));
      expect(service.selection.current, equals(elementB.renderObject));
765
      expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element));
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

      service.setSelection('invalid selection');
      expect(selectionChangedCount, equals(2));
      expect(service.selection.current, equals(elementB.renderObject));

      service.setSelectionById(service.toId(elementA, 'my-group'));
      expect(selectionChangedCount, equals(3));
      expect(service.selection.currentElement, equals(elementA));
      expect(service.selection.current, equals(elementA.renderObject));

      service.setSelectionById(service.toId(elementA, 'my-group'));
      expect(selectionChangedCount, equals(3));
      expect(service.selection.currentElement, equals(elementA));
    });

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
    testWidgets('WidgetInspectorService defunct selection regression test', (WidgetTester tester) async {
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service.setSelection(elementA);
      expect(service.selection.currentElement, equals(elementA));
      expect(service.selection.current, equals(elementA.renderObject));

      await tester.pumpWidget(
        const SizedBox(
          child: Text('b', textDirection: TextDirection.ltr),
        ),
      );
      // Selection is now empty as the element is defunct.
      expect(service.selection.currentElement, equals(null));
      expect(service.selection.current, equals(null));

      // Verify that getting the debug creation location of the defunct element
      // does not crash.
      expect(debugIsLocalCreationLocation(elementA), isFalse);

      // Verify that generating json for a defunct element does not crash.
      expect(
        elementA.toDiagnosticsNode().toJsonMap(
          InspectorSerializationDelegate(
            service: service,
            summaryTree: false,
            includeProperties: true,
            addAdditionalPropertiesCallback: null,
          ),
        ),
        isNotNull,
      );

      final Element elementB = find.text('b').evaluate().first;
      service.setSelection(elementB);
      expect(service.selection.currentElement, equals(elementB));
      expect(service.selection.current, equals(elementB.renderObject));

      // Set selection back to a defunct element.
      service.setSelection(elementA);

      expect(service.selection.currentElement, equals(null));
      expect(service.selection.current, equals(null));
    });

836 837 838 839
    testWidgets('WidgetInspectorService getParentChain', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
840
        Directionality(
841
          textDirection: TextDirection.ltr,
842
          child: Stack(
843
            children: const <Widget>[
844 845 846
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
847 848
            ],
          ),
849
        ),
850 851 852 853
      );

      service.disposeAllGroups();
      final Element elementB = find.text('b').evaluate().first;
854 855
      final String bId = service.toId(elementB, group)!;
      final Object? jsonList = json.decode(service.getParentChain(bId, group));
856
      expect(jsonList, isList);
857
      final List<Object?> chainElements = jsonList! as List<Object?>;
858
      final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList();
859 860 861 862 863 864
      // Sanity check that the chain goes back to the root.
      expect(expectedChain.first, tester.binding.renderViewElement);

      expect(chainElements.length, equals(expectedChain.length));
      for (int i = 0; i < expectedChain.length; i += 1) {
        expect(chainElements[i], isMap);
865
        final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>;
866 867
        final Element element = expectedChain[i];
        expect(chainNode['node'], isMap);
868
        final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>;
869 870
        expect(service.toObject(jsonNode['valueId']! as String), equals(element));
        expect(service.toObject(jsonNode['objectId']! as String), isA<DiagnosticsNode>());
871 872

        expect(chainNode['children'], isList);
873
        final List<Object?> jsonChildren = chainNode['children']! as List<Object?>;
874 875 876 877 878 879 880 881 882 883
        final List<Element> childrenElements = <Element>[];
        element.visitChildren(childrenElements.add);
        expect(jsonChildren.length, equals(childrenElements.length));
        if (i + 1 == expectedChain.length) {
          expect(chainNode['childIndex'], isNull);
        } else {
          expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1])));
        }
        for (int j = 0; j < childrenElements.length; j += 1) {
          expect(jsonChildren[j], isMap);
884
          final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>;
885 886
          expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j]));
          expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
887 888 889 890 891 892 893 894
        }
      }
    });

    test('WidgetInspectorService getProperties', () {
      final DiagnosticsNode diagnostic = const Text('a', textDirection: TextDirection.ltr).toDiagnosticsNode();
      const String group = 'group';
      service.disposeAllGroups();
895
      final String id = service.toId(diagnostic, group)!;
896
      final List<Object?> propertiesJson = json.decode(service.getProperties(id, group)) as List<Object?>;
897 898 899 900
      final List<DiagnosticsNode> properties = diagnostic.getProperties();
      expect(properties, isNotEmpty);
      expect(propertiesJson.length, equals(properties.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
901
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
902 903
        expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
904 905 906 907 908 909 910
      }
    });

    testWidgets('WidgetInspectorService getChildren', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
911
        Directionality(
912
          textDirection: TextDirection.ltr,
913
          child: Stack(
914
            children: const <Widget>[
915 916 917
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
918 919 920 921 922 923
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
      service.disposeAllGroups();
924
      final String id = service.toId(diagnostic, group)!;
925
      final List<Object?> propertiesJson = json.decode(service.getChildren(id, group)) as List<Object?>;
926 927 928 929
      final List<DiagnosticsNode> children = diagnostic.getChildren();
      expect(children.length, equals(3));
      expect(propertiesJson.length, equals(children.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
930
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
931 932
        expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
933 934 935 936 937
      }
    });

    testWidgets('WidgetInspectorService creationLocation', (WidgetTester tester) async {
      await tester.pumpWidget(
938
        Directionality(
939
          textDirection: TextDirection.ltr,
940
          child: Stack(
941
            children: const <Widget>[
942 943 944
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
945 946 947 948 949 950 951 952
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;

      service.disposeAllGroups();
953
      service.setPubRootDirectories(<String>[]);
954
      service.setSelection(elementA, 'my-group');
955 956
      final Map<String, Object?> jsonA = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
      final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>;
957
      expect(creationLocationA, isNotNull);
958 959 960
      final String fileA = creationLocationA['file']! as String;
      final int lineA = creationLocationA['line']! as int;
      final int columnA = creationLocationA['column']! as int;
961 962
      final String nameA = creationLocationA['name']! as String;
      expect(nameA, equals('Text'));
963 964

      service.setSelection(elementB, 'my-group');
965 966
      final Map<String, Object?> jsonB = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
      final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>;
967
      expect(creationLocationB, isNotNull);
968 969 970
      final String fileB = creationLocationB['file']! as String;
      final int lineB = creationLocationB['line']! as int;
      final int columnB = creationLocationB['column']! as int;
971 972
      final String? nameB = creationLocationB['name'] as String?;
      expect(nameB, equals('Text'));
973 974 975 976 977 978
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(fileA, equals(fileB));
      // We don't hardcode the actual lines the widgets are created on as that
      // would make this test fragile.
      expect(lineA + 1, equals(lineB));
      // Column numbers are more stable than line numbers.
979
      expect(columnA, equals(15));
980
      expect(columnA, equals(columnB));
981
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
982

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    testWidgets('test transformDebugCreator will re-order if after stack trace', (WidgetTester tester) async {
      final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked();
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
998
      service.setSelection(elementA, 'my-group');
999
      late String pubRootTest;
1000
      if (widgetTracked) {
1001
        final Map<String, Object?> jsonObject = json.decode(
1002 1003
          service.getSelectedWidget(null, 'my-group'),
        ) as Map<String, Object?>;
1004
        final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1005
        expect(creationLocation, isNotNull);
1006
        final String fileA = creationLocation['file']! as String;
1007 1008 1009 1010 1011 1012 1013
        expect(fileA, endsWith('widget_inspector_test.dart'));
        expect(jsonObject, isNot(contains('createdByLocalProject')));
        final List<String> segments = Uri
          .parse(fileA)
          .pathSegments;
        // Strip a couple subdirectories away to generate a plausible pub root
        // directory.
1014
        pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1015
        service.setPubRootDirectories(<String>[pubRootTest]);
1016 1017 1018 1019 1020 1021 1022
      }
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      builder.add(StringProperty('dummy1', 'value'));
      builder.add(StringProperty('dummy2', 'value'));
      builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null));
      builder.add(DiagnosticsDebugCreator(DebugCreator(elementA)));

1023
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1024 1025 1026 1027 1028 1029 1030 1031
      expect(nodes.length, 5);
      expect(nodes[0].runtimeType, StringProperty);
      expect(nodes[0].name, 'dummy1');
      expect(nodes[1].runtimeType, StringProperty);
      expect(nodes[1].name, 'dummy2');
      // transformed node should come in front of stack trace.
      if (widgetTracked) {
        expect(nodes[2].runtimeType, DiagnosticsBlock);
1032
        final DiagnosticsBlock node = nodes[2] as DiagnosticsBlock;
1033 1034
        final List<DiagnosticsNode> children = node.getChildren();
        expect(children.length, 1);
1035
        final ErrorDescription child = children[0] as ErrorDescription;
1036
        expect(child.valueToString(), contains(Uri.parse(pubRootTest).path));
1037 1038
      } else {
        expect(nodes[2].runtimeType, ErrorDescription);
1039
        final ErrorDescription node = nodes[2] as ErrorDescription;
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true);
      }
      expect(nodes[3].runtimeType, ErrorSpacer);
      expect(nodes[4].runtimeType, DiagnosticsStackTrace);
    });

    testWidgets('test transformDebugCreator will not re-order if before stack trace', (WidgetTester tester) async {
      final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked();
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
1061
      late String pubRootTest;
1062
      if (widgetTracked) {
1063
        final Map<String, Object?> jsonObject = json.decode(
1064 1065
          service.getSelectedWidget(null, 'my-group'),
        ) as Map<String, Object?>;
1066
        final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1067
        expect(creationLocation, isNotNull);
1068
        final String fileA = creationLocation['file']! as String;
1069 1070 1071 1072 1073 1074 1075
        expect(fileA, endsWith('widget_inspector_test.dart'));
        expect(jsonObject, isNot(contains('createdByLocalProject')));
        final List<String> segments = Uri
          .parse(fileA)
          .pathSegments;
        // Strip a couple subdirectories away to generate a plausible pub root
        // directory.
1076
        pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1077
        service.setPubRootDirectories(<String>[pubRootTest]);
1078 1079 1080 1081 1082 1083 1084
      }
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      builder.add(StringProperty('dummy1', 'value'));
      builder.add(DiagnosticsDebugCreator(DebugCreator(elementA)));
      builder.add(StringProperty('dummy2', 'value'));
      builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null));

1085
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1086 1087 1088 1089 1090 1091
      expect(nodes.length, 5);
      expect(nodes[0].runtimeType, StringProperty);
      expect(nodes[0].name, 'dummy1');
      // transformed node stays at original place.
      if (widgetTracked) {
        expect(nodes[1].runtimeType, DiagnosticsBlock);
1092
        final DiagnosticsBlock node = nodes[1] as DiagnosticsBlock;
1093 1094
        final List<DiagnosticsNode> children = node.getChildren();
        expect(children.length, 1);
1095
        final ErrorDescription child = children[0] as ErrorDescription;
1096
        expect(child.valueToString(), contains(Uri.parse(pubRootTest).path));
1097 1098
      } else {
        expect(nodes[1].runtimeType, ErrorDescription);
1099
        final ErrorDescription node = nodes[1] as ErrorDescription;
1100 1101 1102 1103 1104 1105
        expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true);
      }
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, StringProperty);
      expect(nodes[3].name, 'dummy2');
      expect(nodes[4].runtimeType, DiagnosticsStackTrace);
1106
    }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag.
1107

1108 1109 1110 1111
    testWidgets('test transformDebugCreator will add DevToolsDeepLinkProperty for overflow errors', (WidgetTester tester) async {
      activeDevToolsServerAddress = 'http://127.0.0.1:9100';
      connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/';

1112 1113
      setupDefaultPubRootDirectory(service);

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom'));
      builder.add(DiagnosticsDebugCreator(DebugCreator(elementA)));
      builder.add(StringProperty('dummy2', 'value'));

1133
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1134 1135 1136 1137 1138 1139 1140
      expect(nodes.length, 6);
      expect(nodes[0].runtimeType, ErrorSummary);
      expect(nodes[1].runtimeType, DiagnosticsBlock);
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, DevToolsDeepLinkProperty);
      expect(nodes[4].runtimeType, ErrorSpacer);
      expect(nodes[5].runtimeType, StringProperty);
1141
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1142 1143 1144 1145

    testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty for non-overflow errors', (WidgetTester tester) async {
      activeDevToolsServerAddress = 'http://127.0.0.1:9100';
      connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/';
1146
      setupDefaultPubRootDirectory(service);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      builder.add(ErrorSummary('some other error'));
      builder.add(DiagnosticsDebugCreator(DebugCreator(elementA)));
      builder.add(StringProperty('dummy2', 'value'));

1167
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1168 1169 1170 1171 1172
      expect(nodes.length, 4);
      expect(nodes[0].runtimeType, ErrorSummary);
      expect(nodes[1].runtimeType, DiagnosticsBlock);
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, StringProperty);
1173
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked());  // [intended] Test requires --track-widget-creation flag.
1174 1175 1176 1177

    testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty if devtoolsServerAddress is unavailable', (WidgetTester tester) async {
      activeDevToolsServerAddress = null;
      connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/';
1178
      setupDefaultPubRootDirectory(service);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom'));
      builder.add(DiagnosticsDebugCreator(DebugCreator(elementA)));
      builder.add(StringProperty('dummy2', 'value'));

1199
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1200 1201 1202 1203 1204
      expect(nodes.length, 4);
      expect(nodes[0].runtimeType, ErrorSummary);
      expect(nodes[1].runtimeType, DiagnosticsBlock);
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, StringProperty);
1205
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked());  // [intended] Test requires --track-widget-creation flag.
1206

1207 1208
    testWidgets('WidgetInspectorService setPubRootDirectories', (WidgetTester tester) async {
      await tester.pumpWidget(
1209
        Directionality(
1210
          textDirection: TextDirection.ltr,
1211
          child: Stack(
1212
            children: const <Widget>[
1213 1214 1215
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1216 1217 1218 1219 1220 1221 1222
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service.disposeAllGroups();
1223
      service.setPubRootDirectories(<String>[]);
1224
      service.setSelection(elementA, 'my-group');
1225 1226
      Map<String, Object?> jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
      Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1227
      expect(creationLocation, isNotNull);
1228
      final String fileA = creationLocation['file']! as String;
1229 1230 1231 1232 1233
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(jsonObject, isNot(contains('createdByLocalProject')));
      final List<String> segments = Uri.parse(fileA).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1234
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1235
      service.setPubRootDirectories(<String>[pubRootTest]);
1236 1237 1238 1239

      service.setSelection(elementA, 'my-group');
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));

1240
      service.setPubRootDirectories(<String>['/invalid/$pubRootTest']);
1241 1242
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')));

1243
      service.setPubRootDirectories(<String>['file://$pubRootTest']);
1244 1245
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));

1246
      service.setPubRootDirectories(<String>['$pubRootTest/different']);
1247 1248
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')));

1249
      service.setPubRootDirectories(<String>[
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        '/invalid/$pubRootTest',
        pubRootTest,
      ]);
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));

      // The RichText child of the Text widget is created by the core framework
      // not the current package.
      final Element richText = find.descendant(
        of: find.text('a'),
        matching: find.byType(RichText),
      ).evaluate().first;
      service.setSelection(richText, 'my-group');
1262
      service.setPubRootDirectories(<String>[pubRootTest]);
1263
      jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
1264
      expect(jsonObject, isNot(contains('createdByLocalProject')));
1265
      creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1266 1267 1268
      expect(creationLocation, isNotNull);
      // This RichText widget is created by the build method of the Text widget
      // thus the creation location is in text.dart not basic.dart
1269
      final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments;
1270
      expect(pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'));
1271 1272

      // Strip off /src/widgets/text.dart.
1273
      final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
1274
      service.setPubRootDirectories(<String>[pubRootFramework]);
1275 1276 1277 1278
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));
      service.setSelection(elementA, 'my-group');
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')));

1279
      service.setPubRootDirectories(<String>[pubRootFramework, pubRootTest]);
1280 1281 1282 1283
      service.setSelection(elementA, 'my-group');
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));
      service.setSelection(richText, 'my-group');
      expect(json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'));
1284
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1285 1286

    test('ext.flutter.inspector.disposeGroup', () async {
1287
      final Object a = Object();
1288 1289 1290
      const String group1 = 'group-1';
      const String group2 = 'group-2';
      const String group3 = 'group-3';
1291
      final String? aId = service.toId(a, group1);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
      expect(service.toId(a, group2), equals(aId));
      expect(service.toId(a, group3), equals(aId));
      await service.testExtension('disposeGroup', <String, String>{'objectGroup': group1});
      await service.testExtension('disposeGroup', <String, String>{'objectGroup': group2});
      expect(service.toObject(aId), equals(a));
      await service.testExtension('disposeGroup', <String, String>{'objectGroup': group3});
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    test('ext.flutter.inspector.disposeId', () async {
1302 1303
      final Object a = Object();
      final Object b = Object();
1304 1305
      const String group1 = 'group-1';
      const String group2 = 'group-2';
1306 1307
      final String aId = service.toId(a, group1)!;
      final String bId = service.toId(b, group1)!;
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
      expect(service.toId(a, group2), equals(aId));
      await service.testExtension('disposeId', <String, String>{'arg': bId, 'objectGroup': group1});
      expect(() => service.toObject(bId), throwsFlutterError);
      await service.testExtension('disposeId', <String, String>{'arg': aId, 'objectGroup': group1});
      expect(service.toObject(aId), equals(a));
      await service.testExtension('disposeId', <String, String>{'arg': aId, 'objectGroup': group2});
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    testWidgets('ext.flutter.inspector.setSelection', (WidgetTester tester) async {
      await tester.pumpWidget(
1319
        Directionality(
1320
          textDirection: TextDirection.ltr,
1321
          child: Stack(
1322
            children: const <Widget>[
1323 1324 1325
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;

      service.disposeAllGroups();
      service.selection.clear();
      int selectionChangedCount = 0;
      service.selectionChangedCallback = () => selectionChangedCount++;
      service.setSelection('invalid selection');
      expect(selectionChangedCount, equals(0));
      expect(service.selection.currentElement, isNull);
      service.setSelection(elementA);
      expect(selectionChangedCount, equals(1));
      expect(service.selection.currentElement, equals(elementA));
      expect(service.selection.current, equals(elementA.renderObject));

      service.setSelection(elementB.renderObject);
      expect(selectionChangedCount, equals(2));
      expect(service.selection.current, equals(elementB.renderObject));
1348
      expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element));
1349 1350 1351 1352 1353

      service.setSelection('invalid selection');
      expect(selectionChangedCount, equals(2));
      expect(service.selection.current, equals(elementB.renderObject));

1354
      await service.testExtension('setSelectionById', <String, String>{'arg': service.toId(elementA, 'my-group')!, 'objectGroup': 'my-group'});
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
      expect(selectionChangedCount, equals(3));
      expect(service.selection.currentElement, equals(elementA));
      expect(service.selection.current, equals(elementA.renderObject));

      service.setSelectionById(service.toId(elementA, 'my-group'));
      expect(selectionChangedCount, equals(3));
      expect(service.selection.currentElement, equals(elementA));
    });

    testWidgets('ext.flutter.inspector.getParentChain', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1368
        Directionality(
1369
          textDirection: TextDirection.ltr,
1370
          child: Stack(
1371
            children: const <Widget>[
1372 1373 1374
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1375 1376
            ],
          ),
1377
        ),
1378 1379 1380
      );

      final Element elementB = find.text('b').evaluate().first;
1381 1382
      final String bId = service.toId(elementB, group)!;
      final Object? jsonList = await service.testExtension('getParentChain', <String, String>{'arg': bId, 'objectGroup': group});
1383
      expect(jsonList, isList);
1384
      final List<Object?> chainElements = jsonList! as List<Object?>;
1385
      final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList();
1386 1387 1388 1389 1390 1391
      // Sanity check that the chain goes back to the root.
      expect(expectedChain.first, tester.binding.renderViewElement);

      expect(chainElements.length, equals(expectedChain.length));
      for (int i = 0; i < expectedChain.length; i += 1) {
        expect(chainElements[i], isMap);
1392
        final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>;
1393 1394
        final Element element = expectedChain[i];
        expect(chainNode['node'], isMap);
1395
        final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>;
1396 1397
        expect(service.toObject(jsonNode['valueId']! as String), equals(element));
        expect(service.toObject(jsonNode['objectId']! as String), isA<DiagnosticsNode>());
1398 1399

        expect(chainNode['children'], isList);
1400
        final List<Object?> jsonChildren = chainNode['children']! as List<Object?>;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
        final List<Element> childrenElements = <Element>[];
        element.visitChildren(childrenElements.add);
        expect(jsonChildren.length, equals(childrenElements.length));
        if (i + 1 == expectedChain.length) {
          expect(chainNode['childIndex'], isNull);
        } else {
          expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1])));
        }
        for (int j = 0; j < childrenElements.length; j += 1) {
          expect(jsonChildren[j], isMap);
1411
          final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>;
1412 1413
          expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j]));
          expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
1414
        }
1415
      }
1416 1417 1418 1419 1420
    });

    test('ext.flutter.inspector.getProperties', () async {
      final DiagnosticsNode diagnostic = const Text('a', textDirection: TextDirection.ltr).toDiagnosticsNode();
      const String group = 'group';
1421
      final String id = service.toId(diagnostic, group)!;
1422
      final List<Object?> propertiesJson = (await service.testExtension('getProperties', <String, String>{'arg': id, 'objectGroup': group}))! as List<Object?>;
1423 1424 1425 1426
      final List<DiagnosticsNode> properties = diagnostic.getProperties();
      expect(properties, isNotEmpty);
      expect(propertiesJson.length, equals(properties.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
1427
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
1428 1429
        expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
1430
      }
1431 1432 1433 1434 1435 1436
    });

    testWidgets('ext.flutter.inspector.getChildren', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1437
        Directionality(
1438
          textDirection: TextDirection.ltr,
1439
          child: Stack(
1440
            children: const <Widget>[
1441 1442 1443
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1444 1445
            ],
          ),
1446
        ),
1447 1448
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
1449
      final String id = service.toId(diagnostic, group)!;
1450
      final List<Object?> propertiesJson = (await service.testExtension('getChildren', <String, String>{'arg': id, 'objectGroup': group}))! as List<Object?>;
1451 1452 1453 1454
      final List<DiagnosticsNode> children = diagnostic.getChildren();
      expect(children.length, equals(3));
      expect(propertiesJson.length, equals(children.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
1455
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
1456 1457
        expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
1458 1459 1460
      }
    });

1461 1462 1463 1464
    testWidgets('ext.flutter.inspector.getChildrenDetailsSubtree', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1465
        Directionality(
1466
          textDirection: TextDirection.ltr,
1467
          child: Stack(
1468
            children: const <Widget>[
1469 1470 1471
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1472 1473 1474 1475 1476
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
1477
      final String id = service.toId(diagnostic, group)!;
1478
      final List<Object?> childrenJson = (await service.testExtension('getChildrenDetailsSubtree', <String, String>{'arg': id, 'objectGroup': group}))! as List<Object?>;
1479 1480 1481 1482
      final List<DiagnosticsNode> children = diagnostic.getChildren();
      expect(children.length, equals(3));
      expect(childrenJson.length, equals(children.length));
      for (int i = 0; i < childrenJson.length; ++i) {
1483
        final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>;
1484 1485
        expect(service.toObject(childJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
1486
        final List<Object?> propertiesJson = childJson['properties']! as List<Object?>;
1487
        final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId']! as String)! as DiagnosticsNode;
1488
        final List<DiagnosticsNode> expectedProperties = diagnosticsNode.getProperties();
1489
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
1490
          final Object? property = service.toObject(propertyJson['objectId']! as String);
Dan Field's avatar
Dan Field committed
1491
          expect(property, isA<DiagnosticsNode>());
1492
          expect(expectedProperties, contains(property));
1493 1494 1495 1496 1497 1498 1499 1500
        }
      }
    });

    testWidgets('WidgetInspectorService getDetailsSubtree', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1501
        Directionality(
1502
          textDirection: TextDirection.ltr,
1503
          child: Stack(
1504
            children: const <Widget>[
1505 1506 1507
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1508 1509 1510 1511 1512
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
1513
      final String id = service.toId(diagnostic, group)!;
1514
      final Map<String, Object?> subtreeJson = (await service.testExtension('getDetailsSubtree', <String, String>{'arg': id, 'objectGroup': group}))! as Map<String, Object?>;
1515
      expect(subtreeJson['objectId'], equals(id));
1516
      final List<Object?> childrenJson = subtreeJson['children']! as List<Object?>;
1517 1518 1519 1520
      final List<DiagnosticsNode> children = diagnostic.getChildren();
      expect(children.length, equals(3));
      expect(childrenJson.length, equals(children.length));
      for (int i = 0; i < childrenJson.length; ++i) {
1521
        final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>;
1522 1523
        expect(service.toObject(childJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
1524 1525
        final List<Object?> propertiesJson = childJson['properties']! as List<Object?>;
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
1526 1527
          expect(propertyJson, isNot(contains('children')));
        }
1528
        final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId']! as String)! as DiagnosticsNode;
1529
        final List<DiagnosticsNode> expectedProperties = diagnosticsNode.getProperties();
1530
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
1531
          final Object property = service.toObject(propertyJson['objectId']! as String)!;
Dan Field's avatar
Dan Field committed
1532
          expect(property, isA<DiagnosticsNode>());
1533 1534 1535 1536
          expect(expectedProperties, contains(property));
        }
      }

1537
      final Map<String, Object?> deepSubtreeJson = (await service.testExtension(
1538 1539
        'getDetailsSubtree',
        <String, String>{'arg': id, 'objectGroup': group, 'subtreeDepth': '3'},
1540 1541 1542 1543 1544
      ))! as Map<String, Object?>;
      final List<Object?> deepChildrenJson = deepSubtreeJson['children']! as List<Object?>;
      for (final Map<String, Object?> childJson in deepChildrenJson.cast<Map<String, Object?>>()) {
        final List<Object?> propertiesJson = childJson['properties']! as List<Object?>;
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
1545
          expect(propertyJson, contains('children'));
1546 1547 1548 1549
        }
      }
    });

1550 1551 1552 1553 1554 1555 1556 1557 1558
    testWidgets('cyclic diagnostics regression test', (WidgetTester tester) async {
      const String group = 'test-group';
      final CyclicDiagnostic a = CyclicDiagnostic('a');
      final CyclicDiagnostic b = CyclicDiagnostic('b');
      a.related = b;
      a.children.add(b.toDiagnosticsNode());
      b.related = a;

      final DiagnosticsNode diagnostic = a.toDiagnosticsNode();
1559
      final String id = service.toId(diagnostic, group)!;
1560
      final Map<String, Object?> subtreeJson = (await service.testExtension('getDetailsSubtree', <String, String>{'arg': id, 'objectGroup': group}))! as Map<String, Object?>;
1561
      expect(subtreeJson['objectId'], equals(id));
1562
      expect(subtreeJson, contains('children'));
1563
      final List<Object?> propertiesJson = subtreeJson['properties']! as List<Object?>;
1564
      expect(propertiesJson.length, equals(1));
1565
      final Map<String, Object?> relatedProperty = propertiesJson.first! as Map<String, Object?>;
1566 1567
      expect(relatedProperty['name'], equals('related'));
      expect(relatedProperty['description'], equals('CyclicDiagnostic-b'));
1568 1569 1570
      expect(relatedProperty, contains('isDiagnosticableValue'));
      expect(relatedProperty, isNot(contains('children')));
      expect(relatedProperty, contains('properties'));
1571
      final List<Object?> relatedWidgetProperties = relatedProperty['properties']! as List<Object?>;
1572
      expect(relatedWidgetProperties.length, equals(1));
1573
      final Map<String, Object?> nestedRelatedProperty = relatedWidgetProperties.first! as Map<String, Object?>;
1574 1575 1576 1577 1578
      expect(nestedRelatedProperty['name'], equals('related'));
      // Make sure we do not include properties or children for diagnostic a
      // which we already included as the root node as that would indicate a
      // cycle.
      expect(nestedRelatedProperty['description'], equals('CyclicDiagnostic-a'));
1579 1580 1581
      expect(nestedRelatedProperty, contains('isDiagnosticableValue'));
      expect(nestedRelatedProperty, isNot(contains('properties')));
      expect(nestedRelatedProperty, isNot(contains('children')));
1582 1583
    });

1584 1585 1586 1587
    testWidgets('ext.flutter.inspector.getRootWidgetSummaryTree', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1588
        Directionality(
1589
          textDirection: TextDirection.ltr,
1590
          child: Stack(
1591
            children: const <Widget>[
1592 1593 1594
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1595 1596 1597 1598 1599 1600 1601 1602 1603
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service.disposeAllGroups();
      await service.testExtension('setPubRootDirectories', <String, String>{});
      service.setSelection(elementA, 'my-group');
1604
      final Map<String, dynamic> jsonA = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, dynamic>;
1605 1606

      await service.testExtension('setPubRootDirectories', <String, String>{});
1607
      Map<String, Object?> rootJson = (await service.testExtension('getRootWidgetSummaryTree', <String, String>{'objectGroup': group}))! as Map<String, Object?>;
1608 1609 1610
      // We haven't yet properly specified which directories are summary tree
      // directories so we get an empty tree other than the root that is always
      // included.
1611
      final Object? rootWidget = service.toObject(rootJson['valueId']! as String);
1612
      expect(rootWidget, equals(WidgetsBinding.instance?.renderViewElement));
1613
      List<Object?> childrenJson = rootJson['children']! as List<Object?>;
1614 1615 1616
      // There are no summary tree children.
      expect(childrenJson.length, equals(0));

1617
      final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>;
1618
      expect(creationLocation, isNotNull);
1619
      final String testFile = creationLocation['file']! as String;
1620 1621 1622 1623
      expect(testFile, endsWith('widget_inspector_test.dart'));
      final List<String> segments = Uri.parse(testFile).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1624
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1625 1626
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest});

1627 1628
      rootJson = (await service.testExtension('getRootWidgetSummaryTree', <String, String>{'objectGroup': group}))! as Map<String, Object?>;
      childrenJson = rootJson['children']! as List<Object?>;
1629 1630
      // The tree of nodes returned contains all widgets created directly by the
      // test.
1631
      childrenJson = rootJson['children']! as List<Object?>;
1632 1633
      expect(childrenJson.length, equals(1));

1634
      List<Object?> alternateChildrenJson = (await service.testExtension('getChildrenSummaryTree', <String, String>{'arg': rootJson['objectId']! as String, 'objectGroup': group}))! as List<Object?>;
1635
      expect(alternateChildrenJson.length, equals(1));
1636 1637
      Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>;
      Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>;
1638 1639 1640 1641
      expect(childJson['description'], startsWith('Directionality'));
      expect(alternateChildJson['description'], startsWith('Directionality'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));

1642 1643
      childrenJson = childJson['children']! as List<Object?>;
      alternateChildrenJson = (await service.testExtension('getChildrenSummaryTree', <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group}))! as List<Object?>;
1644 1645
      expect(alternateChildrenJson.length, equals(1));
      expect(childrenJson.length, equals(1));
1646 1647
      alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>;
      childJson = childrenJson[0]! as Map<String, Object?>;
1648 1649 1650
      expect(childJson['description'], startsWith('Stack'));
      expect(alternateChildJson['description'], startsWith('Stack'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));
1651
      childrenJson = childJson['children']! as List<Object?>;
1652

1653 1654
      childrenJson = childJson['children']! as List<Object?>;
      alternateChildrenJson = (await service.testExtension('getChildrenSummaryTree', <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group}))! as List<Object?>;
1655 1656
      expect(alternateChildrenJson.length, equals(3));
      expect(childrenJson.length, equals(3));
1657 1658
      alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>;
      childJson = childrenJson[2]! as Map<String, Object?>;
1659 1660 1661
      expect(childJson['description'], startsWith('Text'));
      expect(alternateChildJson['description'], startsWith('Text'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));
1662
      alternateChildrenJson = (await service.testExtension('getChildrenSummaryTree', <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group}))! as List<Object?>;
1663
      expect(alternateChildrenJson.length , equals(0));
1664
      // Tests are failing when this typo is fixed.
1665
      expect(childJson['chidlren'], isNull);
1666
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1667 1668 1669 1670 1671

    testWidgets('ext.flutter.inspector.getSelectedSummaryWidget', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
1672
        Directionality(
1673
          textDirection: TextDirection.ltr,
1674
          child: Stack(
1675
            children: const <Widget>[
1676 1677 1678
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      final List<DiagnosticsNode> children = elementA.debugDescribeChildren();
      expect(children.length, equals(1));
      final DiagnosticsNode richTextDiagnostic = children.first;

      service.disposeAllGroups();
      await service.testExtension('setPubRootDirectories', <String, String>{});
      service.setSelection(elementA, 'my-group');
1692
      final Map<String, Object?> jsonA = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
1693 1694 1695
      service.setSelection(richTextDiagnostic.value, 'my-group');

      await service.testExtension('setPubRootDirectories', <String, String>{});
1696
      Map<String, Object?>? summarySelection = await service.testExtension('getSelectedSummaryWidget', <String, String>{'objectGroup': group}) as Map<String, Object?>?;
1697 1698 1699 1700
      // No summary selection because we haven't set the pub root directories
      // yet to indicate what directories are in the summary tree.
      expect(summarySelection, isNull);

1701
      final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>;
1702
      expect(creationLocation, isNotNull);
1703
      final String testFile = creationLocation['file']! as String;
1704 1705 1706 1707
      expect(testFile, endsWith('widget_inspector_test.dart'));
      final List<String> segments = Uri.parse(testFile).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1708
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1709 1710
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest});

1711
      summarySelection = (await service.testExtension('getSelectedSummaryWidget', <String, String>{'objectGroup': group}))! as Map<String, Object?>;
1712 1713 1714
      expect(summarySelection['valueId'], isNotNull);
      // We got the Text element instead of the selected RichText element
      // because only the RichText element is part of the summary tree.
1715
      expect(service.toObject(summarySelection['valueId']! as String), elementA);
1716 1717 1718

      // Verify tha the regular getSelectedWidget method still returns
      // the RichText object not the Text element.
1719
      final Map<String, Object?> regularSelection = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
1720
      expect(service.toObject(regularSelection['valueId']! as String), richTextDiagnostic.value);
1721
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1722

1723 1724
    testWidgets('ext.flutter.inspector creationLocation', (WidgetTester tester) async {
      await tester.pumpWidget(
1725
        Directionality(
1726
          textDirection: TextDirection.ltr,
1727
          child: Stack(
1728
            children: const <Widget>[
1729 1730 1731
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1732 1733
            ],
          ),
1734
        ),
1735 1736 1737 1738 1739 1740 1741
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;

      service.disposeAllGroups();
      await service.testExtension('setPubRootDirectories', <String, String>{});
      service.setSelection(elementA, 'my-group');
1742 1743
      final Map<String, Object?> jsonA = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
      final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>;
1744
      expect(creationLocationA, isNotNull);
1745 1746 1747
      final String fileA = creationLocationA['file']! as String;
      final int lineA = creationLocationA['line']! as int;
      final int columnA = creationLocationA['column']! as int;
1748 1749

      service.setSelection(elementB, 'my-group');
1750 1751
      final Map<String, Object?> jsonB = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
      final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>;
1752
      expect(creationLocationB, isNotNull);
1753 1754 1755
      final String fileB = creationLocationB['file']! as String;
      final int lineB = creationLocationB['line']! as int;
      final int columnB = creationLocationB['column']! as int;
1756 1757 1758 1759 1760 1761
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(fileA, equals(fileB));
      // We don't hardcode the actual lines the widgets are created on as that
      // would make this test fragile.
      expect(lineA + 1, equals(lineB));
      // Column numbers are more stable than line numbers.
1762
      expect(columnA, equals(15));
1763
      expect(columnA, equals(columnB));
1764
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1765 1766 1767

    testWidgets('ext.flutter.inspector.setPubRootDirectories', (WidgetTester tester) async {
      await tester.pumpWidget(
1768
        Directionality(
1769
          textDirection: TextDirection.ltr,
1770
          child: Stack(
1771
            children: const <Widget>[
1772 1773 1774
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
1775 1776
            ],
          ),
1777
        ),
1778 1779 1780 1781 1782
      );
      final Element elementA = find.text('a').evaluate().first;

      await service.testExtension('setPubRootDirectories', <String, String>{});
      service.setSelection(elementA, 'my-group');
1783 1784
      Map<String, Object?> jsonObject = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
      Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1785
      expect(creationLocation, isNotNull);
1786
      final String fileA = creationLocation['file']! as String;
1787 1788 1789 1790 1791
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(jsonObject, isNot(contains('createdByLocalProject')));
      final List<String> segments = Uri.parse(fileA).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1792
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest});

      service.setSelection(elementA, 'my-group');
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': '/invalid/$pubRootTest'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), isNot(contains('createdByLocalProject')));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': 'file://$pubRootTest'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': '$pubRootTest/different'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), isNot(contains('createdByLocalProject')));

      await service.testExtension('setPubRootDirectories', <String, String>{
        'arg0': '/unrelated/$pubRootTest',
        'arg1': 'file://$pubRootTest',
      });

      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));

      // The RichText child of the Text widget is created by the core framework
      // not the current package.
      final Element richText = find.descendant(
        of: find.text('a'),
        matching: find.byType(RichText),
      ).evaluate().first;
      service.setSelection(richText, 'my-group');
1821
      service.setPubRootDirectories(<String>[pubRootTest]);
1822
      jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
1823
      expect(jsonObject, isNot(contains('createdByLocalProject')));
1824
      creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1825 1826 1827
      expect(creationLocation, isNotNull);
      // This RichText widget is created by the build method of the Text widget
      // thus the creation location is in text.dart not basic.dart
1828
      final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments;
1829
      expect(pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'));
1830 1831

      // Strip off /src/widgets/text.dart.
1832
      final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootFramework});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));
      service.setSelection(elementA, 'my-group');
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), isNot(contains('createdByLocalProject')));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootFramework, 'arg1': pubRootTest});
      service.setSelection(elementA, 'my-group');
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));
      service.setSelection(richText, 'my-group');
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));
1843
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
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 1870 1871 1872
    testWidgets('ext.flutter.inspector.setPubRootDirectories extra args regression test', (WidgetTester tester) async {
      // Ensure that passing the isolate id as an argument won't break
      // setPubRootDirectories command.
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Stack(
            children: const <Widget>[
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      await service.testExtension('setPubRootDirectories', <String, String>{'isolateId': '34'});
      service.setSelection(elementA, 'my-group');
      final Map<String, Object?> jsonObject = (await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}))! as Map<String, Object?>;
      final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
      expect(creationLocation, isNotNull);
      final String fileA = creationLocation['file']! as String;
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(jsonObject, isNot(contains('createdByLocalProject')));
      final List<String> segments = Uri.parse(fileA).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1873
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest, 'isolateId': '34'});

      service.setSelection(elementA, 'my-group');
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': '/invalid/$pubRootTest', 'isolateId': '34'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), isNot(contains('createdByLocalProject')));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));

      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': '$pubRootTest/different', 'isolateId': '34'});
      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), isNot(contains('createdByLocalProject')));

      await service.testExtension('setPubRootDirectories', <String, String>{
        'arg0': '/unrelated/$pubRootTest',
        'isolateId': '34',
        'arg1': 'file://$pubRootTest',
      });

      expect(await service.testExtension('getSelectedWidget', <String, String>{'objectGroup': 'my-group'}), contains('createdByLocalProject'));
1895
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1896

1897 1898 1899 1900 1901 1902 1903
    Map<Object, Object?> removeLastEvent(List<Map<Object, Object?>> events) {
      final Map<Object, Object?> event = events.removeLast();
      // Verify that the event is json encodable.
      json.encode(event);
      return event;
    }

1904 1905 1906
    testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets', (WidgetTester tester) async {
      service.rebuildCount = 0;

1907
      await tester.pumpWidget(const ClockDemo());
1908 1909 1910 1911

      final Element clockDemoElement = find.byType(ClockDemo).evaluate().first;

      service.setSelection(clockDemoElement, 'my-group');
1912
      final Map<String, Object?> jsonObject = (await service.testExtension(
1913
        'getSelectedWidget',
1914
        <String, String>{'objectGroup': 'my-group'},
1915 1916
      ))! as Map<String, Object?>;
      final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1917
      expect(creationLocation, isNotNull);
1918
      final String file = creationLocation['file']! as String;
1919 1920 1921 1922
      expect(file, endsWith('widget_inspector_test.dart'));
      final List<String> segments = Uri.parse(file).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
1923
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1924
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest});
1925

1926
      final List<Map<Object, Object?>> rebuildEvents =
1927 1928 1929 1930 1931
          service.getEventsDispatched('Flutter.RebuiltWidgets');
      expect(rebuildEvents, isEmpty);

      expect(service.rebuildCount, equals(0));
      expect(
1932 1933 1934
        await service.testBoolExtension('trackRebuildDirtyWidgets', <String, String>{'enabled': 'true'}),
        equals('true'),
      );
1935 1936 1937 1938
      expect(service.rebuildCount, equals(1));
      await tester.pump();

      expect(rebuildEvents.length, equals(1));
1939
      Map<Object, Object?> event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
1940
      expect(event['startTime'], isA<int>());
1941
      List<int> data = event['events']! as List<int>;
1942 1943
      expect(data.length, equals(14));
      final int numDataEntries = data.length ~/ 2;
1944
      Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>;
1945 1946 1947
      expect(newLocations, isNotNull);
      expect(newLocations.length, equals(1));
      expect(newLocations.keys.first, equals(file));
1948 1949 1950 1951
      Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>;
      expect(fileLocationsMap, isNotNull);
      expect(fileLocationsMap.length, equals(1));
      expect(fileLocationsMap.keys.first, equals(file));
1952
      final List<int> locationsForFile = newLocations[file]!;
1953 1954 1955
      expect(locationsForFile.length, equals(21));
      final int numLocationEntries = locationsForFile.length ~/ 3;
      expect(numLocationEntries, equals(numDataEntries));
1956 1957 1958
      final Map<String, List<Object?>> locations = fileLocationsMap[file]!;
      expect(locations.length, equals(4));
      expect(locations['ids']!.length, equals(7));
1959

1960
      final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{};
1961
      _addToKnownLocationsMap(
1962
        knownLocations: knownLocations,
1963
        newLocations: fileLocationsMap,
1964 1965 1966 1967 1968 1969 1970 1971
      );
      int totalCount = 0;
      int maxCount = 0;
      for (int i = 0; i < data.length; i += 2) {
        final int id = data[i];
        final int count = data[i + 1];
        totalCount += count;
        maxCount = max(maxCount, count);
1972
        expect(knownLocations, contains(id));
1973 1974 1975 1976 1977 1978 1979 1980 1981
      }
      expect(totalCount, equals(27));
      // The creation locations that were rebuilt the most were rebuilt 6 times
      // as there are 6 instances of the ClockText widget.
      expect(maxCount, equals(6));

      final List<Element> clocks = find.byType(ClockText).evaluate().toList();
      expect(clocks.length, equals(6));
      // Update a single clock.
1982 1983
      StatefulElement clockElement = clocks.first as StatefulElement;
      _ClockTextState state = clockElement.state as _ClockTextState;
1984 1985 1986
      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
      expect(rebuildEvents.length, equals(1));
1987
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
1988
      expect(event['startTime'], isA<int>());
1989
      data = event['events']! as List<int>;
1990
      // No new locations were rebuilt.
1991
      expect(event, isNot(contains('newLocations')));
1992
      expect(event, isNot(contains('locations')));
1993 1994 1995 1996 1997 1998

      // There were two rebuilds: one for the ClockText element itself and one
      // for its child.
      expect(data.length, equals(4));
      int id = data[0];
      int count = data[1];
1999
      _CreationLocation location = knownLocations[id]!;
2000 2001
      expect(location.file, equals(file));
      // ClockText widget.
2002
      expect(location.line, equals(60));
2003
      expect(location.column, equals(9));
2004
      expect(location.name, equals('ClockText'));
2005 2006 2007 2008
      expect(count, equals(1));

      id = data[2];
      count = data[3];
2009
      location = knownLocations[id]!;
2010 2011
      expect(location.file, equals(file));
      // Text widget in _ClockTextState build method.
2012
      expect(location.line, equals(98));
2013
      expect(location.column, equals(12));
2014
      expect(location.name, equals('Text'));
2015 2016 2017 2018
      expect(count, equals(1));

      // Update 3 of the clocks;
      for (int i = 0; i < 3; i++) {
2019 2020
        clockElement = clocks[i] as StatefulElement;
        state = clockElement.state as _ClockTextState;
2021 2022 2023 2024 2025
        state.updateTime(); // Triggers a rebuild.
      }

      await tester.pump();
      expect(rebuildEvents.length, equals(1));
2026
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
2027
      expect(event['startTime'], isA<int>());
2028
      data = event['events']! as List<int>;
2029
      // No new locations were rebuilt.
2030
      expect(event, isNot(contains('newLocations')));
2031
      expect(event, isNot(contains('locations')));
2032 2033 2034 2035

      expect(data.length, equals(4));
      id = data[0];
      count = data[1];
2036
      location = knownLocations[id]!;
2037 2038
      expect(location.file, equals(file));
      // ClockText widget.
2039
      expect(location.line, equals(60));
2040
      expect(location.column, equals(9));
2041
      expect(location.name, equals('ClockText'));
2042 2043 2044 2045
      expect(count, equals(3)); // 3 clock widget instances rebuilt.

      id = data[2];
      count = data[3];
2046
      location = knownLocations[id]!;
2047 2048
      expect(location.file, equals(file));
      // Text widget in _ClockTextState build method.
2049
      expect(location.line, equals(98));
2050
      expect(location.column, equals(12));
2051
      expect(location.name, equals('Text'));
2052 2053 2054
      expect(count, equals(3)); // 3 clock widget instances rebuilt.

      // Update one clock 3 times.
2055 2056
      clockElement = clocks.first as StatefulElement;
      state = clockElement.state as _ClockTextState;
2057 2058 2059 2060 2061 2062
      state.updateTime(); // Triggers a rebuild.
      state.updateTime(); // Triggers a rebuild.
      state.updateTime(); // Triggers a rebuild.

      await tester.pump();
      expect(rebuildEvents.length, equals(1));
2063
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
2064
      expect(event['startTime'], isA<int>());
2065
      data = event['events']! as List<int>;
2066
      // No new locations were rebuilt.
2067
      expect(event, isNot(contains('newLocations')));
2068
      expect(event, isNot(contains('locations')));
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080

      expect(data.length, equals(4));
      id = data[0];
      count = data[1];
      // Even though a rebuild was triggered 3 times, only one rebuild actually
      // occurred.
      expect(count, equals(1));

      // Trigger a widget creation location that wasn't previously triggered.
      state.stopClock();
      await tester.pump();
      expect(rebuildEvents.length, equals(1));
2081
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
2082
      expect(event['startTime'], isA<int>());
2083 2084
      data = event['events']! as List<int>;
      newLocations = event['newLocations']! as Map<String, List<int>>;
2085
      fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>;
2086 2087 2088 2089 2090 2091 2092

      expect(data.length, equals(4));
      // The second pair in data is the previously unseen rebuild location.
      id = data[2];
      count = data[3];
      expect(count, equals(1));
      // Verify the rebuild location is new.
2093
      expect(knownLocations, isNot(contains(id)));
2094
      _addToKnownLocationsMap(
2095
        knownLocations: knownLocations,
2096
        newLocations: fileLocationsMap,
2097 2098
      );
      // Verify the rebuild location was included in the newLocations data.
2099
      expect(knownLocations, contains(id));
2100 2101 2102

      // Turn off rebuild counts.
      expect(
2103 2104 2105
        await service.testBoolExtension('trackRebuildDirtyWidgets', <String, String>{'enabled': 'false'}),
        equals('false'),
      );
2106 2107 2108 2109 2110

      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
      // Verify that rebuild events are not fired once the extension is disabled.
      expect(rebuildEvents, isEmpty);
2111
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
2112 2113 2114 2115

    testWidgets('ext.flutter.inspector.trackRepaintWidgets', (WidgetTester tester) async {
      service.rebuildCount = 0;

2116
      await tester.pumpWidget(const ClockDemo());
2117 2118 2119 2120

      final Element clockDemoElement = find.byType(ClockDemo).evaluate().first;

      service.setSelection(clockDemoElement, 'my-group');
2121
      final Map<String, Object?> jsonObject = (await service.testExtension(
2122 2123 2124
        'getSelectedWidget',
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, Object?>;
2125 2126
      final Map<String, Object?> creationLocation =
          jsonObject['creationLocation']! as Map<String, Object?>;
2127
      expect(creationLocation, isNotNull);
2128
      final String file = creationLocation['file']! as String;
2129 2130 2131 2132
      expect(file, endsWith('widget_inspector_test.dart'));
      final List<String> segments = Uri.parse(file).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub root
      // directory.
2133
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
2134
      await service.testExtension('setPubRootDirectories', <String, String>{'arg0': pubRootTest});
2135

2136
      final List<Map<Object, Object?>> repaintEvents =
2137 2138 2139 2140 2141
          service.getEventsDispatched('Flutter.RepaintWidgets');
      expect(repaintEvents, isEmpty);

      expect(service.rebuildCount, equals(0));
      expect(
2142 2143 2144
        await service.testBoolExtension('trackRepaintWidgets', <String, String>{'enabled': 'true'}),
        equals('true'),
      );
2145 2146 2147 2148 2149 2150 2151
      // Unlike trackRebuildDirtyWidgets, trackRepaintWidgets doesn't force a full
      // rebuild.
      expect(service.rebuildCount, equals(0));

      await tester.pump();

      expect(repaintEvents.length, equals(1));
2152
      Map<Object, Object?> event = removeLastEvent(repaintEvents);
Dan Field's avatar
Dan Field committed
2153
      expect(event['startTime'], isA<int>());
2154
      List<int> data = event['events']! as List<int>;
2155 2156
      expect(data.length, equals(18));
      final int numDataEntries = data.length ~/ 2;
2157
      final Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>;
2158 2159 2160
      expect(newLocations, isNotNull);
      expect(newLocations.length, equals(1));
      expect(newLocations.keys.first, equals(file));
2161 2162 2163 2164
      final Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>;
      expect(fileLocationsMap, isNotNull);
      expect(fileLocationsMap.length, equals(1));
      expect(fileLocationsMap.keys.first, equals(file));
2165
      final List<int> locationsForFile = newLocations[file]!;
2166 2167 2168
      expect(locationsForFile.length, equals(27));
      final int numLocationEntries = locationsForFile.length ~/ 3;
      expect(numLocationEntries, equals(numDataEntries));
2169 2170 2171
      final Map<String, List<Object?>> locations = fileLocationsMap[file]!;
      expect(locations.length, equals(4));
      expect(locations['ids']!.length, equals(9));
2172

2173
      final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{};
2174
      _addToKnownLocationsMap(
2175
        knownLocations: knownLocations,
2176
        newLocations: fileLocationsMap,
2177 2178 2179 2180 2181 2182 2183 2184
      );
      int totalCount = 0;
      int maxCount = 0;
      for (int i = 0; i < data.length; i += 2) {
        final int id = data[i];
        final int count = data[i + 1];
        totalCount += count;
        maxCount = max(maxCount, count);
2185
        expect(knownLocations, contains(id));
2186 2187 2188 2189 2190 2191 2192 2193 2194
      }
      expect(totalCount, equals(34));
      // The creation locations that were rebuilt the most were rebuilt 6 times
      // as there are 6 instances of the ClockText widget.
      expect(maxCount, equals(6));

      final List<Element> clocks = find.byType(ClockText).evaluate().toList();
      expect(clocks.length, equals(6));
      // Update a single clock.
2195 2196
      final StatefulElement clockElement = clocks.first as StatefulElement;
      final _ClockTextState state = clockElement.state as _ClockTextState;
2197 2198 2199
      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
      expect(repaintEvents.length, equals(1));
2200
      event = removeLastEvent(repaintEvents);
Dan Field's avatar
Dan Field committed
2201
      expect(event['startTime'], isA<int>());
2202
      data = event['events']! as List<int>;
2203
      // No new locations were rebuilt.
2204
      expect(event, isNot(contains('newLocations')));
2205
      expect(event, isNot(contains('locations')));
2206

2207
      // Triggering a rebuild of one widget in this app causes the whole app
2208 2209 2210 2211 2212 2213 2214 2215
      // to repaint.
      expect(data.length, equals(18));

      // TODO(jacobr): add an additional repaint test that uses multiple repaint
      // boundaries to test more complex repaint conditions.

      // Turn off rebuild counts.
      expect(
2216 2217 2218
        await service.testBoolExtension('trackRepaintWidgets', <String, String>{'enabled': 'false'}),
        equals('false'),
      );
2219 2220 2221

      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
2222
      // Verify that repaint events are not fired once the extension is disabled.
2223
      expect(repaintEvents, isEmpty);
2224
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
2225

2226
    testWidgets('ext.flutter.inspector.show', (WidgetTester tester) async {
2227 2228
      final Iterable<Map<Object, Object?>> extensionChangedEvents = service.getServiceExtensionStateChangedEvents('ext.flutter.inspector.show');
      Map<Object, Object?> extensionChangedEvent;
2229

2230
      service.rebuildCount = 0;
2231
      expect(extensionChangedEvents, isEmpty);
2232
      expect(await service.testBoolExtension('show', <String, String>{'enabled': 'true'}), equals('true'));
2233 2234 2235 2236
      expect(extensionChangedEvents.length, equals(1));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isTrue);
2237 2238 2239
      expect(service.rebuildCount, equals(1));
      expect(await service.testBoolExtension('show', <String, String>{}), equals('true'));
      expect(WidgetsApp.debugShowWidgetInspectorOverride, isTrue);
2240
      expect(extensionChangedEvents.length, equals(1));
2241
      expect(await service.testBoolExtension('show', <String, String>{'enabled': 'true'}), equals('true'));
2242 2243 2244 2245
      expect(extensionChangedEvents.length, equals(2));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isTrue);
2246 2247
      expect(service.rebuildCount, equals(1));
      expect(await service.testBoolExtension('show', <String, String>{'enabled': 'false'}), equals('false'));
2248 2249 2250 2251
      expect(extensionChangedEvents.length, equals(3));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isFalse);
2252
      expect(await service.testBoolExtension('show', <String, String>{}), equals('false'));
2253
      expect(extensionChangedEvents.length, equals(3));
2254 2255 2256
      expect(service.rebuildCount, equals(2));
      expect(WidgetsApp.debugShowWidgetInspectorOverride, isFalse);
    });
2257

2258
    testWidgets('ext.flutter.inspector.screenshot', (WidgetTester tester) async {
2259 2260 2261 2262 2263
      final GlobalKey outerContainerKey = GlobalKey();
      final GlobalKey paddingKey = GlobalKey();
      final GlobalKey redContainerKey = GlobalKey();
      final GlobalKey whiteContainerKey = GlobalKey();
      final GlobalKey sizedBoxKey = GlobalKey();
2264 2265 2266 2267 2268

      // Complex widget tree intended to exercise features such as children
      // with rotational transforms and clipping without introducing platform
      // specific behavior as text rendering would.
      await tester.pumpWidget(
2269 2270 2271
        Center(
          child: RepaintBoundaryWithDebugPaint(
            child: Container(
2272 2273
              key: outerContainerKey,
              color: Colors.white,
2274
              child: Padding(
2275 2276
                key: paddingKey,
                padding: const EdgeInsets.all(100.0),
2277
                child: SizedBox(
2278 2279 2280
                  key: sizedBoxKey,
                  height: 100.0,
                  width: 100.0,
2281
                  child: Transform.rotate(
2282
                    angle: 1.0, // radians
2283
                    child: ClipRRect(
2284 2285 2286 2287 2288 2289
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.elliptical(10.0, 20.0),
                        topRight: Radius.elliptical(5.0, 30.0),
                        bottomLeft: Radius.elliptical(2.5, 12.0),
                        bottomRight: Radius.elliptical(15.0, 6.0),
                      ),
2290
                      child: Container(
2291 2292
                        key: redContainerKey,
                        color: Colors.red,
2293
                        child: Container(
2294 2295
                          key: whiteContainerKey,
                          color: Colors.white,
2296 2297 2298
                          child: RepaintBoundary(
                            child: Center(
                              child: Container(
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
                                color: Colors.black,
                                height: 10.0,
                                width: 10.0,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      );

      final Element repaintBoundary =
          find.byType(RepaintBoundaryWithDebugPaint).evaluate().single;

2319
      final RenderRepaintBoundary renderObject = repaintBoundary.renderObject! as RenderRepaintBoundary;
2320

2321
      final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer;
2322 2323 2324 2325
      final int expectedChildLayerCount = getChildLayerCount(layer);
      expect(expectedChildLayerCount, equals(2));
      await expectLater(
        layer.toImage(renderObject.semanticBounds.inflate(50.0)),
2326
        matchesGoldenFile('inspector.repaint_boundary_margin.png'),
2327 2328 2329 2330 2331 2332 2333 2334 2335
      );

      // Regression test for how rendering with a pixel scale other than 1.0
      // was handled.
      await expectLater(
        layer.toImage(
          renderObject.semanticBounds.inflate(50.0),
          pixelRatio: 0.5,
        ),
2336
        matchesGoldenFile('inspector.repaint_boundary_margin_small.png'),
2337 2338 2339 2340 2341 2342 2343
      );

      await expectLater(
        layer.toImage(
          renderObject.semanticBounds.inflate(50.0),
          pixelRatio: 2.0,
        ),
2344
        matchesGoldenFile('inspector.repaint_boundary_margin_large.png'),
2345 2346
      );

2347 2348
      final Layer? layerParent = layer.parent;
      final Layer? firstChild = layer.firstChild;
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358

      expect(layerParent, isNotNull);
      expect(firstChild, isNotNull);

      await expectLater(
        service.screenshot(
          repaintBoundary,
          width: 300.0,
          height: 300.0,
        ),
2359
        matchesGoldenFile('inspector.repaint_boundary.png'),
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
      );

      // Verify that taking a screenshot didn't change the layers associated with
      // the renderObject.
      expect(renderObject.debugLayer, equals(layer));
      // Verify that taking a screenshot did not change the number of children
      // of the layer.
      expect(getChildLayerCount(layer), equals(expectedChildLayerCount));

      await expectLater(
        service.screenshot(
          repaintBoundary,
          width: 500.0,
          height: 500.0,
          margin: 50.0,
        ),
2376
        matchesGoldenFile('inspector.repaint_boundary_margin.png'),
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
      );

      // Verify that taking a screenshot didn't change the layers associated with
      // the renderObject.
      expect(renderObject.debugLayer, equals(layer));
      // Verify that taking a screenshot did not change the number of children
      // of the layer.
      expect(getChildLayerCount(layer), equals(expectedChildLayerCount));

      // Make sure taking a screenshot didn't change the parent of the layer.
      expect(layer.parent, equals(layerParent));

      await expectLater(
        service.screenshot(
          repaintBoundary,
          width: 300.0,
          height: 300.0,
          debugPaint: true,
        ),
2396
        matchesGoldenFile('inspector.repaint_boundary_debugPaint.png'),
2397 2398 2399 2400 2401 2402 2403 2404 2405
      );
      // Verify that taking a screenshot with debug paint on did not change
      // the number of children the layer has.
      expect(getChildLayerCount(layer), equals(expectedChildLayerCount));

      // Ensure that creating screenshots including ones with debug paint
      // hasn't changed the regular render of the widget.
      await expectLater(
        find.byType(RepaintBoundaryWithDebugPaint),
2406
        matchesGoldenFile('inspector.repaint_boundary.png'),
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
      );

      expect(renderObject.debugLayer, equals(layer));
      expect(layer.attached, isTrue);

      // Full size image
      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 100.0,
          height: 100.0,
        ),
2419
        matchesGoldenFile('inspector.container.png'),
2420 2421 2422 2423 2424 2425 2426 2427 2428
      );

      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 100.0,
          height: 100.0,
          debugPaint: true,
        ),
2429
        matchesGoldenFile('inspector.container_debugPaint.png'),
2430 2431 2432 2433 2434 2435
      );

      {
        // Verify calling the screenshot method still works if the RenderObject
        // needs to be laid out again.
        final RenderObject container =
2436
            find.byKey(outerContainerKey).evaluate().single.renderObject!;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
        container
          ..markNeedsLayout()
          ..markNeedsPaint();
        expect(container.debugNeedsLayout, isTrue);

        await expectLater(
          service.screenshot(
            find.byKey(outerContainerKey).evaluate().single,
            width: 100.0,
            height: 100.0,
            debugPaint: true,
          ),
2449
          matchesGoldenFile('inspector.container_debugPaint.png'),
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
        );
        expect(container.debugNeedsLayout, isFalse);
      }

      // Small image
      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 50.0,
          height: 100.0,
        ),
2461
        matchesGoldenFile('inspector.container_small.png'),
2462 2463 2464 2465 2466 2467 2468 2469 2470
      );

      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 400.0,
          height: 400.0,
          maxPixelRatio: 3.0,
        ),
2471
        matchesGoldenFile('inspector.container_large.png'),
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
      );

      // This screenshot will show the clip rect debug paint but no other
      // debug paint.
      await expectLater(
        service.screenshot(
          find.byType(ClipRRect).evaluate().single,
          width: 100.0,
          height: 100.0,
          debugPaint: true,
        ),
2483
        matchesGoldenFile('inspector.clipRect_debugPaint.png'),
2484 2485
      );

2486 2487
      final Element clipRect = find.byType(ClipRRect).evaluate().single;

2488
      final Future<ui.Image?> clipRectScreenshot = service.screenshot(
2489 2490 2491 2492 2493 2494
        clipRect,
        width: 100.0,
        height: 100.0,
        margin: 20.0,
        debugPaint: true,
      );
2495 2496 2497
      // Add a margin so that the clip icon shows up in the screenshot.
      // This golden image is platform dependent due to the clip icon.
      await expectLater(
2498
        clipRectScreenshot,
2499
        matchesGoldenFile('inspector.clipRect_debugPaint_margin.png'),
2500 2501 2502 2503
      );

      // Verify we get the same image if we go through the service extension
      // instead of invoking the screenshot method directly.
2504
      final Future<Object?> base64ScreenshotFuture = service.testExtension(
2505 2506
        'screenshot',
        <String, String>{
2507
          'id': service.toId(clipRect, 'group')!,
2508 2509 2510 2511 2512 2513 2514
          'width': '100.0',
          'height': '100.0',
          'margin': '20.0',
          'debugPaint': 'true',
        },
      );

2515
      final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as TestWidgetsFlutterBinding;
2516 2517
      final ui.Image screenshotImage = (await binding.runAsync<ui.Image>(() async {
        final String base64Screenshot = (await base64ScreenshotFuture)! as String;
2518 2519 2520
        final ui.Codec codec = await ui.instantiateImageCodec(base64.decode(base64Screenshot));
        final ui.FrameInfo frame = await codec.getNextFrame();
        return frame.image;
2521
      }, additionalTime: const Duration(seconds: 11)))!;
2522 2523 2524

      await expectLater(
        screenshotImage,
2525
        matchesReferenceImage((await clipRectScreenshot)!),
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
      );

      // Test with a very visible debug paint
      await expectLater(
        service.screenshot(
          find.byKey(paddingKey).evaluate().single,
          width: 300.0,
          height: 300.0,
          debugPaint: true,
        ),
2536
        matchesGoldenFile('inspector.padding_debugPaint.png'),
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
      );

      // The bounds for this box crop its rendered content.
      await expectLater(
        service.screenshot(
          find.byKey(sizedBoxKey).evaluate().single,
          width: 300.0,
          height: 300.0,
          debugPaint: true,
        ),
2547
        matchesGoldenFile('inspector.sizedBox_debugPaint.png'),
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
      );

      // Verify that setting a margin includes the previously cropped content.
      await expectLater(
        service.screenshot(
          find.byKey(sizedBoxKey).evaluate().single,
          width: 300.0,
          height: 300.0,
          margin: 50.0,
          debugPaint: true,
        ),
2559
        matchesGoldenFile('inspector.sizedBox_debugPaint_margin.png'),
2560
      );
2561
    });
2562

2563
    test('ext.flutter.inspector.structuredErrors', () async {
2564
      List<Map<Object, Object?>> flutterErrorEvents = service.getEventsDispatched('Flutter.Error');
2565 2566
      expect(flutterErrorEvents, isEmpty);

2567
      final FlutterExceptionHandler oldHandler = FlutterError.presentError;
2568 2569 2570

      try {
        // Enable structured errors.
2571 2572 2573 2574
        expect(
          await service.testBoolExtension('structuredErrors', <String, String>{'enabled': 'true'}),
          equals('true'),
        );
2575 2576

        // Create an error.
2577
        FlutterError.reportError(FlutterErrorDetails(
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
          library: 'rendering library',
          context: ErrorDescription('during layout'),
          exception: StackTrace.current,
        ));

        // Validate that we received an error.
        flutterErrorEvents = service.getEventsDispatched('Flutter.Error');
        expect(flutterErrorEvents, hasLength(1));

        // Validate the error contents.
2588
        Map<Object, Object?> error = flutterErrorEvents.first;
2589 2590 2591 2592 2593
        expect(error['description'], 'Exception caught by rendering library');
        expect(error['children'], isEmpty);

        // Validate that we received an error count.
        expect(error['errorsSinceReload'], 0);
2594
        expect(
2595 2596 2597
          error['renderedErrorText'],
          startsWith('══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞════════════'),
        );
2598 2599

        // Send a second error.
2600
        FlutterError.reportError(FlutterErrorDetails(
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
          library: 'rendering library',
          context: ErrorDescription('also during layout'),
          exception: StackTrace.current,
        ));

        // Validate that the error count increased.
        flutterErrorEvents = service.getEventsDispatched('Flutter.Error');
        expect(flutterErrorEvents, hasLength(2));
        error = flutterErrorEvents.last;
        expect(error['errorsSinceReload'], 1);
2611
        expect(error['renderedErrorText'], startsWith('Another exception was thrown:'));
2612

2613
        // Reloads the app.
2614
        final FlutterExceptionHandler? oldHandler = FlutterError.onError;
2615
        final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as TestWidgetsFlutterBinding;
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
        // We need the runTest to setup the fake async in the test binding.
        await binding.runTest(() async {
          binding.reassembleApplication();
          await binding.pump();
        }, () { });
        // The run test overrides the flutter error handler, so we should
        // restore it back for the structure error to continue working.
        FlutterError.onError = oldHandler;
        // Cleans up the fake async so it does not bleed into next test.
        binding.postTest();
2626 2627

        // Send another error.
2628
        FlutterError.reportError(FlutterErrorDetails(
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
          library: 'rendering library',
          context: ErrorDescription('during layout'),
          exception: StackTrace.current,
        ));

        // And, validate that the error count has been reset.
        flutterErrorEvents = service.getEventsDispatched('Flutter.Error');
        expect(flutterErrorEvents, hasLength(3));
        error = flutterErrorEvents.last;
        expect(error['errorsSinceReload'], 0);
      } finally {
2640
        FlutterError.presentError = oldHandler;
2641 2642 2643
      }
    });

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
    testWidgets('Screenshot of composited transforms - only offsets', (WidgetTester tester) async {
      // Composited transforms are challenging to take screenshots of as the
      // LeaderLayer and FollowerLayer classes used by CompositedTransformTarget
      // and CompositedTransformFollower depend on traversing ancestors of the
      // layer tree and mutating a [LayerLink] object when attaching layers to
      // the tree so that the FollowerLayer knows about the LeaderLayer.
      // 1. Finding the correct position for the follower layers requires
      // traversing the ancestors of the follow layer to find a common ancestor
      // with the leader layer.
      // 2. Creating a LeaderLayer and attaching it to a layer tree has side
      // effects as the leader layer will attempt to modify the mutable
      // LeaderLayer object shared by the LeaderLayer and FollowerLayer.
      // These tests verify that screenshots can still be taken and look correct
      // when the leader and follower layer are both in the screenshots and when
      // only the leader or follower layer is in the screenshot.
2659 2660 2661 2662 2663
      final LayerLink link = LayerLink();
      final GlobalKey key = GlobalKey();
      final GlobalKey mainStackKey = GlobalKey();
      final GlobalKey transformTargetParent = GlobalKey();
      final GlobalKey stackWithTransformFollower = GlobalKey();
2664 2665

      await tester.pumpWidget(
2666
        Directionality(
2667
          textDirection: TextDirection.ltr,
2668 2669
          child: RepaintBoundary(
            child: Stack(
2670 2671
              key: mainStackKey,
              children: <Widget>[
2672
                Stack(
2673 2674
                  key: transformTargetParent,
                  children: <Widget>[
2675
                    Positioned(
2676 2677
                      left: 123.0,
                      top: 456.0,
2678
                      child: CompositedTransformTarget(
2679
                        link: link,
2680
                        child: Container(height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)),
2681 2682 2683 2684
                      ),
                    ),
                  ],
                ),
2685
                Positioned(
2686 2687
                  left: 787.0,
                  top: 343.0,
2688
                  child: Stack(
2689 2690 2691 2692
                    key: stackWithTransformFollower,
                    children: <Widget>[
                      // Container so we can see how the follower layer was
                      // transformed relative to its initial location.
2693 2694
                      Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)),
                      CompositedTransformFollower(
2695
                        link: link,
2696
                        child: Container(key: key, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)),
2697 2698 2699 2700 2701 2702 2703 2704 2705
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
2706
      final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
2707 2708 2709 2710
      expect(box.localToGlobal(Offset.zero), const Offset(123.0, 456.0));

      await expectLater(
        find.byKey(mainStackKey),
2711
        matchesGoldenFile('inspector.composited_transform.only_offsets.png'),
2712 2713 2714 2715 2716 2717 2718 2719
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformFollower).evaluate().first,
          width: 5000.0,
          height: 500.0,
        ),
2720
        matchesGoldenFile('inspector.composited_transform.only_offsets_follower.png'),
2721 2722 2723 2724
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(find.byType(Stack).evaluate().first, width: 300.0, height: 300.0),
2725
        matchesGoldenFile('inspector.composited_transform.only_offsets_small.png'),
2726 2727 2728 2729 2730 2731 2732 2733
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(transformTargetParent).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
2734
        matchesGoldenFile('inspector.composited_transform.only_offsets_target.png'),
2735
      );
2736
    });
2737 2738

    testWidgets('Screenshot composited transforms - with rotations', (WidgetTester tester) async {
2739 2740 2741 2742 2743 2744 2745 2746
      final LayerLink link = LayerLink();
      final GlobalKey key1 = GlobalKey();
      final GlobalKey key2 = GlobalKey();
      final GlobalKey rotate1 = GlobalKey();
      final GlobalKey rotate2 = GlobalKey();
      final GlobalKey mainStackKey = GlobalKey();
      final GlobalKey stackWithTransformTarget = GlobalKey();
      final GlobalKey stackWithTransformFollower = GlobalKey();
2747 2748

      await tester.pumpWidget(
2749
        Directionality(
2750
          textDirection: TextDirection.ltr,
2751
          child: Stack(
2752 2753
            key: mainStackKey,
            children: <Widget>[
2754
              Stack(
2755 2756
                key: stackWithTransformTarget,
                children: <Widget>[
2757
                  Positioned(
2758 2759
                    top: 123.0,
                    left: 456.0,
2760
                    child: Transform.rotate(
2761 2762
                      key: rotate1,
                      angle: 1.0, // radians
2763
                      child: CompositedTransformTarget(
2764
                        link: link,
2765
                        child: Container(key: key1, height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)),
2766 2767 2768 2769 2770
                      ),
                    ),
                  ),
                ],
              ),
2771
              Positioned(
2772 2773
                top: 487.0,
                left: 243.0,
2774
                child: Stack(
2775 2776
                  key: stackWithTransformFollower,
                  children: <Widget>[
2777 2778
                    Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)),
                    Transform.rotate(
2779 2780
                      key: rotate2,
                      angle: -0.3, // radians
2781
                      child: CompositedTransformFollower(
2782
                        link: link,
2783
                        child: Container(key: key2, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)),
2784 2785 2786 2787 2788 2789 2790 2791 2792
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
2793 2794
      final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
      final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
      // Snapshot the positions of the two relevant boxes to ensure that taking
      // screenshots doesn't impact their positions.
      final Offset position1 = box1.localToGlobal(Offset.zero);
      final Offset position2 = box2.localToGlobal(Offset.zero);
      expect(position1.dx, moreOrLessEquals(position2.dx));
      expect(position1.dy, moreOrLessEquals(position2.dy));

      // Image of the full scene to use as reference to help validate that the
      // screenshots of specific subtrees are reasonable.
      await expectLater(
        find.byKey(mainStackKey),
2806
        matchesGoldenFile('inspector.composited_transform.with_rotations.png'),
2807 2808 2809 2810 2811 2812 2813 2814
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(mainStackKey).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
2815
        matchesGoldenFile('inspector.composited_transform.with_rotations_small.png'),
2816 2817 2818 2819 2820 2821 2822 2823
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformTarget).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
2824
        matchesGoldenFile('inspector.composited_transform.with_rotations_target.png'),
2825 2826 2827 2828 2829 2830 2831 2832
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformFollower).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
2833
        matchesGoldenFile('inspector.composited_transform.with_rotations_follower.png'),
2834 2835 2836 2837
      );

      // Make sure taking screenshots hasn't modified the positions of the
      // TransformTarget or TransformFollower layers.
2838 2839
      expect(identical(key1.currentContext!.findRenderObject(), box1), isTrue);
      expect(identical(key2.currentContext!.findRenderObject(), box2), isTrue);
2840 2841
      expect(box1.localToGlobal(Offset.zero), equals(position1));
      expect(box2.localToGlobal(Offset.zero), equals(position2));
2842
    });
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860

    testWidgets('getChildrenDetailsSubtree', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          title: 'Hello, World',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Hello, World'),
            ),
            body: const Center(
              child: Text('Hello, World!'),
            ),
          ),
        ),
      );
2861
      service.setSelection(find.text('Hello, World!').evaluate().first, 'my-group');
2862 2863

      // Figure out the pubRootDirectory
2864
      final Map<String, Object?> jsonObject = (await service.testExtension(
2865
          'getSelectedWidget',
2866
          <String, String>{'objectGroup': 'my-group'},
2867 2868
      ))! as Map<String, Object?>;
      final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
2869
      expect(creationLocation, isNotNull);
2870
      final String file = creationLocation['file']! as String;
2871 2872 2873
      expect(file, endsWith('widget_inspector_test.dart'));
      final List<String> segments = Uri.parse(file).pathSegments;
      // Strip a couple subdirectories away to generate a plausible pub rootdirectory.
2874
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
2875 2876 2877
      service.setPubRootDirectories(<String>[pubRootTest]);

      final String summary = service.getRootWidgetSummaryTree('foo1');
2878
      // ignore: avoid_dynamic_calls
2879 2880 2881
      final List<Object?> childrenOfRoot = json.decode(summary)['children'] as List<Object?>;
      final List<Object?> childrenOfMaterialApp = (childrenOfRoot.first! as Map<String, Object?>)['children']! as List<Object?>;
      final Map<String, Object?> scaffold = childrenOfMaterialApp.first! as Map<String, Object?>;
2882
      expect(scaffold['description'], 'Scaffold');
2883
      final String objectId = scaffold['objectId']! as String;
2884
      final String details = service.getDetailsSubtree(objectId, 'foo2');
2885
      // ignore: avoid_dynamic_calls
2886
      final List<Object?> detailedChildren = json.decode(details)['children'] as List<Object?>;
2887

2888 2889 2890
      final List<Map<String, Object?>> appBars = <Map<String, Object?>>[];
      void visitChildren(List<Object?> children) {
        for (final Map<String, Object?> child in children.cast<Map<String, Object?>>()) {
2891 2892 2893 2894
          if (child['description'] == 'AppBar') {
            appBars.add(child);
          }
          if (child.containsKey('children')) {
2895
            visitChildren(child['children']! as List<Object?>);
2896 2897 2898 2899
          }
        }
      }
      visitChildren(detailedChildren);
2900
      expect(appBars.single, isNot(contains('children')));
2901
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918

    testWidgets('InspectorSerializationDelegate addAdditionalPropertiesCallback', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          title: 'Hello World!',
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Hello World!'),
            ),
            body: Center(
              child: Column(
                children: const <Widget>[
                  Text('Hello World!'),
                ],
              ),
            ),
          ),
2919
        ),
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
      );
      final Finder columnWidgetFinder = find.byType(Column);
      expect(columnWidgetFinder, findsOneWidget);
      final Element columnWidgetElement = columnWidgetFinder
        .evaluate()
        .first;
      final DiagnosticsNode node = columnWidgetElement.toDiagnosticsNode();
      final InspectorSerializationDelegate delegate =
        InspectorSerializationDelegate(
          service: service,
          summaryTree: false,
          includeProperties: true,
          addAdditionalPropertiesCallback:
            (DiagnosticsNode node, InspectorSerializationDelegate delegate) {
              final Map<String, Object> additionalJson = <String, Object>{};
2935
              final Object? value = node.value;
2936
              if (value is Element) {
2937 2938 2939 2940 2941 2942 2943
                final RenderObject? renderObject = value.renderObject;
                if (renderObject != null) {
                  additionalJson['renderObject'] =
                      renderObject.toDiagnosticsNode().toJsonMap(
                        delegate.copyWith(subtreeDepth: 0),
                      );
                }
2944 2945 2946 2947 2948
              }
              additionalJson['callbackExecuted'] = true;
              return additionalJson;
            },
        );
2949
      final Map<String, Object?> json = node.toJsonMap(delegate);
2950 2951
      expect(json['callbackExecuted'], true);
      expect(json.containsKey('renderObject'), true);
2952 2953
      expect(json['renderObject'], isA<Map<String, Object?>>());
      final Map<String, Object?> renderObjectJson = json['renderObject']! as Map<String, Object?>;
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
      expect(renderObjectJson['description'], startsWith('RenderFlex'));

      final InspectorSerializationDelegate emptyDelegate =
        InspectorSerializationDelegate(
          service: service,
          summaryTree: false,
          includeProperties: true,
          addAdditionalPropertiesCallback:
            (DiagnosticsNode node, InspectorSerializationDelegate delegate) {
              return null;
            },
        );
      final InspectorSerializationDelegate defaultDelegate =
        InspectorSerializationDelegate(
          service: service,
          summaryTree: false,
          includeProperties: true,
          addAdditionalPropertiesCallback: null,
        );
      expect(node.toJsonMap(emptyDelegate), node.toJsonMap(defaultDelegate));
    });
2975 2976

    testWidgets('debugIsLocalCreationLocation test', (WidgetTester tester) async {
2977
      setupDefaultPubRootDirectory(service);
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990

      final GlobalKey key = GlobalKey();

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Container(
            padding: const EdgeInsets.all(8),
            child: Text('target', key: key, textDirection: TextDirection.ltr),
          ),
        ),
      );

2991
      final Element element = key.currentContext! as Element;
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002

      expect(debugIsLocalCreationLocation(element), isTrue);
      expect(debugIsLocalCreationLocation(element.widget), isTrue);

      // Padding is inside container
      final Finder paddingFinder = find.byType(Padding);

      final Element paddingElement = paddingFinder.evaluate().first;

      expect(debugIsLocalCreationLocation(paddingElement), isFalse);
      expect(debugIsLocalCreationLocation(paddingElement.widget), isFalse);
3003
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
3004

3005 3006
    test('devToolsInspectorUri test', () {
      activeDevToolsServerAddress = 'http://127.0.0.1:9100';
3007
      connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/';
3008
      expect(
3009
        WidgetInspectorService.instance.devToolsInspectorUri('inspector-0'),
3010 3011 3012
        equals('http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55269%2F798ay5al_FM%3D%2F&inspectorRef=inspector-0'),
      );
    });
3013 3014 3015 3016 3017

    test('DevToolsDeepLinkProperty test', () {
      final DevToolsDeepLinkProperty node =
      DevToolsDeepLinkProperty(
        'description of the deep link',
3018
        'http://the-deeplink/',
3019 3020 3021
      );
      expect(node.toString(), equals('description of the deep link'));
      expect(node.name, isEmpty);
3022
      expect(node.value, equals('http://the-deeplink/'));
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
      expect(
        node.toJsonMap(const DiagnosticsSerializationDelegate()),
        equals(<String, dynamic>{
          'description': 'description of the deep link',
          'type': 'DevToolsDeepLinkProperty',
          'name': '',
          'style': 'singleLine',
          'allowNameWrap': true,
          'missingIfNull': false,
          'propertyType': 'String',
          'defaultLevel': 'info',
3034
          'value': 'http://the-deeplink/',
3035 3036 3037
        }),
      );
    });
3038
  }
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048

  static void setupDefaultPubRootDirectory(TestWidgetInspectorService service) {
    final Map<String, Object?> jsonObject = const SizedBox().toDiagnosticsNode().toJsonMap(InspectorSerializationDelegate(service: service));
    final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
    expect(creationLocation, isNotNull);
    final String file = creationLocation['file']! as String;
    expect(file, endsWith('widget_inspector_test.dart'));
    final List<String> segments = Uri
        .parse(file)
        .pathSegments;
3049
    final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
3050 3051 3052 3053 3054

    // Strip a couple subdirectories away to generate a plausible pub root
    // directory.
    service.setPubRootDirectories(<String>[pubRootTest]);
  }
3055
}
3056

3057
void _addToKnownLocationsMap({
3058
  required Map<int, _CreationLocation> knownLocations,
3059
  required Map<String, Map<String, List<Object?>>> newLocations,
3060
}) {
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
  newLocations.forEach((String file, Map<String, List<Object?>> entries) {
    final List<int> ids = entries['ids']!.cast<int>();
    final List<int> lines = entries['lines']!.cast<int>();
    final List<int> columns = entries['columns']!.cast<int>();
    final List<String> names = entries['names']!.cast<String>();

    for (int i = 0; i < ids.length; i++) {
      final int id = ids[i];
      knownLocations[id] = _CreationLocation(
        id: id,
        file: file,
        line: lines[i],
        column: columns[i],
        name: names[i],
      );
3076 3077 3078
    }
  });
}