widget_inspector_test.dart 206 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 6 7
// reduced-test-set:
//   This file is run as part of a reduced test set in CI on Mac and Windows
//   machines.
8
@Tags(<String>['reduced-test-set'])
9
@TestOn('!chrome')
10
library;
11

12
import 'dart:convert';
13
import 'dart:math';
14
import 'dart:ui' as ui;
15

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

23 24
import 'widget_inspector_test_utils.dart';

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

28
class ClockDemo extends StatelessWidget {
29
  const ClockDemo({ super.key });
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

  @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),
        ],
      ),
    );
  }

50
  Widget makeClock(String label, int utcOffset) {
51 52 53 54 55 56 57 58 59 60 61 62
    return Stack(
      children: <Widget>[
        const Icon(Icons.watch),
        Text(label),
        ClockText(utcOffset: utcOffset),
      ],
    );
  }
}

class ClockText extends StatefulWidget {
  const ClockText({
63
    super.key,
64
    this.utcOffset = 0,
65
  });
66

67
  final int utcOffset;
68 69

  @override
70
  State<ClockText> createState() => _ClockTextState();
71 72 73
}

class _ClockTextState extends State<ClockText> {
74
  DateTime? currentTime = DateTime.now();
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

  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(
94
      currentTime!
95 96 97 98 99 100 101 102 103 104
          .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.

105 106 107 108 109 110 111 112
// 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.
113
  CyclicDiagnostic? related;
114 115 116 117 118
  final List<DiagnosticsNode> children = <DiagnosticsNode>[];

  final String name;

  @override
119
  String toStringShort() => '${objectRuntimeType(this, 'CyclicDiagnostic')}-$name';
120 121 122 123

  // We have to override toString to avoid the toString call itself triggering a
  // stack overflow.
  @override
124
  String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
125 126 127 128 129 130 131 132 133 134 135 136 137
    return toStringShort();
  }

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

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

138
class _CreationLocation {
139
  _CreationLocation({
140
    required this.id,
141 142 143
    required this.file,
    required this.line,
    required this.column,
144
    required this.name,
145 146
  });

147
  final int id;
148 149 150
  final String file;
  final int line;
  final int column;
151
  String? name;
152 153
}

154 155 156 157 158 159 160
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.
161
      final Paint paint = Paint()
162 163 164 165
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1.0
        ..color = Colors.red;
      {
166 167 168
        final PictureLayer pictureLayer = PictureLayer(Offset.zero & size);
        final ui.PictureRecorder recorder = ui.PictureRecorder();
        final Canvas pictureCanvas = Canvas(recorder);
169 170 171
        pictureCanvas.drawCircle(Offset.zero, 20.0, paint);
        pictureLayer.picture = recorder.endRecording();
        context.addLayer(
172
          OffsetLayer()
173 174 175 176 177 178 179 180 181 182
            ..offset = offset
            ..append(pictureLayer),
        );
      }
      context.canvas.drawLine(
        offset,
        offset.translate(size.width, size.height),
        paint,
      );
      {
183 184 185
        final PictureLayer pictureLayer = PictureLayer(Offset.zero & size);
        final ui.PictureRecorder recorder = ui.PictureRecorder();
        final Canvas pictureCanvas = Canvas(recorder);
186 187 188
        pictureCanvas.drawCircle(const Offset(20.0, 20.0), 20.0, paint);
        pictureLayer.picture = recorder.endRecording();
        context.addLayer(
189
          OffsetLayer()
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
            ..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({
208 209 210
    super.key,
    super.child,
  });
211 212 213

  @override
  RenderRepaintBoundary createRenderObject(BuildContext context) {
214
    return RenderRepaintBoundaryWithDebugPaint();
215 216 217
  }
}

218 219 220 221 222 223 224 225
Widget _applyConstructor(Widget Function() constructor) => constructor();

class _TrivialWidget extends StatelessWidget {
  const _TrivialWidget() : super(key: const Key('singleton'));
  @override
  Widget build(BuildContext context) => const Text('Hello, world!');
}

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

236 237 238 239 240 241 242
extension TextFromString on String {
  @widgetFactory
  Widget text() {
    return Text(this);
  }
}

243
void main() {
244
  _TestWidgetInspectorService.runTests();
245 246
}

247
class _TestWidgetInspectorService extends TestWidgetInspectorService {
248 249
  // These tests need access to protected members of WidgetInspectorService.
  static void runTests() {
250
    final TestWidgetInspectorService service = TestWidgetInspectorService();
251 252
    WidgetInspectorService.instance = service;

253
    tearDown(() async {
254
      service.resetAllState();
255 256 257 258 259 260 261

      if (WidgetInspectorService.instance.isWidgetCreationTracked()) {
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name,
          <String, String>{'enabled': 'false'},
        );
      }
262 263
    });

264 265 266
    testWidgets('WidgetInspector smoke test', (WidgetTester tester) async {
      // This is a smoke test to verify that adding the inspector doesn't crash.
      await tester.pumpWidget(
267
        const Directionality(
268
          textDirection: TextDirection.ltr,
269
          child: Stack(
270
            children: <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
      );

      await tester.pumpWidget(
280
        const Directionality(
281
          textDirection: TextDirection.ltr,
282
          child: WidgetInspector(
283
            selectButtonBuilder: null,
284
            child: Stack(
285
              children: <Widget>[
286 287 288
                Text('a', textDirection: TextDirection.ltr),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
289 290 291 292
              ],
            ),
          ),
        ),
293 294 295 296 297 298 299
      );

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

    testWidgets('WidgetInspector interaction test', (WidgetTester tester) async {
      final List<String> log = <String>[];
300 301 302
      final GlobalKey selectButtonKey = GlobalKey();
      final GlobalKey inspectorKey = GlobalKey();
      final GlobalKey topButtonKey = GlobalKey();
303 304

      Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) {
305
        return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null));
306 307 308
      }
      // State type is private, hence using dynamic.
      dynamic getInspectorState() => inspectorKey.currentState;
309
      String paragraphText(RenderParagraph paragraph) {
310
        final TextSpan textSpan = paragraph.text as TextSpan;
311
        return textSpan.text!;
312
      }
313 314

      await tester.pumpWidget(
315
        Directionality(
316
          textDirection: TextDirection.ltr,
317
          child: WidgetInspector(
318 319
            key: inspectorKey,
            selectButtonBuilder: selectButtonBuilder,
320 321
            child: Material(
              child: ListView(
322
                children: <Widget>[
323
                  ElevatedButton(
324 325 326 327 328 329
                    key: topButtonKey,
                    onPressed: () {
                      log.add('top');
                    },
                    child: const Text('TOP'),
                  ),
330
                  ElevatedButton(
331 332 333 334 335 336
                    onPressed: () {
                      log.add('bottom');
                    },
                    child: const Text('BOTTOM'),
                  ),
                ],
337
              ),
338 339 340 341 342
            ),
          ),
        ),
      );

343
      expect(getInspectorState().selection.current, isNull); // ignore: avoid_dynamic_calls
344
      await tester.tap(find.text('TOP'), warnIfMissed: false);
345 346 347
      await tester.pump();
      // Tap intercepted by the inspector
      expect(log, equals(<String>[]));
348
      // ignore: avoid_dynamic_calls
349
      final InspectorSelection selection = getInspectorState().selection as InspectorSelection;
350 351
      expect(paragraphText(selection.current! as RenderParagraph), equals('TOP'));
      final RenderObject topButton = find.byKey(topButtonKey).evaluate().first.renderObject!;
352
      expect(selection.candidates, contains(topButton));
353 354 355 356 357 358 359 360 361

      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.
362
      // ignore: avoid_dynamic_calls
363
      expect(paragraphText(getInspectorState().selection.current as RenderParagraph), equals('TOP'));
364 365 366 367 368 369

      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.
370
      await tester.tap(find.text('BOTTOM'), warnIfMissed: false);
371 372
      expect(log, equals(<String>[]));
      log.clear();
373
      // ignore: avoid_dynamic_calls
374
      expect(paragraphText(getInspectorState().selection.current as RenderParagraph), equals('BOTTOM'));
375 376 377 378
    });

    testWidgets('WidgetInspector non-invertible transform regression test', (WidgetTester tester) async {
      await tester.pumpWidget(
379
        Directionality(
380
          textDirection: TextDirection.ltr,
381
          child: WidgetInspector(
382
            selectButtonBuilder: null,
383 384
            child: Transform(
              transform: Matrix4.identity()..scale(0.0),
385 386
              child: const Stack(
                children: <Widget>[
387 388 389
                  Text('a', textDirection: TextDirection.ltr),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
390 391 392
                ],
              ),
            ),
393
          ),
394
        ),
395 396
      );

397
      await tester.tap(find.byType(Transform), warnIfMissed: false);
398

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

402
    testWidgets('WidgetInspector scroll test', (WidgetTester tester) async {
403 404 405
      final Key childKey = UniqueKey();
      final GlobalKey selectButtonKey = GlobalKey();
      final GlobalKey inspectorKey = GlobalKey();
406

407
      Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) {
408
        return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null));
409 410 411 412 413
      }
      // State type is private, hence using dynamic.
      dynamic getInspectorState() => inspectorKey.currentState;

      await tester.pumpWidget(
414
        Directionality(
415
          textDirection: TextDirection.ltr,
416
          child: WidgetInspector(
417 418
            key: inspectorKey,
            selectButtonBuilder: selectButtonBuilder,
419
            child: ListView(
420
              dragStartBehavior: DragStartBehavior.down,
421
              children: <Widget>[
422
                Container(
423 424 425 426 427 428 429 430 431
                  key: childKey,
                  height: 5000.0,
                ),
              ],
            ),
          ),
        ),
      );
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
432

433
      await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false);
434
      await tester.pump();
435

436 437
      // Fling does nothing as are in inspect mode.
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0));
438

439
      await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false);
440
      await tester.pump();
441

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

445
      await tester.tap(find.byType(ListView), warnIfMissed: false);
446
      await tester.pump();
447
      expect(getInspectorState().selection.current, isNotNull); // ignore: avoid_dynamic_calls
448

449 450 451
      // 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();
452

453
      expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-200.0));
454

455 456 457 458
      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));
459
    });
460 461 462 463 464

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

      await tester.pumpWidget(
465
        Directionality(
466
          textDirection: TextDirection.ltr,
467
          child: WidgetInspector(
468
            selectButtonBuilder: null,
469
            child: GestureDetector(
470 471 472 473 474 475
              onLongPress: () {
                expect(didLongPress, isFalse);
                didLongPress = true;
              },
              child: const Text('target', textDirection: TextDirection.ltr),
            ),
476
          ),
477
        ),
478 479
      );

480
      await tester.longPress(find.text('target'), warnIfMissed: false);
481 482 483 484 485
      // The inspector will swallow the long press.
      expect(didLongPress, isFalse);
    });

    testWidgets('WidgetInspector offstage', (WidgetTester tester) async {
486 487
      final GlobalKey inspectorKey = GlobalKey();
      final GlobalKey clickTarget = GlobalKey();
488

489
      Widget createSubtree({ double? width, Key? key }) {
490
        return Stack(
491
          children: <Widget>[
492
            Positioned(
493 494 495 496 497
              key: key,
              left: 0.0,
              top: 0.0,
              width: width,
              height: 100.0,
498
              child: Text(width.toString(), textDirection: TextDirection.ltr),
499 500 501 502 503
            ),
          ],
        );
      }
      await tester.pumpWidget(
504
        Directionality(
505
          textDirection: TextDirection.ltr,
506
          child: WidgetInspector(
507 508
            key: inspectorKey,
            selectButtonBuilder: null,
509
            child: Overlay(
510
              initialEntries: <OverlayEntry>[
511
                OverlayEntry(
512 513 514
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 94.0),
                ),
515
                OverlayEntry(
516 517 518 519
                  opaque: true,
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 95.0),
                ),
520
                OverlayEntry(
521 522 523 524 525
                  maintainState: true,
                  builder: (BuildContext _) => createSubtree(width: 96.0, key: clickTarget),
                ),
              ],
            ),
526
          ),
527
        ),
528
      );
529

530
      await tester.longPress(find.byKey(clickTarget), warnIfMissed: false);
531 532 533 534
      // 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.
535
      // ignore: avoid_dynamic_calls
536 537 538 539
      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.
540
      // ignore: avoid_dynamic_calls
541 542 543
      expect(inspectorState.selection.candidates.where((RenderObject object) => object is RenderParagraph).length, equals(2));
    });

544 545 546 547 548 549 550 551 552 553 554 555
    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,
556
          child: ColoredBox(
557 558 559 560 561 562 563
            color: Colors.grey,
            child: Transform(
              transform: mainTransform,
              child: Directionality(
                textDirection: TextDirection.ltr,
                child: WidgetInspector(
                  selectButtonBuilder: null,
564
                  child: ColoredBox(
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                    color: Colors.white,
                    child: Center(
                      child: Container(
                        key: childKey,
                        height: 100.0,
                        width: 50.0,
                        color: Colors.red,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      );

582
      await tester.tap(find.byKey(childKey), warnIfMissed: false);
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
      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) {
606
          return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null));
607 608 609 610 611 612 613 614
        };
      }

      // 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;
615
        return textSpan.text!;
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
      }

      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'),
                  ),
                ),
              ),
            ],
          ),
        ),
      );

648
      // ignore: avoid_dynamic_calls
649 650
      final InspectorSelection selection = getInspectorState().selection as InspectorSelection;
      // The selection is static, so it may be initialized from previous tests.
651
      selection.clear();
652

653
      await tester.tap(find.text('Child 1'), warnIfMissed: false);
654
      await tester.pump();
655
      expect(paragraphText(selection.current! as RenderParagraph), equals('Child 1'));
656

657
      await tester.tap(find.text('Child 2'), warnIfMissed: false);
658
      await tester.pump();
659
      expect(paragraphText(selection.current! as RenderParagraph), equals('Child 2'));
660 661
    });

662 663 664 665 666 667 668 669
    test('WidgetInspectorService null id', () {
      service.disposeAllGroups();
      expect(service.toObject(null), isNull);
      expect(service.toId(null, 'test-group'), isNull);
    });

    test('WidgetInspectorService dispose group', () {
      service.disposeAllGroups();
670
      final Object a = Object();
671 672 673
      const String group1 = 'group-1';
      const String group2 = 'group-2';
      const String group3 = 'group-3';
674
      final String? aId = service.toId(a, group1);
675 676 677 678 679 680 681 682 683 684 685
      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();
686 687
      final Object a = Object();
      final Object b = Object();
688 689
      const String group1 = 'group-1';
      const String group2 = 'group-2';
690 691
      final String? aId = service.toId(a, group1);
      final String? bId = service.toId(b, group1);
692 693 694 695 696 697 698 699 700 701 702
      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';
703
      const Text widget = Text('a', textDirection: TextDirection.ltr);
704
      service.disposeAllGroups();
705
      final String id = service.toId(widget, group)!;
706 707
      expect(service.toObjectForSourceLocation(id), equals(widget));
      final Element element = widget.createElement();
708
      final String elementId = service.toId(element, group)!;
709 710 711 712 713 714 715
      expect(service.toObjectForSourceLocation(elementId), equals(widget));
      expect(element, isNot(equals(widget)));
      service.disposeGroup(group);
      expect(() => service.toObjectForSourceLocation(elementId), throwsFlutterError);
    });

    test('WidgetInspectorService object id test', () {
716 717 718 719
      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);
720 721 722 723 724 725

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

726 727 728 729
      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);
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
      // 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(
749
        const Directionality(
750
          textDirection: TextDirection.ltr,
751
          child: Stack(
752
            children: <Widget>[
753 754 755
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
756 757
            ],
          ),
758
        ),
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
      );
      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));
778
      expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element));
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

      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));
    });

794 795
    testWidgets('WidgetInspectorService defunct selection regression test', (WidgetTester tester) async {
      await tester.pumpWidget(
796
        const Directionality(
797 798
          textDirection: TextDirection.ltr,
          child: Stack(
799
            children: <Widget>[
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 836 837 838 839 840 841 842 843 844 845 846
              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,
            includeProperties: true,
          ),
        ),
        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));
    });

847 848 849 850
    testWidgets('WidgetInspectorService getParentChain', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
851
        const Directionality(
852
          textDirection: TextDirection.ltr,
853
          child: Stack(
854
            children: <Widget>[
855 856 857
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
858 859
            ],
          ),
860
        ),
861 862 863 864
      );

      service.disposeAllGroups();
      final Element elementB = find.text('b').evaluate().first;
865 866
      final String bId = service.toId(elementB, group)!;
      final Object? jsonList = json.decode(service.getParentChain(bId, group));
867
      expect(jsonList, isList);
868
      final List<Object?> chainElements = jsonList! as List<Object?>;
869
      final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList();
870
      // Sanity check that the chain goes back to the root.
871
      expect(expectedChain.first, tester.binding.rootElement);
872 873 874 875

      expect(chainElements.length, equals(expectedChain.length));
      for (int i = 0; i < expectedChain.length; i += 1) {
        expect(chainElements[i], isMap);
876
        final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>;
877 878
        final Element element = expectedChain[i];
        expect(chainNode['node'], isMap);
879
        final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>;
880 881
        expect(service.toObject(jsonNode['valueId']! as String), equals(element));
        expect(service.toObject(jsonNode['objectId']! as String), isA<DiagnosticsNode>());
882 883

        expect(chainNode['children'], isList);
884
        final List<Object?> jsonChildren = chainNode['children']! as List<Object?>;
885 886 887 888 889 890 891 892 893 894
        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);
895
          final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>;
896 897
          expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j]));
          expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
898 899 900 901 902 903 904 905
        }
      }
    });

    test('WidgetInspectorService getProperties', () {
      final DiagnosticsNode diagnostic = const Text('a', textDirection: TextDirection.ltr).toDiagnosticsNode();
      const String group = 'group';
      service.disposeAllGroups();
906
      final String id = service.toId(diagnostic, group)!;
907
      final List<Object?> propertiesJson = json.decode(service.getProperties(id, group)) as List<Object?>;
908 909 910 911
      final List<DiagnosticsNode> properties = diagnostic.getProperties();
      expect(properties, isNotEmpty);
      expect(propertiesJson.length, equals(properties.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
912
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
913 914
        expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
915 916 917 918 919 920 921
      }
    });

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

      await tester.pumpWidget(
922
        const Directionality(
923
          textDirection: TextDirection.ltr,
924
          child: Stack(
925
            children: <Widget>[
926 927 928
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
929 930 931 932 933 934
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
      service.disposeAllGroups();
935
      final String id = service.toId(diagnostic, group)!;
936
      final List<Object?> propertiesJson = json.decode(service.getChildren(id, group)) as List<Object?>;
937 938 939 940
      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) {
941
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
942 943
        expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
944 945 946 947 948
      }
    });

    testWidgets('WidgetInspectorService creationLocation', (WidgetTester tester) async {
      await tester.pumpWidget(
949
        Directionality(
950
          textDirection: TextDirection.ltr,
951
          child: Stack(
952
            children: <Widget>[
953 954 955
              const Text('a'),
              const Text('b', textDirection: TextDirection.ltr),
              'c'.text(),
956 957 958 959 960 961
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;
962
      final Element elementC = find.text('c').evaluate().first;
963 964

      service.disposeAllGroups();
965
      service.resetPubRootDirectories();
966
      service.setSelection(elementA, 'my-group');
967 968
      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?>;
969
      expect(creationLocationA, isNotNull);
970 971 972
      final String fileA = creationLocationA['file']! as String;
      final int lineA = creationLocationA['line']! as int;
      final int columnA = creationLocationA['column']! as int;
973 974
      final String nameA = creationLocationA['name']! as String;
      expect(nameA, equals('Text'));
975 976

      service.setSelection(elementB, 'my-group');
977 978
      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?>;
979
      expect(creationLocationB, isNotNull);
980 981 982
      final String fileB = creationLocationB['file']! as String;
      final int lineB = creationLocationB['line']! as int;
      final int columnB = creationLocationB['column']! as int;
983 984
      final String? nameB = creationLocationB['name'] as String?;
      expect(nameB, equals('Text'));
985 986 987 988 989 990 991 992 993 994 995

      service.setSelection(elementC, 'my-group');
      final Map<String, Object?> jsonC = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>;
      final Map<String, Object?> creationLocationC = jsonC['creationLocation']! as Map<String, Object?>;
      expect(creationLocationC, isNotNull);
      final String fileC = creationLocationC['file']! as String;
      final int lineC = creationLocationC['line']! as int;
      final int columnC = creationLocationC['column']! as int;
      final String? nameC = creationLocationC['name'] as String?;
      expect(nameC, equals('TextFromString|text'));

996 997
      expect(fileA, endsWith('widget_inspector_test.dart'));
      expect(fileA, equals(fileB));
998
      expect(fileA, equals(fileC));
999 1000 1001
      // We don't hardcode the actual lines the widgets are created on as that
      // would make this test fragile.
      expect(lineA + 1, equals(lineB));
1002
      expect(lineB + 1, equals(lineC));
1003
      // Column numbers are more stable than line numbers.
1004
      expect(columnA, equals(21));
1005
      expect(columnA, equals(columnB));
1006
      expect(columnC, equals(19));
1007
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1008

1009 1010 1011
  testWidgets('WidgetInspectorService setSelection notifiers for an Element',
    (WidgetTester tester) async {
      await tester.pumpWidget(
1012
        const Directionality(
1013 1014
          textDirection: TextDirection.ltr,
          child: Stack(
1015
            children: <Widget>[
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service.disposeAllGroups();

      setupDefaultPubRootDirectory(service);

      // Select the widget
      service.setSelection(elementA, 'my-group');

      // ensure that developer.inspect was called on the widget
      final List<Object?> objectsInspected = service.inspectedObjects();
      expect(objectsInspected, equals(<Element>[elementA]));

      // ensure that a navigate event was sent for the element
      final List<Map<Object, Object?>> navigateEventsPosted
        = service.dispatchedEvents('navigate', stream: 'ToolEvent',);
      expect(navigateEventsPosted.length, equals(1));
      final Map<Object,Object?> event = navigateEventsPosted[0];
      final String file = event['fileUri']! as String;
      final int line = event['line']! as int;
      final int column = event['column']! as int;
      expect(file, endsWith('widget_inspector_test.dart'));
      // We don't hardcode the actual lines the widgets are created on as that
      // would make this test fragile.
      expect(line, isNotNull);
      // Column numbers are more stable than line numbers.
      expect(column, equals(15));
    },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );

    testWidgets(
      'WidgetInspectorService setSelection notifiers for a RenderObject',
      (WidgetTester tester) async {
        await tester.pumpWidget(
1058
          const Directionality(
1059 1060
            textDirection: TextDirection.ltr,
            child: Stack(
1061
              children: <Widget>[
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          ),
        );
        final Element elementA = find.text('a').evaluate().first;

        service.disposeAllGroups();

        setupDefaultPubRootDirectory(service);

        // Select the render object for the widget.
        service.setSelection(elementA.renderObject, 'my-group');

        // ensure that developer.inspect was called on the widget
        final List<Object?> objectsInspected = service.inspectedObjects();
        expect(objectsInspected, equals(<RenderObject?>[elementA.renderObject]));

        // ensure that a navigate event was sent for the renderObject
        final List<Map<Object, Object?>> navigateEventsPosted
          = service.dispatchedEvents('navigate', stream: 'ToolEvent',);
        expect(navigateEventsPosted.length, equals(1));
        final Map<Object,Object?> event = navigateEventsPosted[0];
        final String file = event['fileUri']! as String;
        final int line = event['line']! as int;
        final int column = event['column']! as int;
        expect(file, endsWith('widget_inspector_test.dart'));
        // We don't hardcode the actual lines the widgets are created on as that
        // would make this test fragile.
        expect(line, isNotNull);
        // Column numbers are more stable than line numbers.
        expect(column, equals(17));
      },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );

    testWidgets(
      'WidgetInspector selectButton inspection for tap',
      (WidgetTester tester) async {
        final GlobalKey selectButtonKey = GlobalKey();
        final GlobalKey inspectorKey = GlobalKey();
        setupDefaultPubRootDirectory(service);

        Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) {
          return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null));
        }

        await tester.pumpWidget(
          Directionality(
            textDirection: TextDirection.ltr,
            child: WidgetInspector(
              key: inspectorKey,
              selectButtonBuilder: selectButtonBuilder,
              child: const Text('Child 1'),
            ),
          ),
        );
        final Finder child = find.text('Child 1');
        final Element childElement = child.evaluate().first;

        await tester.tap(child, warnIfMissed: false);

        await tester.pump();

        // ensure that developer.inspect was called on the widget
        final List<Object?> objectsInspected = service.inspectedObjects();
        expect(objectsInspected, equals(<RenderObject?>[childElement.renderObject]));

        // ensure that a navigate event was sent for the renderObject
        final List<Map<Object, Object?>> navigateEventsPosted
          = service.dispatchedEvents('navigate', stream: 'ToolEvent',);
        expect(navigateEventsPosted.length, equals(1));
        final Map<Object,Object?> event = navigateEventsPosted[0];
        final String file = event['fileUri']! as String;
        final int line = event['line']! as int;
        final int column = event['column']! as int;
        expect(file, endsWith('widget_inspector_test.dart'));
        // We don't hardcode the actual lines the widgets are created on as that
        // would make this test fragile.
        expect(line, isNotNull);
        // Column numbers are more stable than line numbers.
        expect(column, equals(28));
      },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked() // [intended] Test requires --track-widget-creation flag.
    );

1150 1151 1152
    testWidgets('test transformDebugCreator will re-order if after stack trace', (WidgetTester tester) async {
      final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked();
      await tester.pumpWidget(
1153
        const Directionality(
1154 1155
          textDirection: TextDirection.ltr,
          child: Stack(
1156
            children: <Widget>[
1157 1158 1159 1160 1161 1162 1163 1164
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
1165
      service.setSelection(elementA, 'my-group');
1166
      late String pubRootTest;
1167
      if (widgetTracked) {
1168
        final Map<String, Object?> jsonObject = json.decode(
1169 1170
          service.getSelectedWidget(null, 'my-group'),
        ) as Map<String, Object?>;
1171
        final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1172
        expect(creationLocation, isNotNull);
1173
        final String fileA = creationLocation['file']! as String;
1174 1175 1176 1177 1178 1179 1180
        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.
1181
        pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1182 1183
        service.resetPubRootDirectories();
        service.addPubRootDirectories(<String>[pubRootTest]);
1184 1185 1186 1187 1188 1189 1190
      }
      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)));

1191
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1192 1193 1194 1195 1196 1197 1198 1199
      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);
1200
        final DiagnosticsBlock node = nodes[2] as DiagnosticsBlock;
1201 1202
        final List<DiagnosticsNode> children = node.getChildren();
        expect(children.length, 1);
1203
        final ErrorDescription child = children[0] as ErrorDescription;
1204
        expect(child.valueToString(), contains(Uri.parse(pubRootTest).path));
1205 1206
      } else {
        expect(nodes[2].runtimeType, ErrorDescription);
1207
        final ErrorDescription node = nodes[2] as ErrorDescription;
1208 1209 1210 1211 1212 1213 1214 1215 1216
        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(
1217
        const Directionality(
1218 1219
          textDirection: TextDirection.ltr,
          child: Stack(
1220
            children: <Widget>[
1221 1222 1223 1224 1225 1226 1227 1228
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;
1229
      late String pubRootTest;
1230
      if (widgetTracked) {
1231
        final Map<String, Object?> jsonObject = json.decode(
1232 1233
          service.getSelectedWidget(null, 'my-group'),
        ) as Map<String, Object?>;
1234
        final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
1235
        expect(creationLocation, isNotNull);
1236
        final String fileA = creationLocation['file']! as String;
1237 1238 1239 1240 1241 1242 1243
        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.
1244
        pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
1245 1246
        service.resetPubRootDirectories();
        service.addPubRootDirectories(<String>[pubRootTest]);
1247 1248 1249 1250 1251 1252 1253
      }
      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));

1254
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1255 1256 1257 1258 1259 1260
      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);
1261
        final DiagnosticsBlock node = nodes[1] as DiagnosticsBlock;
1262 1263
        final List<DiagnosticsNode> children = node.getChildren();
        expect(children.length, 1);
1264
        final ErrorDescription child = children[0] as ErrorDescription;
1265
        expect(child.valueToString(), contains(Uri.parse(pubRootTest).path));
1266 1267
      } else {
        expect(nodes[1].runtimeType, ErrorDescription);
1268
        final ErrorDescription node = nodes[1] as ErrorDescription;
1269 1270 1271 1272 1273 1274
        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);
1275
    }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag.
1276

1277 1278 1279 1280
    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=/';

1281 1282
      setupDefaultPubRootDirectory(service);

1283
      await tester.pumpWidget(
1284
        const Directionality(
1285 1286
          textDirection: TextDirection.ltr,
          child: Stack(
1287
            children: <Widget>[
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
              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'));

1302
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1303 1304 1305 1306 1307 1308 1309
      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);
1310
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
1311 1312 1313 1314

    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=/';
1315
      setupDefaultPubRootDirectory(service);
1316 1317

      await tester.pumpWidget(
1318
        const Directionality(
1319 1320
          textDirection: TextDirection.ltr,
          child: Stack(
1321
            children: <Widget>[
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
              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'));

1336
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1337 1338 1339 1340 1341
      expect(nodes.length, 4);
      expect(nodes[0].runtimeType, ErrorSummary);
      expect(nodes[1].runtimeType, DiagnosticsBlock);
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, StringProperty);
1342
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked());  // [intended] Test requires --track-widget-creation flag.
1343 1344 1345 1346

    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=/';
1347
      setupDefaultPubRootDirectory(service);
1348 1349

      await tester.pumpWidget(
1350
        const Directionality(
1351 1352
          textDirection: TextDirection.ltr,
          child: Stack(
1353
            children: <Widget>[
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
              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'));

1368
      final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties));
1369 1370 1371 1372 1373
      expect(nodes.length, 4);
      expect(nodes[0].runtimeType, ErrorSummary);
      expect(nodes[1].runtimeType, DiagnosticsBlock);
      expect(nodes[2].runtimeType, ErrorSpacer);
      expect(nodes[3].runtimeType, StringProperty);
1374
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked());  // [intended] Test requires --track-widget-creation flag.
1375

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    // TODO(CoderDake): Clean up pubRootDirectory tests https://github.com/flutter/flutter/issues/107186
    group('pubRootDirectory', () {
      const String directoryA = '/a/b/c';
      const String directoryB = '/d/e/f';
      const String directoryC = '/g/h/i';

      setUp(() {
        service.resetPubRootDirectories();
      });

      group('addPubRootDirectories', () {
1387
        test('can add multiple directories', () async {
1388 1389 1390
          const List<String> directories = <String>[directoryA, directoryB];
          service.addPubRootDirectories(directories);

1391 1392
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, unorderedEquals(directories));
1393 1394
        });

Lioness100's avatar
Lioness100 committed
1395
        test('can add multiple directories separately', () async {
1396 1397 1398 1399
          service.addPubRootDirectories(<String>[directoryA]);
          service.addPubRootDirectories(<String>[directoryB]);
          service.addPubRootDirectories(<String>[]);

1400 1401
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, unorderedEquals(<String>[
1402 1403 1404 1405 1406
            directoryA,
            directoryB,
          ]));
        });

1407
        test('handles duplicates', () async {
1408 1409 1410 1411 1412 1413 1414 1415
          const List<String> directories = <String>[
            directoryA,
            'file://$directoryA',
            directoryB,
            directoryB
          ];
          service.addPubRootDirectories(directories);

1416 1417
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, unorderedEquals(<String>[
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
            directoryA,
            directoryB,
          ]));
        });
      });

      group('removePubRootDirectories', () {
        setUp(() {
          service.resetPubRootDirectories();
          service.addPubRootDirectories(<String>[directoryA, directoryB, directoryC]);
        });

1430
        test('removes multiple directories', () async {
1431 1432
          service.removePubRootDirectories(<String>[directoryA, directoryB,]);

1433 1434
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, equals(<String>[directoryC]));
1435 1436
        });

Lioness100's avatar
Lioness100 committed
1437
        test('removes multiple directories separately', () async {
1438 1439 1440 1441
          service.removePubRootDirectories(<String>[directoryA]);
          service.removePubRootDirectories(<String>[directoryB]);
          service.removePubRootDirectories(<String>[]);

1442 1443
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, equals(<String>[directoryC]));
1444 1445
        });

1446
        test('handles duplicates', () async {
1447 1448 1449 1450 1451 1452 1453
          service.removePubRootDirectories(<String>[
            'file://$directoryA',
            directoryA,
            directoryB,
            directoryB,
          ]);

1454 1455
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, equals(<String>[directoryC]));
1456 1457
        });

1458
        test("does nothing if the directories doesn't exist ", () async {
1459 1460
          service.removePubRootDirectories(<String>['/x/y/z']);

1461 1462
          final List<String> pubRoots = await service.currentPubRootDirectories;
          expect(pubRoots, unorderedEquals(<String>[
1463 1464 1465 1466 1467 1468 1469 1470
            directoryA,
            directoryB,
            directoryC,
          ]));
        });
      });
    });

1471
    group(
1472 1473 1474
    'WidgetInspectorService',
    () {
      late final String pubRootTest;
1475

1476 1477 1478
      setUpAll(() {
        pubRootTest = generateTestPubRootDirectory(service);
      });
1479

1480 1481 1482 1483
      setUp(() {
        service.disposeAllGroups();
        service.resetPubRootDirectories();
      });
1484

1485
        group('addPubRootDirectories', () {
1486 1487 1488
          testWidgets(
            'does not have createdByLocalProject when there are no pubRootDirectories',
            (WidgetTester tester) async {
1489
              const Widget widget = Directionality(
1490 1491
                textDirection: TextDirection.ltr,
                child: Stack(
1492
                  children: <Widget>[
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              service.setSelection(elementA, 'my-group');

              final Map<String, Object?> jsonObject =
                  json.decode(service.getSelectedWidget(null, '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')));
            },
          );
1515

1516 1517 1518
          testWidgets(
            'has createdByLocalProject when the element is part of the pubRootDirectory',
            (WidgetTester tester) async {
1519
              const Widget widget = Directionality(
1520 1521
                textDirection: TextDirection.ltr,
                child: Stack(
1522
                  children: <Widget>[
1523 1524 1525 1526 1527 1528 1529 1530
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
1531

1532
              service.addPubRootDirectories(<String>[pubRootTest]);
1533

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
              service.setSelection(elementA, 'my-group');
              expect(
                json.decode(service.getSelectedWidget(null, 'my-group')),
                contains('createdByLocalProject'),
              );
            },
          );

          testWidgets(
            'does not have createdByLocalProject when widget package directory is a suffix of a pubRootDirectory',
            (WidgetTester tester) async {
1545
              const Widget widget = Directionality(
1546 1547
                textDirection: TextDirection.ltr,
                child: Stack(
1548
                  children: <Widget>[
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              service.setSelection(elementA, 'my-group');

1559
              service.addPubRootDirectories(<String>['/invalid/$pubRootTest']);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
              expect(
                json.decode(service.getSelectedWidget(null, 'my-group')),
                isNot(contains('createdByLocalProject')),
              );
            },
          );

          testWidgets(
            'has createdByLocalProject when the pubRootDirectory is prefixed with file://',
            (WidgetTester tester) async {
1570
              const Widget widget = Directionality(
1571 1572
                textDirection: TextDirection.ltr,
                child: Stack(
1573
                  children: <Widget>[
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              service.setSelection(elementA, 'my-group');

1584
              service.addPubRootDirectories(<String>['file://$pubRootTest']);
1585 1586 1587 1588 1589 1590 1591 1592
              expect(
                json.decode(service.getSelectedWidget(null, 'my-group')),
                contains('createdByLocalProject'),
              );
            },
          );

          testWidgets(
Lioness100's avatar
Lioness100 committed
1593
            'does not have createdByLocalProject when thePubRootDirectory has a different suffix',
1594
            (WidgetTester tester) async {
1595
              const Widget widget = Directionality(
1596 1597
                textDirection: TextDirection.ltr,
                child: Stack(
1598
                  children: <Widget>[
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              service.setSelection(elementA, 'my-group');

1609
              service.addPubRootDirectories(<String>['$pubRootTest/different']);
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
              expect(
                json.decode(service.getSelectedWidget(null, 'my-group')),
                isNot(contains('createdByLocalProject')),
              );
            },
          );

          testWidgets(
            'has createdByLocalProject even if another pubRootDirectory does not match',
            (WidgetTester tester) async {
1620
              const Widget widget = Directionality(
1621 1622
                textDirection: TextDirection.ltr,
                child: Stack(
1623
                  children: <Widget>[
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              service.setSelection(elementA, 'my-group');

1634
              service.addPubRootDirectories(<String>[
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
                '/invalid/$pubRootTest',
                pubRootTest,
              ]);
              expect(
                json.decode(service.getSelectedWidget(null, 'my-group')),
                contains('createdByLocalProject'),
              );
            },
          );

          testWidgets(
            'widget is part of core framework and is the child of a widget in the package pubRootDirectories',
            (WidgetTester tester) async {
1648
              const Widget widget = Directionality(
1649 1650
                textDirection: TextDirection.ltr,
                child: Stack(
1651
                  children: <Widget>[
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              );
              await tester.pumpWidget(widget);
              final Element elementA = find.text('a').evaluate().first;
              final Element richText = find
                  .descendant(
                    of: find.text('a'),
                    matching: find.byType(RichText),
                  )
                  .evaluate()
                  .first;
              service.setSelection(richText, 'my-group');
1668
              service.addPubRootDirectories(<String>[pubRootTest]);
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688

              final Map<String, Object?> jsonObject =
                  json.decode(service.getSelectedWidget(null, 'my-group'))
                      as Map<String, Object?>;
              expect(jsonObject, isNot(contains('createdByLocalProject')));
              final Map<String, Object?> creationLocation =
                  jsonObject['creationLocation']! as Map<String, Object?>;
              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
              final List<String> pathSegmentsFramework =
                  Uri.parse(creationLocation['file']! as String).pathSegments;
              expect(
                pathSegmentsFramework.join('/'),
                endsWith('/flutter/lib/src/widgets/text.dart'),
              );

              // Strip off /src/widgets/text.dart.
              final String pubRootFramework =
                  '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
1689 1690
              service.resetPubRootDirectories();
              service.addPubRootDirectories(<String>[pubRootFramework]);
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
              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')),
              );

              service
                  .setPubRootDirectories(<String>[pubRootFramework, pubRootTest]);
              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'),
              );
            },
          );
        });
1716 1717 1718 1719 1720 1721 1722 1723 1724

      group('createdByLocalProject', () {
        setUp(() {
          service.resetPubRootDirectories();
        });

        testWidgets(
          'reacts to add and removing pubRootDirectories',
          (WidgetTester tester) async {
1725
            const Widget widget = Directionality(
1726 1727
              textDirection: TextDirection.ltr,
              child: Stack(
1728
                children: <Widget>[
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;

            service.addPubRootDirectories(<String>[
              pubRootTest,
              'file://$pubRootTest',
              '/unrelated/$pubRootTest',
            ]);

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

            service.removePubRootDirectories(<String>[pubRootTest]);

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

        testWidgets(
          'does not match when the package directory does not match',
          (WidgetTester tester) async {
1763
            const Widget widget = Directionality(
1764 1765
              textDirection: TextDirection.ltr,
              child: Stack(
1766
                children: <Widget>[
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            service.addPubRootDirectories(<String>[
              '$pubRootTest/different',
              '/unrelated/$pubRootTest',
            ]);
            expect(
              json.decode(service.getSelectedWidget(null, 'my-group')),
              isNot(contains('createdByLocalProject')),
            );
          },
        );

        testWidgets(
          'has createdByLocalProject when the pubRootDirectory is prefixed with file://',
          (WidgetTester tester) async {
1791
            const Widget widget = Directionality(
1792 1793
              textDirection: TextDirection.ltr,
              child: Stack(
1794
                children: <Widget>[
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

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

        testWidgets(
          'can handle consecutive calls to add',
          (WidgetTester tester) async {
1816
            const Widget widget = Directionality(
1817 1818
              textDirection: TextDirection.ltr,
              child: Stack(
1819
                children: <Widget>[
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            service.addPubRootDirectories(<String>[
              pubRootTest,
            ]);
            service.addPubRootDirectories(<String>[
              '/invalid/$pubRootTest',
            ]);
            expect(
              json.decode(service.getSelectedWidget(null, 'my-group')),
              contains('createdByLocalProject'),
            );
          },
        );
        testWidgets(
          'can handle removing an unrelated pubRootDirectory',
          (WidgetTester tester) async {
1845
            const Widget widget = Directionality(
1846 1847
              textDirection: TextDirection.ltr,
              child: Stack(
1848
                children: <Widget>[
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

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

            service.removePubRootDirectories(<String>[
              '/invalid/$pubRootTest',
            ]);
            expect(
              json.decode(service.getSelectedWidget(null, 'my-group')),
              contains('createdByLocalProject'),
            );
          },
        );

        testWidgets(
          'can handle parent widget being part of a separate package',
          (WidgetTester tester) async {
1881
            const Widget widget = Directionality(
1882 1883
              textDirection: TextDirection.ltr,
              child: Stack(
1884
                children: <Widget>[
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
                  Text('a'),
                  Text('b', textDirection: TextDirection.ltr),
                  Text('c', textDirection: TextDirection.ltr),
                ],
              ),
            );
            await tester.pumpWidget(widget);
            final Element elementA = find.text('a').evaluate().first;
            final Element richText = find
                .descendant(
                  of: find.text('a'),
                  matching: find.byType(RichText),
                )
                .evaluate()
                .first;
            service.setSelection(richText, 'my-group');
            service.addPubRootDirectories(<String>[pubRootTest]);

            final Map<String, Object?> jsonObject =
                json.decode(service.getSelectedWidget(null, 'my-group'))
                    as Map<String, Object?>;
            expect(jsonObject, isNot(contains('createdByLocalProject')));
            final Map<String, Object?> creationLocation =
                jsonObject['creationLocation']! as Map<String, Object?>;
            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
            final List<String> pathSegmentsFramework =
                Uri.parse(creationLocation['file']! as String).pathSegments;
            expect(
              pathSegmentsFramework.join('/'),
              endsWith('/flutter/lib/src/widgets/text.dart'),
            );

            // Strip off /src/widgets/text.dart.
            final String pubRootFramework =
                '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
            service.resetPubRootDirectories();
            service.addPubRootDirectories(<String>[pubRootFramework]);
            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')),
            );

            service.resetPubRootDirectories();
            service
                .addPubRootDirectories(<String>[pubRootFramework, pubRootTest]);
            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'),
            );
          },
        );
      });
    },
    skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
  );
1953 1954

    test('ext.flutter.inspector.disposeGroup', () async {
1955
      final Object a = Object();
1956 1957 1958
      const String group1 = 'group-1';
      const String group2 = 'group-2';
      const String group3 = 'group-3';
1959
      final String? aId = service.toId(a, group1);
1960 1961
      expect(service.toId(a, group2), equals(aId));
      expect(service.toId(a, group3), equals(aId));
1962 1963 1964 1965 1966 1967 1968 1969
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeGroup.name,
        <String, String>{'objectGroup': group1},
      );
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeGroup.name,
        <String, String>{'objectGroup': group2},
      );
1970
      expect(service.toObject(aId), equals(a));
1971 1972 1973 1974
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeGroup.name,
        <String, String>{'objectGroup': group3},
      );
1975 1976 1977 1978
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    test('ext.flutter.inspector.disposeId', () async {
1979 1980
      final Object a = Object();
      final Object b = Object();
1981 1982
      const String group1 = 'group-1';
      const String group2 = 'group-2';
1983 1984
      final String aId = service.toId(a, group1)!;
      final String bId = service.toId(b, group1)!;
1985
      expect(service.toId(a, group2), equals(aId));
1986 1987 1988 1989
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeId.name,
        <String, String>{'arg': bId, 'objectGroup': group1},
      );
1990
      expect(() => service.toObject(bId), throwsFlutterError);
1991 1992 1993 1994
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeId.name,
        <String, String>{'arg': aId, 'objectGroup': group1},
      );
1995
      expect(service.toObject(aId), equals(a));
1996 1997 1998 1999
      await service.testExtension(
        WidgetInspectorServiceExtensions.disposeId.name,
        <String, String>{'arg': aId, 'objectGroup': group2},
      );
2000 2001 2002 2003 2004
      expect(() => service.toObject(aId), throwsFlutterError);
    });

    testWidgets('ext.flutter.inspector.setSelection', (WidgetTester tester) async {
      await tester.pumpWidget(
2005
        const Directionality(
2006
          textDirection: TextDirection.ltr,
2007
          child: Stack(
2008
            children: <Widget>[
2009 2010 2011
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
            ],
          ),
        ),
      );
      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));
2034
      expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element));
2035 2036 2037 2038 2039

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

2040 2041 2042 2043
      await service.testExtension(
        WidgetInspectorServiceExtensions.setSelectionById.name,
        <String, String>{'arg': service.toId(elementA, 'my-group')!, 'objectGroup': 'my-group'},
      );
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
      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(
2057
        const Directionality(
2058
          textDirection: TextDirection.ltr,
2059
          child: Stack(
2060
            children: <Widget>[
2061 2062 2063
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2064 2065
            ],
          ),
2066
        ),
2067 2068 2069
      );

      final Element elementB = find.text('b').evaluate().first;
2070
      final String bId = service.toId(elementB, group)!;
2071 2072 2073 2074
      final Object? jsonList = await service.testExtension(
        WidgetInspectorServiceExtensions.getParentChain.name,
        <String, String>{'arg': bId, 'objectGroup': group},
      );
2075
      expect(jsonList, isList);
2076
      final List<Object?> chainElements = jsonList! as List<Object?>;
2077
      final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList();
2078
      // Sanity check that the chain goes back to the root.
2079
      expect(expectedChain.first, tester.binding.rootElement);
2080 2081 2082 2083

      expect(chainElements.length, equals(expectedChain.length));
      for (int i = 0; i < expectedChain.length; i += 1) {
        expect(chainElements[i], isMap);
2084
        final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>;
2085 2086
        final Element element = expectedChain[i];
        expect(chainNode['node'], isMap);
2087
        final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>;
2088 2089
        expect(service.toObject(jsonNode['valueId']! as String), equals(element));
        expect(service.toObject(jsonNode['objectId']! as String), isA<DiagnosticsNode>());
2090 2091

        expect(chainNode['children'], isList);
2092
        final List<Object?> jsonChildren = chainNode['children']! as List<Object?>;
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
        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);
2103
          final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>;
2104 2105
          expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j]));
          expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
2106
        }
2107
      }
2108 2109 2110 2111 2112
    });

    test('ext.flutter.inspector.getProperties', () async {
      final DiagnosticsNode diagnostic = const Text('a', textDirection: TextDirection.ltr).toDiagnosticsNode();
      const String group = 'group';
2113
      final String id = service.toId(diagnostic, group)!;
2114 2115 2116 2117
      final List<Object?> propertiesJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getProperties.name,
        <String, String>{'arg': id, 'objectGroup': group},
      ))! as List<Object?>;
2118 2119 2120 2121
      final List<DiagnosticsNode> properties = diagnostic.getProperties();
      expect(properties, isNotEmpty);
      expect(propertiesJson.length, equals(properties.length));
      for (int i = 0; i < propertiesJson.length; ++i) {
2122
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
2123 2124
        expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
2125
      }
2126 2127 2128 2129 2130 2131
    });

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

      await tester.pumpWidget(
2132
        const Directionality(
2133
          textDirection: TextDirection.ltr,
2134
          child: Stack(
2135
            children: <Widget>[
2136 2137 2138
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2139 2140
            ],
          ),
2141
        ),
2142 2143
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
2144
      final String id = service.toId(diagnostic, group)!;
2145 2146 2147 2148
      final List<Object?> propertiesJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildren.name,
        <String, String>{'arg': id, 'objectGroup': group},
      ))! as List<Object?>;
2149 2150 2151 2152
      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) {
2153
        final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>;
2154 2155
        expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(propertyJson['objectId']! as String), isA<DiagnosticsNode>());
2156 2157 2158
      }
    });

2159 2160 2161 2162
    testWidgets('ext.flutter.inspector.getChildrenDetailsSubtree', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
2163
        const Directionality(
2164
          textDirection: TextDirection.ltr,
2165
          child: Stack(
2166
            children: <Widget>[
2167 2168 2169
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2170 2171 2172 2173 2174
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
2175
      final String id = service.toId(diagnostic, group)!;
2176 2177 2178 2179
      final List<Object?> childrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name,
        <String, String>{'arg': id, 'objectGroup': group},
      ))! as List<Object?>;
2180 2181 2182 2183
      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) {
2184
        final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>;
2185 2186
        expect(service.toObject(childJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
2187
        final List<Object?> propertiesJson = childJson['properties']! as List<Object?>;
2188
        final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId']! as String)! as DiagnosticsNode;
2189
        final List<DiagnosticsNode> expectedProperties = diagnosticsNode.getProperties();
2190
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
2191
          final Object? property = service.toObject(propertyJson['objectId']! as String);
Dan Field's avatar
Dan Field committed
2192
          expect(property, isA<DiagnosticsNode>());
2193
          expect(expectedProperties, contains(property));
2194 2195 2196 2197 2198 2199 2200 2201
        }
      }
    });

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

      await tester.pumpWidget(
2202
        const Directionality(
2203
          textDirection: TextDirection.ltr,
2204
          child: Stack(
2205
            children: <Widget>[
2206 2207 2208
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2209 2210 2211 2212 2213
            ],
          ),
        ),
      );
      final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode();
2214
      final String id = service.toId(diagnostic, group)!;
2215 2216 2217 2218
      final Map<String, Object?> subtreeJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getDetailsSubtree.name,
        <String, String>{'arg': id, 'objectGroup': group},
      ))! as Map<String, Object?>;
2219
      expect(subtreeJson['objectId'], equals(id));
2220
      final List<Object?> childrenJson = subtreeJson['children']! as List<Object?>;
2221 2222 2223 2224
      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) {
2225
        final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>;
2226 2227
        expect(service.toObject(childJson['valueId']! as String), equals(children[i].value));
        expect(service.toObject(childJson['objectId']! as String), isA<DiagnosticsNode>());
2228 2229
        final List<Object?> propertiesJson = childJson['properties']! as List<Object?>;
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
2230 2231
          expect(propertyJson, isNot(contains('children')));
        }
2232
        final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId']! as String)! as DiagnosticsNode;
2233
        final List<DiagnosticsNode> expectedProperties = diagnosticsNode.getProperties();
2234
        for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) {
2235
          final Object property = service.toObject(propertyJson['objectId']! as String)!;
Dan Field's avatar
Dan Field committed
2236
          expect(property, isA<DiagnosticsNode>());
2237 2238 2239 2240
          expect(expectedProperties, contains(property));
        }
      }

2241
      final Map<String, Object?> deepSubtreeJson = (await service.testExtension(
2242
        WidgetInspectorServiceExtensions.getDetailsSubtree.name,
2243
        <String, String>{'arg': id, 'objectGroup': group, 'subtreeDepth': '3'},
2244 2245 2246 2247 2248
      ))! 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?>>()) {
2249
          expect(propertyJson, contains('children'));
2250 2251 2252 2253
        }
      }
    });

2254 2255 2256 2257 2258 2259 2260 2261 2262
    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();
2263
      final String id = service.toId(diagnostic, group)!;
2264 2265 2266 2267
      final Map<String, Object?> subtreeJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getDetailsSubtree.name,
        <String, String>{'arg': id, 'objectGroup': group},
      ))! as Map<String, Object?>;
2268
      expect(subtreeJson['objectId'], equals(id));
2269
      expect(subtreeJson, contains('children'));
2270
      final List<Object?> propertiesJson = subtreeJson['properties']! as List<Object?>;
2271
      expect(propertiesJson.length, equals(1));
2272
      final Map<String, Object?> relatedProperty = propertiesJson.first! as Map<String, Object?>;
2273 2274
      expect(relatedProperty['name'], equals('related'));
      expect(relatedProperty['description'], equals('CyclicDiagnostic-b'));
2275 2276 2277
      expect(relatedProperty, contains('isDiagnosticableValue'));
      expect(relatedProperty, isNot(contains('children')));
      expect(relatedProperty, contains('properties'));
2278
      final List<Object?> relatedWidgetProperties = relatedProperty['properties']! as List<Object?>;
2279
      expect(relatedWidgetProperties.length, equals(1));
2280
      final Map<String, Object?> nestedRelatedProperty = relatedWidgetProperties.first! as Map<String, Object?>;
2281 2282 2283 2284 2285
      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'));
2286 2287 2288
      expect(nestedRelatedProperty, contains('isDiagnosticableValue'));
      expect(nestedRelatedProperty, isNot(contains('properties')));
      expect(nestedRelatedProperty, isNot(contains('children')));
2289 2290
    });

2291 2292 2293 2294
    testWidgets('ext.flutter.inspector.getRootWidgetSummaryTree', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
2295
        const Directionality(
2296
          textDirection: TextDirection.ltr,
2297
          child: Stack(
2298
            children: <Widget>[
2299 2300 2301
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2302 2303 2304 2305 2306 2307 2308
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service.disposeAllGroups();
2309
      service.resetPubRootDirectories();
2310
      service.setSelection(elementA, 'my-group');
2311 2312 2313 2314
      final Map<String, dynamic> jsonA = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, dynamic>;
2315

2316
      service.resetPubRootDirectories();
2317 2318 2319 2320
      Map<String, Object?> rootJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name,
        <String, String>{'objectGroup': group},
      ))! as Map<String, Object?>;
2321 2322 2323
      // 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.
2324
      final Object? rootWidget = service.toObject(rootJson['valueId']! as String);
2325
      expect(rootWidget, equals(WidgetsBinding.instance.rootElement));
2326
      List<Object?> childrenJson = rootJson['children']! as List<Object?>;
2327 2328 2329
      // There are no summary tree children.
      expect(childrenJson.length, equals(0));

2330
      final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>;
2331
      expect(creationLocation, isNotNull);
2332
      final String testFile = creationLocation['file']! as String;
2333 2334 2335 2336
      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.
2337
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
2338
      service.resetPubRootDirectories();
2339 2340 2341 2342
      await service.testExtension(
        WidgetInspectorServiceExtensions.addPubRootDirectories.name,
        <String, String>{'arg0': pubRootTest},
      );
2343

2344 2345 2346 2347
      rootJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name,
        <String, String>{'objectGroup': group},
      ))! as Map<String, Object?>;
2348
      childrenJson = rootJson['children']! as List<Object?>;
2349 2350
      // The tree of nodes returned contains all widgets created directly by the
      // test.
2351
      childrenJson = rootJson['children']! as List<Object?>;
2352 2353
      expect(childrenJson.length, equals(1));

2354 2355 2356 2357
      List<Object?> alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': rootJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
2358
      expect(alternateChildrenJson.length, equals(1));
2359 2360
      Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>;
      Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>;
2361 2362 2363 2364
      expect(childJson['description'], startsWith('Directionality'));
      expect(alternateChildJson['description'], startsWith('Directionality'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));

2365
      childrenJson = childJson['children']! as List<Object?>;
2366 2367 2368 2369
      alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
2370 2371
      expect(alternateChildrenJson.length, equals(1));
      expect(childrenJson.length, equals(1));
2372 2373
      alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>;
      childJson = childrenJson[0]! as Map<String, Object?>;
2374 2375 2376
      expect(childJson['description'], startsWith('Stack'));
      expect(alternateChildJson['description'], startsWith('Stack'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));
2377
      childrenJson = childJson['children']! as List<Object?>;
2378

2379
      childrenJson = childJson['children']! as List<Object?>;
2380 2381 2382 2383
      alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
2384 2385
      expect(alternateChildrenJson.length, equals(3));
      expect(childrenJson.length, equals(3));
2386 2387
      alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>;
      childJson = childrenJson[2]! as Map<String, Object?>;
2388 2389 2390
      expect(childJson['description'], startsWith('Text'));
      expect(alternateChildJson['description'], startsWith('Text'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));
2391 2392 2393 2394
      alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
2395
      expect(alternateChildrenJson.length , equals(0));
2396
      // Tests are failing when this typo is fixed.
2397
      expect(childJson['chidlren'], isNull);
2398
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
2399

2400 2401 2402 2403
    testWidgets('ext.flutter.inspector.getRootWidgetSummaryTreeWithPreviews', (WidgetTester tester) async {
      const String group = 'test-group';

      await tester.pumpWidget(
2404
        const Directionality(
2405 2406
          textDirection: TextDirection.ltr,
          child: Stack(
2407
            children: <Widget>[
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
            ],
          ),
        ),
      );
      final Element elementA = find.text('a').evaluate().first;

      service
        ..disposeAllGroups()
        ..resetPubRootDirectories()
        ..setSelection(elementA, 'my-group');

      final Map<String, dynamic> jsonA = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, dynamic>;


      final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>;
      expect(creationLocation, isNotNull);
      final String testFile = creationLocation['file']! as String;
      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.
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
      service
        ..resetPubRootDirectories()
        ..addPubRootDirectories(<String>[pubRootTest]);

      final Map<String, Object?> rootJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getRootWidgetSummaryTreeWithPreviews.name,
        <String, String>{'groupName': group},
      ))! as Map<String, Object?>;
      List<Object?> childrenJson = rootJson['children']! as List<Object?>;
      // The tree of nodes returned contains all widgets created directly by the
      // test.
      childrenJson = rootJson['children']! as List<Object?>;
      expect(childrenJson.length, equals(1));

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

      childrenJson = childJson['children']! as List<Object?>;
      alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
      expect(alternateChildrenJson.length, equals(1));
      expect(childrenJson.length, equals(1));
      alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>;
      childJson = childrenJson[0]! as Map<String, Object?>;
      expect(childJson['description'], startsWith('Stack'));
      expect(alternateChildJson['description'], startsWith('Stack'));
      expect(alternateChildJson['valueId'], equals(childJson['valueId']));
      childrenJson = childJson['children']! as List<Object?>;

      childrenJson = childJson['children']! as List<Object?>;
      alternateChildrenJson = (await service.testExtension(
        WidgetInspectorServiceExtensions.getChildrenSummaryTree.name,
        <String, String>{'arg': childJson['objectId']! as String, 'objectGroup': group},
      ))! as List<Object?>;
      expect(alternateChildrenJson.length, equals(3));
      expect(childrenJson.length, equals(3));
      alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>;
      childJson = childrenJson[2]! as Map<String, Object?>;
      expect(childJson['description'], startsWith('Text'));

      // [childJson] contains the 'textPreview' key since the tree was requested
      // with previews [getRootWidgetSummaryTreeWithPreviews].
      expect(childJson['textPreview'], equals('c'));
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.

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

      await tester.pumpWidget(
2495
        const Directionality(
2496
          textDirection: TextDirection.ltr,
2497
          child: Stack(
2498
            children: <Widget>[
2499 2500 2501
              Text('a', textDirection: TextDirection.ltr),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
            ],
          ),
        ),
      );
      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();
2513
      service.resetPubRootDirectories();
2514
      service.setSelection(elementA, 'my-group');
2515 2516 2517 2518
      final Map<String, Object?> jsonA = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, Object?>;
2519 2520
      service.setSelection(richTextDiagnostic.value, 'my-group');

2521
      service.resetPubRootDirectories();
2522 2523 2524 2525
      Map<String, Object?>? summarySelection = await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name,
        <String, String>{'objectGroup': group},
      ) as Map<String, Object?>?;
2526 2527 2528 2529
      // 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);

2530
      final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>;
2531
      expect(creationLocation, isNotNull);
2532
      final String testFile = creationLocation['file']! as String;
2533 2534 2535 2536
      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.
2537
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
2538
      service.resetPubRootDirectories();
2539 2540 2541 2542
      await service.testExtension(
        WidgetInspectorServiceExtensions.addPubRootDirectories.name,
        <String, String>{'arg0': pubRootTest},
      );
2543

2544 2545 2546 2547
      summarySelection = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name,
        <String, String>{'objectGroup': group},
      ))! as Map<String, Object?>;
2548 2549 2550
      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.
2551
      expect(service.toObject(summarySelection['valueId']! as String), elementA);
2552 2553 2554

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

2562 2563
    testWidgets('ext.flutter.inspector creationLocation', (WidgetTester tester) async {
      await tester.pumpWidget(
2564
        const Directionality(
2565
          textDirection: TextDirection.ltr,
2566
          child: Stack(
2567
            children: <Widget>[
2568 2569 2570
              Text('a'),
              Text('b', textDirection: TextDirection.ltr),
              Text('c', textDirection: TextDirection.ltr),
2571 2572
            ],
          ),
2573
        ),
2574 2575 2576 2577 2578
      );
      final Element elementA = find.text('a').evaluate().first;
      final Element elementB = find.text('b').evaluate().first;

      service.disposeAllGroups();
2579
      service.resetPubRootDirectories();
2580
      service.setSelection(elementA, 'my-group');
2581 2582 2583 2584
      final Map<String, Object?> jsonA = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, Object?>;
2585
      final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>;
2586
      expect(creationLocationA, isNotNull);
2587 2588 2589
      final String fileA = creationLocationA['file']! as String;
      final int lineA = creationLocationA['line']! as int;
      final int columnA = creationLocationA['column']! as int;
2590 2591

      service.setSelection(elementB, 'my-group');
2592 2593 2594 2595
      final Map<String, Object?> jsonB = (await service.testExtension(
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, Object?>;
2596
      final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>;
2597
      expect(creationLocationB, isNotNull);
2598 2599 2600
      final String fileB = creationLocationB['file']! as String;
      final int lineB = creationLocationB['line']! as int;
      final int columnB = creationLocationB['column']! as int;
2601 2602 2603 2604 2605 2606
      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.
2607
      expect(columnA, equals(15));
2608
      expect(columnA, equals(columnB));
2609
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
2610

2611
    group(
2612
      'ext.flutter.inspector.addPubRootDirectories group',
2613 2614
      () {
        late final String pubRootTest;
2615

2616 2617 2618
        setUpAll(() async {
          pubRootTest = generateTestPubRootDirectory(service);
        });
2619

2620 2621 2622 2623
        setUp(() {
          service.resetPubRootDirectories();
        });

2624 2625 2626 2627
        testWidgets(
          'has createdByLocalProject when the widget is in the pubRootDirectory',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2628
              const Directionality(
2629 2630
                textDirection: TextDirection.ltr,
                child: Stack(
2631
                  children: <Widget>[
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );

            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2644
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2645 2646 2647 2648
              <String, String>{'arg0': pubRootTest},
            );
            expect(
              await service.testExtension(
2649
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );

        testWidgets(
          'does not have createdByLocalProject if the prefix of the pubRootDirectory is different',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2661
              const Directionality(
2662 2663
                textDirection: TextDirection.ltr,
                child: Stack(
2664
                  children: <Widget>[
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );

            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2677
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2678 2679 2680 2681
              <String, String>{'arg0': '/invalid/$pubRootTest'},
            );
            expect(
              await service.testExtension(
2682
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2683 2684 2685 2686 2687 2688
                <String, String>{'objectGroup': 'my-group'},
              ),
              isNot(contains('createdByLocalProject')),
            );
          },
        );
2689

2690 2691 2692 2693
        testWidgets(
          'has createdByLocalProject if the pubRootDirectory is prefixed with file://',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2694
              const Directionality(
2695 2696
                textDirection: TextDirection.ltr,
                child: Stack(
2697
                  children: <Widget>[
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );

            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2710
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2711 2712 2713 2714
              <String, String>{'arg0': 'file://$pubRootTest'},
            );
            expect(
              await service.testExtension(
2715
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2716 2717 2718 2719 2720 2721
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
2722

2723 2724 2725 2726
        testWidgets(
          'does not have createdByLocalProject if the pubRootDirectory has a different suffix',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2727
              const Directionality(
2728 2729
                textDirection: TextDirection.ltr,
                child: Stack(
2730
                  children: <Widget>[
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );

            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2743
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2744 2745 2746 2747
              <String, String>{'arg0': '$pubRootTest/different'},
            );
            expect(
              await service.testExtension(
2748
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2749 2750 2751 2752 2753 2754
                <String, String>{'objectGroup': 'my-group'},
              ),
              isNot(contains('createdByLocalProject')),
            );
          },
        );
2755

2756 2757 2758 2759
        testWidgets(
          'has createdByLocalProject if at least one of the pubRootDirectories matches',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2760
              const Directionality(
2761 2762
                textDirection: TextDirection.ltr,
                child: Stack(
2763
                  children: <Widget>[
2764 2765 2766 2767 2768 2769 2770
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
2771

2772 2773
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');
2774

2775 2776 2777 2778 2779 2780 2781
            await service.testExtension(
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
              <String, String>{
                'arg0': '/unrelated/$pubRootTest',
                'arg1': 'file://$pubRootTest',
              },
            );
2782

2783 2784
            expect(
              await service.testExtension(
2785
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2786 2787 2788 2789 2790 2791
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
2792

2793 2794 2795 2796
        testWidgets(
          'widget is part of core framework and is the child of a widget in the package pubRootDirectories',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2797
              const Directionality(
2798 2799
                textDirection: TextDirection.ltr,
                child: Stack(
2800
                  children: <Widget>[
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;

            // 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');
            service.setPubRootDirectories(<String>[pubRootTest]);
            final Map<String, Object?> jsonObject =
                json.decode(service.getSelectedWidget(null, 'my-group'))
                    as Map<String, Object?>;
            expect(jsonObject, isNot(contains('createdByLocalProject')));
            final Map<String, Object?> creationLocation =
                jsonObject['creationLocation']! as Map<String, Object?>;
            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
            final List<String> pathSegmentsFramework =
                Uri.parse(creationLocation['file']! as String).pathSegments;
            expect(
              pathSegmentsFramework.join('/'),
              endsWith('/flutter/lib/src/widgets/text.dart'),
            );

            // Strip off /src/widgets/text.dart.
            final String pubRootFramework =
                '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
2840
            service.resetPubRootDirectories();
2841
            await service.testExtension(
2842
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2843 2844 2845 2846
              <String, String>{'arg0': pubRootFramework},
            );
            expect(
              await service.testExtension(
2847
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2848 2849 2850 2851 2852 2853 2854
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
            service.setSelection(elementA, 'my-group');
            expect(
              await service.testExtension(
2855
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2856 2857 2858 2859 2860
                <String, String>{'objectGroup': 'my-group'},
              ),
              isNot(contains('createdByLocalProject')),
            );

2861
            service.resetPubRootDirectories();
2862
            await service.testExtension(
2863
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2864 2865 2866 2867 2868
              <String, String>{'arg0': pubRootFramework, 'arg1': pubRootTest},
            );
            service.setSelection(elementA, 'my-group');
            expect(
              await service.testExtension(
2869
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2870 2871 2872 2873 2874 2875 2876
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
            service.setSelection(richText, 'my-group');
            expect(
              await service.testExtension(
2877
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2878 2879 2880 2881 2882 2883 2884 2885 2886
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
      },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );
2887

2888 2889 2890 2891 2892
    group(
      'ext.flutter.inspector.setPubRootDirectories extra args regression test',
      () {
        // Ensure that passing the isolate id as an argument won't break
        // setPubRootDirectories command.
2893

2894
        late final String pubRootTest;
2895

2896 2897 2898
        setUpAll(() {
          pubRootTest = generateTestPubRootDirectory(service);
        });
2899

2900 2901 2902 2903
        setUp(() {
          service.resetPubRootDirectories();
        });

2904 2905 2906 2907
        testWidgets(
          'has createdByLocalProject when the widget is in the pubRootDirectory',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2908
              const Directionality(
2909 2910
                textDirection: TextDirection.ltr,
                child: Stack(
2911
                  children: <Widget>[
2912 2913
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
2914
                      Text('c', textDirection: TextDirection.ltr),
2915 2916 2917 2918 2919 2920 2921 2922
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2923
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2924 2925 2926 2927
              <String, String>{'arg0': pubRootTest, 'isolateId': '34'},
            );
            expect(
              await service.testExtension(
2928
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2929 2930 2931 2932 2933 2934
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
2935

2936 2937 2938 2939
        testWidgets(
          'does not have createdByLocalProject if the prefix of the pubRootDirectory is different',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2940
              const Directionality(
2941 2942
                textDirection: TextDirection.ltr,
                child: Stack(
2943
                  children: <Widget>[
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

2954 2955 2956 2957 2958 2959 2960
            await service.testExtension(
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
              <String, String>{
                'arg0': '/invalid/$pubRootTest',
                'isolateId': '34'
              },
            );
2961 2962
            expect(
              await service.testExtension(
2963
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2964 2965 2966 2967 2968 2969
                <String, String>{'objectGroup': 'my-group'},
              ),
              isNot(contains('createdByLocalProject')),
            );
          },
        );
2970

2971 2972 2973 2974
        testWidgets(
          'has createdByLocalProject if the pubRootDirectory is prefixed with file://',
          (WidgetTester tester) async {
            await tester.pumpWidget(
2975
              const Directionality(
2976 2977
                textDirection: TextDirection.ltr,
                child: Stack(
2978
                  children: <Widget>[
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

            await service.testExtension(
2990
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
2991 2992 2993 2994
              <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'},
            );
            expect(
              await service.testExtension(
2995
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
2996 2997 2998 2999 3000 3001
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
3002

3003 3004 3005 3006
        testWidgets(
          'does not have createdByLocalProject if the pubRootDirectory has a different suffix',
          (WidgetTester tester) async {
            await tester.pumpWidget(
3007
              const Directionality(
3008 3009
                textDirection: TextDirection.ltr,
                child: Stack(
3010
                  children: <Widget>[
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

3021 3022 3023 3024 3025 3026 3027
            await service.testExtension(
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
              <String, String>{
                'arg0': '$pubRootTest/different',
                'isolateId': '34'
              },
            );
3028 3029
            expect(
              await service.testExtension(
3030
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
3031 3032 3033 3034 3035 3036
                <String, String>{'objectGroup': 'my-group'},
              ),
              isNot(contains('createdByLocalProject')),
            );
          },
        );
3037

3038
        testWidgets(
3039
          'has createdByLocalProject if at least one of the pubRootDirectories matches',
3040 3041
          (WidgetTester tester) async {
            await tester.pumpWidget(
3042
              const Directionality(
3043 3044
                textDirection: TextDirection.ltr,
                child: Stack(
3045
                  children: <Widget>[
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
                    Text('a'),
                    Text('b', textDirection: TextDirection.ltr),
                    Text('c', textDirection: TextDirection.ltr),
                  ],
                ),
              ),
            );
            final Element elementA = find.text('a').evaluate().first;
            service.setSelection(elementA, 'my-group');

3056 3057 3058 3059 3060 3061 3062 3063
            await service.testExtension(
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
              <String, String>{
                'arg0': '/unrelated/$pubRootTest',
                'isolateId': '34',
                'arg1': 'file://$pubRootTest',
              },
            );
3064 3065 3066

            expect(
              await service.testExtension(
3067
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
3068 3069 3070 3071 3072 3073 3074 3075 3076
                <String, String>{'objectGroup': 'my-group'},
              ),
              contains('createdByLocalProject'),
            );
          },
        );
      },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );
3077

3078 3079 3080 3081 3082 3083 3084
    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;
    }

3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
    group('ext.flutter.inspector createdByLocalProject', () {
      late final String pubRootTest;

      setUpAll(() {
        pubRootTest = generateTestPubRootDirectory(service);
      });

      setUp(() {
        service.resetPubRootDirectories();
      });

      testWidgets(
        'reacts to add and removing pubRootDirectories',
        (WidgetTester tester) async {
3099
          const Widget widget = Directionality(
3100 3101
            textDirection: TextDirection.ltr,
            child: Stack(
3102
              children: <Widget>[
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;

          await service.testExtension(
3113
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
3114 3115 3116 3117 3118 3119 3120 3121 3122
            <String, String>{
              'arg0': pubRootTest,
              'arg1': 'file://$pubRootTest',
              'arg2': '/unrelated/$pubRootTest',
            },
          );
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3123
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3124 3125 3126 3127 3128 3129
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );

          await service.testExtension(
3130
            WidgetInspectorServiceExtensions.removePubRootDirectories.name,
3131 3132 3133 3134 3135 3136 3137
            <String, String>{
              'arg0': pubRootTest,
            },
          );
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3138
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
              <String, String>{'objectGroup': 'my-group'},
            ),
            isNot(contains('createdByLocalProject')),
          );
        },
      );

      testWidgets(
        'does not match when the package directory does not match',
        (WidgetTester tester) async {
3149
          const Widget widget = Directionality(
3150 3151
            textDirection: TextDirection.ltr,
            child: Stack(
3152
              children: <Widget>[
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3163 3164 3165 3166 3167 3168 3169
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': '$pubRootTest/different',
              'arg1': '/unrelated/$pubRootTest',
            },
          );
3170 3171
          expect(
            await service.testExtension(
3172
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
              <String, String>{'objectGroup': 'my-group'},
            ),
            isNot(contains('createdByLocalProject')),
          );
        },
      );

      testWidgets(
        'has createdByLocalProject when the pubRootDirectory is prefixed with file://',
        (WidgetTester tester) async {
3183
          const Widget widget = Directionality(
3184 3185
            textDirection: TextDirection.ltr,
            child: Stack(
3186
              children: <Widget>[
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3197 3198 3199 3200
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{'arg0':'file://$pubRootTest'},
          );
3201 3202
          expect(
            await service.testExtension(
3203
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
        },
      );

      testWidgets(
        'can handle consecutive calls to add',
        (WidgetTester tester) async {
3214
          const Widget widget = Directionality(
3215 3216
            textDirection: TextDirection.ltr,
            child: Stack(
3217
              children: <Widget>[
3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3228 3229 3230 3231 3232 3233 3234 3235
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{'arg0': pubRootTest},
          );
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{'arg0': '/invalid/$pubRootTest'},
          );
3236 3237
          expect(
            await service.testExtension(
3238
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3239 3240 3241 3242 3243 3244 3245 3246 3247
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
        },
      );
      testWidgets(
        'can handle removing an unrelated pubRootDirectory',
        (WidgetTester tester) async {
3248
          const Widget widget = Directionality(
3249 3250
            textDirection: TextDirection.ltr,
            child: Stack(
3251
              children: <Widget>[
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3262 3263 3264 3265 3266 3267 3268
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': pubRootTest,
              'arg1': '/invalid/$pubRootTest',
            },
          );
3269 3270
          expect(
            await service.testExtension(
3271
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3272 3273 3274 3275 3276
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );

3277 3278 3279 3280
          service.testExtension(
            WidgetInspectorServiceExtensions.removePubRootDirectories.name,
            <String, String>{'arg0': '/invalid/$pubRootTest'},
          );
3281 3282
          expect(
            await service.testExtension(
3283
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
        },
      );

      testWidgets(
        'can handle parent widget being part of a separate package',
        (WidgetTester tester) async {
3294
          const Widget widget = Directionality(
3295 3296
            textDirection: TextDirection.ltr,
            child: Stack(
3297
              children: <Widget>[
3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          final Element richText = find
              .descendant(
                of: find.text('a'),
                matching: find.byType(RichText),
              )
              .evaluate()
              .first;
          service.setSelection(richText, 'my-group');
3314 3315 3316 3317
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{ 'arg0': pubRootTest },
          );
3318 3319 3320

          final Map<String, Object?> jsonObject =
              (await service.testExtension(
3321
                WidgetInspectorServiceExtensions.getSelectedWidget.name,
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
                <String, String>{'objectGroup': 'my-group'},
              ))! as Map<String, Object?>;
          expect(jsonObject, isNot(contains('createdByLocalProject')));
          final Map<String, Object?> creationLocation =
              jsonObject['creationLocation']! as Map<String, Object?>;
          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
          final List<String> pathSegmentsFramework =
              Uri.parse(creationLocation['file']! as String).pathSegments;
          expect(
            pathSegmentsFramework.join('/'),
            endsWith('/flutter/lib/src/widgets/text.dart'),
          );

          // Strip off /src/widgets/text.dart.
          final String pubRootFramework =
              '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}';
          service.resetPubRootDirectories();
3341 3342 3343 3344
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{'arg0': pubRootFramework},
          );
3345 3346
          expect(
            await service.testExtension(
3347
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3348 3349 3350 3351 3352 3353 3354
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3355
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3356 3357 3358 3359 3360 3361
              <String, String>{'objectGroup': 'my-group'},
            ),
            isNot(contains('createdByLocalProject')),
          );

          service.resetPubRootDirectories();
3362 3363 3364 3365 3366 3367 3368
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': pubRootFramework,
              'arg1': pubRootTest,
            },
          );
3369 3370 3371
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3372
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3373 3374 3375 3376 3377 3378 3379
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
          service.setSelection(richText, 'my-group');
          expect(
            await service.testExtension(
3380
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
              <String, String>{'objectGroup': 'my-group'},
            ),
            contains('createdByLocalProject'),
          );
        },
      );
    },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );

    group('ext.flutter.inspector createdByLocalProject extra args regression test', () {
      late final String pubRootTest;

      setUpAll(() {
        pubRootTest = generateTestPubRootDirectory(service);
      });

      setUp(() {
        service.resetPubRootDirectories();
      });

      testWidgets(
        'reacts to add and removing pubRootDirectories',
        (WidgetTester tester) async {
3405
          const Widget widget = Directionality(
3406 3407
            textDirection: TextDirection.ltr,
            child: Stack(
3408
              children: <Widget>[
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;

          await service.testExtension(
3419
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
            <String, String>{
              'arg0': pubRootTest,
              'arg1': 'file://$pubRootTest',
              'arg2': '/unrelated/$pubRootTest',
              'isolateId': '34',
            },
          );
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3430
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3431 3432 3433 3434 3435 3436
              <String, String>{'objectGroup': 'my-group', 'isolateId': '34',},
            ),
            contains('createdByLocalProject'),
          );

          await service.testExtension(
3437
            WidgetInspectorServiceExtensions.removePubRootDirectories.name,
3438 3439 3440 3441 3442 3443 3444 3445
            <String, String>{
              'arg0': pubRootTest,
              'isolateId': '34',
            },
          );
          service.setSelection(elementA, 'my-group');
          expect(
            await service.testExtension(
3446
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456
              <String, String>{'objectGroup': 'my-group', 'isolateId': '34',},
            ),
            isNot(contains('createdByLocalProject')),
          );
        },
      );

      testWidgets(
        'does not match when the package directory does not match',
        (WidgetTester tester) async {
3457
          const Widget widget = Directionality(
3458 3459
            textDirection: TextDirection.ltr,
            child: Stack(
3460
              children: <Widget>[
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3471 3472 3473 3474 3475 3476 3477
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': '$pubRootTest/different',
              'arg1': '/unrelated/$pubRootTest',
            },
          );
3478 3479
          expect(
            await service.testExtension(
3480
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
              <String, String>{'objectGroup': 'my-group', 'isolateId': '34',},
            ),
            isNot(contains('createdByLocalProject')),
          );
        },
      );

      testWidgets(
        'has createdByLocalProject when the pubRootDirectory is prefixed with file://',
        (WidgetTester tester) async {
3491
          const Widget widget = Directionality(
3492 3493
            textDirection: TextDirection.ltr,
            child: Stack(
3494
              children: <Widget>[
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3505 3506 3507 3508 3509 3510 3511
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0':'file://$pubRootTest',
              'isolateId': '34',
            },
          );
3512 3513
          expect(
            await service.testExtension(
3514
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
              <String, String>{'objectGroup': 'my-group', 'isolateId': '34',},
            ),
            contains('createdByLocalProject'),
          );
        },
      );

      testWidgets(
        'can handle consecutive calls to add',
        (WidgetTester tester) async {
3525
          const Widget widget = Directionality(
3526 3527
            textDirection: TextDirection.ltr,
            child: Stack(
3528
              children: <Widget>[
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': pubRootTest,
              'isolateId': '34',
            },
          );
          service.testExtension(
            WidgetInspectorServiceExtensions.addPubRootDirectories.name,
            <String, String>{
              'arg0': '/invalid/$pubRootTest',
              'isolateId': '34',
            },
          );
3553 3554
          expect(
            await service.testExtension(
3555
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
3556 3557 3558 3559 3560 3561 3562 3563 3564
              <String, String>{'objectGroup': 'my-group', 'isolateId': '34',},
            ),
            contains('createdByLocalProject'),
          );
        },
      );
      testWidgets(
        'can handle removing an unrelated pubRootDirectory',
        (WidgetTester tester) async {
3565
          const Widget widget = Directionality(
3566 3567
            textDirection: TextDirection.ltr,
            child: Stack(
3568
              children: <Widget>[
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
                Text('a'),
                Text('b', textDirection: TextDirection.ltr),
                Text('c', textDirection: TextDirection.ltr),
              ],
            ),
          );
          await tester.pumpWidget(widget);
          final Element elementA = find.text('a').evaluate().first;
          service.setSelection(elementA, 'my-group');

3579 3580 3581 3582 3583 3584 3585 3586
          service.testExtension(
              WidgetInspectorServiceExtensions.addPubRootDirectories.name,
              <String, String>{
              'arg0': pubRootTest,
              'arg1': '/invalid/$pubRootTest',
              'isolateId': '34',
            },
          );
3587 3588
          expect(
            await service.testExtension(
3589 3590 3591 3592 3593
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
              <String, String>{
                'objectGroup': 'my-group',
                'isolateId': '34',
              },
3594 3595 3596 3597
            ),
            contains('createdByLocalProject'),
          );

3598 3599 3600 3601 3602 3603 3604
          service.testExtension(
            WidgetInspectorServiceExtensions.removePubRootDirectories.name,
            <String, String>{
              'arg0': '/invalid/$pubRootTest',
              'isolateId': '34',
            },
          );
3605 3606
          expect(
            await service.testExtension(
3607 3608 3609 3610 3611
              WidgetInspectorServiceExtensions.getSelectedWidget.name,
              <String, String>{
                'objectGroup': 'my-group',
                'isolateId': '34',
              },
3612 3613 3614 3615 3616 3617 3618 3619 3620
            ),
            contains('createdByLocalProject'),
          );
        },
      );
    },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );

3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
    testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets with tear-offs', (WidgetTester tester) async {
      final Widget widget = Directionality(
        textDirection: TextDirection.ltr,
        child: WidgetInspector(
          selectButtonBuilder: null,
          child: _applyConstructor(_TrivialWidget.new),
        ),
      );

      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name,
          <String, String>{'enabled': 'true'},
        ),
        equals('true'),
      );

      await tester.pumpWidget(widget);
    },
      skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag.
    );

3643 3644 3645
    testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets', (WidgetTester tester) async {
      service.rebuildCount = 0;

3646
      await tester.pumpWidget(const ClockDemo());
3647 3648 3649 3650

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

      service.setSelection(clockDemoElement, 'my-group');
3651
      final Map<String, Object?> jsonObject = (await service.testExtension(
3652
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
3653
        <String, String>{'objectGroup': 'my-group'},
3654 3655
      ))! as Map<String, Object?>;
      final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
3656
      expect(creationLocation, isNotNull);
3657
      final String file = creationLocation['file']! as String;
3658 3659 3660 3661
      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.
3662
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
3663
      service.resetPubRootDirectories();
3664 3665 3666 3667
      await service.testExtension(
        WidgetInspectorServiceExtensions.addPubRootDirectories.name,
        <String, String>{'arg0': pubRootTest},
      );
3668

3669
      final List<Map<Object, Object?>> rebuildEvents =
3670
          service.dispatchedEvents('Flutter.RebuiltWidgets');
3671 3672 3673 3674
      expect(rebuildEvents, isEmpty);

      expect(service.rebuildCount, equals(0));
      expect(
3675 3676 3677 3678
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name,
          <String, String>{'enabled': 'true'},
        ),
3679 3680
        equals('true'),
      );
3681 3682 3683 3684
      expect(service.rebuildCount, equals(1));
      await tester.pump();

      expect(rebuildEvents.length, equals(1));
3685
      Map<Object, Object?> event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
3686
      expect(event['startTime'], isA<int>());
3687
      List<int> data = event['events']! as List<int>;
3688 3689
      expect(data.length, equals(14));
      final int numDataEntries = data.length ~/ 2;
3690
      Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>;
3691 3692 3693
      expect(newLocations, isNotNull);
      expect(newLocations.length, equals(1));
      expect(newLocations.keys.first, equals(file));
3694 3695 3696 3697
      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));
3698
      final List<int> locationsForFile = newLocations[file]!;
3699 3700 3701
      expect(locationsForFile.length, equals(21));
      final int numLocationEntries = locationsForFile.length ~/ 3;
      expect(numLocationEntries, equals(numDataEntries));
3702 3703 3704
      final Map<String, List<Object?>> locations = fileLocationsMap[file]!;
      expect(locations.length, equals(4));
      expect(locations['ids']!.length, equals(7));
3705

3706
      final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{};
3707
      _addToKnownLocationsMap(
3708
        knownLocations: knownLocations,
3709
        newLocations: fileLocationsMap,
3710 3711 3712 3713 3714 3715 3716 3717
      );
      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);
3718
        expect(knownLocations, contains(id));
3719 3720 3721 3722 3723 3724 3725 3726 3727
      }
      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.
3728 3729
      StatefulElement clockElement = clocks.first as StatefulElement;
      _ClockTextState state = clockElement.state as _ClockTextState;
3730 3731 3732
      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
      expect(rebuildEvents.length, equals(1));
3733
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
3734
      expect(event['startTime'], isA<int>());
3735
      data = event['events']! as List<int>;
3736
      // No new locations were rebuilt.
3737
      expect(event, isNot(contains('newLocations')));
3738
      expect(event, isNot(contains('locations')));
3739 3740 3741 3742 3743 3744

      // 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];
3745
      _CreationLocation location = knownLocations[id]!;
3746 3747
      expect(location.file, equals(file));
      // ClockText widget.
3748
      expect(location.line, equals(55));
3749
      expect(location.column, equals(9));
3750
      expect(location.name, equals('ClockText'));
3751 3752 3753 3754
      expect(count, equals(1));

      id = data[2];
      count = data[3];
3755
      location = knownLocations[id]!;
3756 3757
      expect(location.file, equals(file));
      // Text widget in _ClockTextState build method.
3758
      expect(location.line, equals(93));
3759
      expect(location.column, equals(12));
3760
      expect(location.name, equals('Text'));
3761 3762 3763 3764
      expect(count, equals(1));

      // Update 3 of the clocks;
      for (int i = 0; i < 3; i++) {
3765 3766
        clockElement = clocks[i] as StatefulElement;
        state = clockElement.state as _ClockTextState;
3767 3768 3769 3770 3771
        state.updateTime(); // Triggers a rebuild.
      }

      await tester.pump();
      expect(rebuildEvents.length, equals(1));
3772
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
3773
      expect(event['startTime'], isA<int>());
3774
      data = event['events']! as List<int>;
3775
      // No new locations were rebuilt.
3776
      expect(event, isNot(contains('newLocations')));
3777
      expect(event, isNot(contains('locations')));
3778 3779 3780 3781

      expect(data.length, equals(4));
      id = data[0];
      count = data[1];
3782
      location = knownLocations[id]!;
3783 3784
      expect(location.file, equals(file));
      // ClockText widget.
3785
      expect(location.line, equals(55));
3786
      expect(location.column, equals(9));
3787
      expect(location.name, equals('ClockText'));
3788 3789 3790 3791
      expect(count, equals(3)); // 3 clock widget instances rebuilt.

      id = data[2];
      count = data[3];
3792
      location = knownLocations[id]!;
3793 3794
      expect(location.file, equals(file));
      // Text widget in _ClockTextState build method.
3795
      expect(location.line, equals(93));
3796
      expect(location.column, equals(12));
3797
      expect(location.name, equals('Text'));
3798 3799 3800
      expect(count, equals(3)); // 3 clock widget instances rebuilt.

      // Update one clock 3 times.
3801 3802
      clockElement = clocks.first as StatefulElement;
      state = clockElement.state as _ClockTextState;
3803 3804 3805 3806 3807 3808
      state.updateTime(); // Triggers a rebuild.
      state.updateTime(); // Triggers a rebuild.
      state.updateTime(); // Triggers a rebuild.

      await tester.pump();
      expect(rebuildEvents.length, equals(1));
3809
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
3810
      expect(event['startTime'], isA<int>());
3811
      data = event['events']! as List<int>;
3812
      // No new locations were rebuilt.
3813
      expect(event, isNot(contains('newLocations')));
3814
      expect(event, isNot(contains('locations')));
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826

      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));
3827
      event = removeLastEvent(rebuildEvents);
Dan Field's avatar
Dan Field committed
3828
      expect(event['startTime'], isA<int>());
3829 3830
      data = event['events']! as List<int>;
      newLocations = event['newLocations']! as Map<String, List<int>>;
3831
      fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>;
3832 3833 3834 3835 3836 3837 3838

      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.
3839
      expect(knownLocations, isNot(contains(id)));
3840
      _addToKnownLocationsMap(
3841
        knownLocations: knownLocations,
3842
        newLocations: fileLocationsMap,
3843 3844
      );
      // Verify the rebuild location was included in the newLocations data.
3845
      expect(knownLocations, contains(id));
3846 3847 3848

      // Turn off rebuild counts.
      expect(
3849 3850 3851 3852
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name,
          <String, String>{'enabled': 'false'},
        ),
3853 3854
        equals('false'),
      );
3855 3856 3857 3858 3859

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

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

3865
      await tester.pumpWidget(const ClockDemo());
3866 3867 3868 3869

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

      service.setSelection(clockDemoElement, 'my-group');
3870
      final Map<String, Object?> jsonObject = (await service.testExtension(
3871
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
3872 3873
        <String, String>{'objectGroup': 'my-group'},
      ))! as Map<String, Object?>;
3874 3875
      final Map<String, Object?> creationLocation =
          jsonObject['creationLocation']! as Map<String, Object?>;
3876
      expect(creationLocation, isNotNull);
3877
      final String file = creationLocation['file']! as String;
3878 3879 3880 3881
      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.
3882
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
3883
      service.resetPubRootDirectories();
3884 3885 3886 3887
      await service.testExtension(
        WidgetInspectorServiceExtensions.addPubRootDirectories.name,
        <String, String>{'arg0': pubRootTest},
      );
3888

3889
      final List<Map<Object, Object?>> repaintEvents =
3890
          service.dispatchedEvents('Flutter.RepaintWidgets');
3891 3892 3893 3894
      expect(repaintEvents, isEmpty);

      expect(service.rebuildCount, equals(0));
      expect(
3895 3896 3897 3898
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRepaintWidgets.name,
          <String, String>{'enabled': 'true'},
        ),
3899 3900
        equals('true'),
      );
3901 3902 3903 3904 3905 3906 3907
      // Unlike trackRebuildDirtyWidgets, trackRepaintWidgets doesn't force a full
      // rebuild.
      expect(service.rebuildCount, equals(0));

      await tester.pump();

      expect(repaintEvents.length, equals(1));
3908
      Map<Object, Object?> event = removeLastEvent(repaintEvents);
Dan Field's avatar
Dan Field committed
3909
      expect(event['startTime'], isA<int>());
3910
      List<int> data = event['events']! as List<int>;
3911 3912
      expect(data.length, equals(18));
      final int numDataEntries = data.length ~/ 2;
3913
      final Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>;
3914 3915 3916
      expect(newLocations, isNotNull);
      expect(newLocations.length, equals(1));
      expect(newLocations.keys.first, equals(file));
3917 3918 3919 3920
      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));
3921
      final List<int> locationsForFile = newLocations[file]!;
3922 3923 3924
      expect(locationsForFile.length, equals(27));
      final int numLocationEntries = locationsForFile.length ~/ 3;
      expect(numLocationEntries, equals(numDataEntries));
3925 3926 3927
      final Map<String, List<Object?>> locations = fileLocationsMap[file]!;
      expect(locations.length, equals(4));
      expect(locations['ids']!.length, equals(9));
3928

3929
      final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{};
3930
      _addToKnownLocationsMap(
3931
        knownLocations: knownLocations,
3932
        newLocations: fileLocationsMap,
3933 3934 3935 3936 3937 3938 3939 3940
      );
      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);
3941
        expect(knownLocations, contains(id));
3942 3943 3944 3945 3946 3947 3948 3949 3950
      }
      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.
3951 3952
      final StatefulElement clockElement = clocks.first as StatefulElement;
      final _ClockTextState state = clockElement.state as _ClockTextState;
3953 3954 3955
      state.updateTime(); // Triggers a rebuild.
      await tester.pump();
      expect(repaintEvents.length, equals(1));
3956
      event = removeLastEvent(repaintEvents);
Dan Field's avatar
Dan Field committed
3957
      expect(event['startTime'], isA<int>());
3958
      data = event['events']! as List<int>;
3959
      // No new locations were rebuilt.
3960
      expect(event, isNot(contains('newLocations')));
3961
      expect(event, isNot(contains('locations')));
3962

3963
      // Triggering a rebuild of one widget in this app causes the whole app
3964 3965 3966 3967 3968 3969 3970 3971
      // 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(
3972 3973 3974 3975
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.trackRepaintWidgets.name,
          <String, String>{'enabled': 'false'},
        ),
3976 3977
        equals('false'),
      );
3978 3979 3980

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

3985
    testWidgets('ext.flutter.inspector.show', (WidgetTester tester) async {
3986 3987
      final Iterable<Map<Object, Object?>> extensionChangedEvents = service.getServiceExtensionStateChangedEvents('ext.flutter.inspector.show');
      Map<Object, Object?> extensionChangedEvent;
3988

3989
      service.rebuildCount = 0;
3990
      expect(extensionChangedEvents, isEmpty);
3991 3992 3993 3994 3995 3996 3997
      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.show.name,
          <String, String>{'enabled': 'true'},
        ),
        equals('true'),
      );
3998 3999 4000 4001
      expect(extensionChangedEvents.length, equals(1));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isTrue);
4002
      expect(service.rebuildCount, equals(1));
4003 4004 4005 4006 4007 4008 4009
      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.show.name,
          <String, String>{},
        ),
        equals('true'),
      );
4010
      expect(WidgetsApp.debugShowWidgetInspectorOverride, isTrue);
4011
      expect(extensionChangedEvents.length, equals(1));
4012 4013 4014 4015 4016 4017 4018
      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.show.name,
          <String, String>{'enabled': 'true'},
        ),
        equals('true'),
      );
4019 4020 4021 4022
      expect(extensionChangedEvents.length, equals(2));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isTrue);
4023
      expect(service.rebuildCount, equals(1));
4024 4025 4026 4027 4028 4029 4030
      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.show.name,
          <String, String>{'enabled': 'false'},
        ),
        equals('false'),
      );
4031 4032 4033 4034
      expect(extensionChangedEvents.length, equals(3));
      extensionChangedEvent = extensionChangedEvents.last;
      expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show'));
      expect(extensionChangedEvent['value'], isFalse);
4035 4036 4037 4038 4039 4040 4041
      expect(
        await service.testBoolExtension(
          WidgetInspectorServiceExtensions.show.name,
          <String, String>{},
        ),
        equals('false'),
      );
4042
      expect(extensionChangedEvents.length, equals(3));
4043 4044 4045
      expect(service.rebuildCount, equals(2));
      expect(WidgetsApp.debugShowWidgetInspectorOverride, isFalse);
    });
4046

4047
    testWidgets('ext.flutter.inspector.screenshot', (WidgetTester tester) async {
4048 4049 4050 4051 4052
      final GlobalKey outerContainerKey = GlobalKey();
      final GlobalKey paddingKey = GlobalKey();
      final GlobalKey redContainerKey = GlobalKey();
      final GlobalKey whiteContainerKey = GlobalKey();
      final GlobalKey sizedBoxKey = GlobalKey();
4053 4054 4055 4056 4057

      // 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(
4058 4059
        Center(
          child: RepaintBoundaryWithDebugPaint(
4060
            child: ColoredBox(
4061 4062
              key: outerContainerKey,
              color: Colors.white,
4063
              child: Padding(
4064 4065
                key: paddingKey,
                padding: const EdgeInsets.all(100.0),
4066
                child: SizedBox(
4067 4068 4069
                  key: sizedBoxKey,
                  height: 100.0,
                  width: 100.0,
4070
                  child: Transform.rotate(
4071
                    angle: 1.0, // radians
4072
                    child: ClipRRect(
4073 4074 4075 4076 4077 4078
                      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),
                      ),
4079
                      child: ColoredBox(
4080 4081
                        key: redContainerKey,
                        color: Colors.red,
4082
                        child: ColoredBox(
4083 4084
                          key: whiteContainerKey,
                          color: Colors.white,
4085 4086 4087
                          child: RepaintBoundary(
                            child: Center(
                              child: Container(
4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
                                color: Colors.black,
                                height: 10.0,
                                width: 10.0,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      );

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

4108
      final RenderRepaintBoundary renderObject = repaintBoundary.renderObject! as RenderRepaintBoundary;
4109

4110
      final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer;
4111 4112 4113 4114
      final int expectedChildLayerCount = getChildLayerCount(layer);
      expect(expectedChildLayerCount, equals(2));
      await expectLater(
        layer.toImage(renderObject.semanticBounds.inflate(50.0)),
4115
        matchesGoldenFile('inspector.repaint_boundary_margin.png'),
4116 4117 4118 4119 4120 4121 4122 4123 4124
      );

      // 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,
        ),
4125
        matchesGoldenFile('inspector.repaint_boundary_margin_small.png'),
4126 4127 4128 4129 4130 4131 4132
      );

      await expectLater(
        layer.toImage(
          renderObject.semanticBounds.inflate(50.0),
          pixelRatio: 2.0,
        ),
4133
        matchesGoldenFile('inspector.repaint_boundary_margin_large.png'),
4134 4135
      );

4136 4137
      final Layer? layerParent = layer.parent;
      final Layer? firstChild = layer.firstChild;
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147

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

      await expectLater(
        service.screenshot(
          repaintBoundary,
          width: 300.0,
          height: 300.0,
        ),
4148
        matchesGoldenFile('inspector.repaint_boundary.png'),
4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164
      );

      // 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,
        ),
4165
        matchesGoldenFile('inspector.repaint_boundary_margin.png'),
4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184
      );

      // 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,
        ),
4185
        matchesGoldenFile('inspector.repaint_boundary_debugPaint.png'),
4186 4187 4188 4189 4190 4191 4192 4193 4194
      );
      // 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),
4195
        matchesGoldenFile('inspector.repaint_boundary.png'),
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207
      );

      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,
        ),
4208
        matchesGoldenFile('inspector.container.png'),
4209 4210 4211 4212 4213 4214 4215 4216 4217
      );

      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 100.0,
          height: 100.0,
          debugPaint: true,
        ),
4218
        matchesGoldenFile('inspector.container_debugPaint.png'),
4219 4220 4221 4222 4223 4224
      );

      {
        // Verify calling the screenshot method still works if the RenderObject
        // needs to be laid out again.
        final RenderObject container =
4225
            find.byKey(outerContainerKey).evaluate().single.renderObject!;
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
        container
          ..markNeedsLayout()
          ..markNeedsPaint();
        expect(container.debugNeedsLayout, isTrue);

        await expectLater(
          service.screenshot(
            find.byKey(outerContainerKey).evaluate().single,
            width: 100.0,
            height: 100.0,
            debugPaint: true,
          ),
4238
          matchesGoldenFile('inspector.container_debugPaint.png'),
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
        );
        expect(container.debugNeedsLayout, isFalse);
      }

      // Small image
      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 50.0,
          height: 100.0,
        ),
4250
        matchesGoldenFile('inspector.container_small.png'),
4251 4252 4253 4254 4255 4256 4257 4258 4259
      );

      await expectLater(
        service.screenshot(
          find.byKey(outerContainerKey).evaluate().single,
          width: 400.0,
          height: 400.0,
          maxPixelRatio: 3.0,
        ),
4260
        matchesGoldenFile('inspector.container_large.png'),
4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271
      );

      // 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,
        ),
4272
        matchesGoldenFile('inspector.clipRect_debugPaint.png'),
4273 4274
      );

4275 4276
      final Element clipRect = find.byType(ClipRRect).evaluate().single;

4277
      final Future<ui.Image?> clipRectScreenshot = service.screenshot(
4278 4279 4280 4281 4282 4283
        clipRect,
        width: 100.0,
        height: 100.0,
        margin: 20.0,
        debugPaint: true,
      );
4284 4285 4286
      // 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(
4287
        clipRectScreenshot,
4288
        matchesGoldenFile('inspector.clipRect_debugPaint_margin.png'),
4289 4290 4291 4292
      );

      // Verify we get the same image if we go through the service extension
      // instead of invoking the screenshot method directly.
4293
      final Future<Object?> base64ScreenshotFuture = service.testExtension(
4294
        WidgetInspectorServiceExtensions.screenshot.name,
4295
        <String, String>{
4296
          'id': service.toId(clipRect, 'group')!,
4297 4298 4299 4300 4301 4302 4303
          'width': '100.0',
          'height': '100.0',
          'margin': '20.0',
          'debugPaint': 'true',
        },
      );

4304
      final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
4305 4306
      final ui.Image screenshotImage = (await binding.runAsync<ui.Image>(() async {
        final String base64Screenshot = (await base64ScreenshotFuture)! as String;
4307 4308 4309
        final ui.Codec codec = await ui.instantiateImageCodec(base64.decode(base64Screenshot));
        final ui.FrameInfo frame = await codec.getNextFrame();
        return frame.image;
4310
      }))!;
4311 4312 4313

      await expectLater(
        screenshotImage,
4314
        matchesReferenceImage((await clipRectScreenshot)!),
4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
      );

      // Test with a very visible debug paint
      await expectLater(
        service.screenshot(
          find.byKey(paddingKey).evaluate().single,
          width: 300.0,
          height: 300.0,
          debugPaint: true,
        ),
4325
        matchesGoldenFile('inspector.padding_debugPaint.png'),
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335
      );

      // 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,
        ),
4336
        matchesGoldenFile('inspector.sizedBox_debugPaint.png'),
4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
      );

      // 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,
        ),
4348
        matchesGoldenFile('inspector.sizedBox_debugPaint_margin.png'),
4349
      );
4350
    });
4351

4352 4353 4354 4355 4356 4357 4358 4359
    group('layout explorer', () {
      const String group = 'test-group';

      tearDown(() {
        service.disposeAllGroups();
      });

      Future<void> pumpWidgetForLayoutExplorer(WidgetTester tester) async {
4360
        const Widget widget = Directionality(
4361 4362 4363
          textDirection: TextDirection.ltr,
          child: Center(
            child: Row(
4364
              children: <Widget>[
4365
                Flexible(
4366
                  child: ColoredBox(
4367
                    color: Colors.green,
4368
                    child: Text('a'),
4369 4370
                  ),
                ),
4371
                Text('b'),
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474
              ],
            ),
          ),
        );
        await tester.pumpWidget(widget);
      }

      testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with BoxParentData',(WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element rowElement = tester.element(find.byType(Row));
        service.setSelection(rowElement, group);

        final DiagnosticsNode diagnostic = rowElement.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        final Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Row'));

        final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?;
        expect(renderObject, isNotNull);
        expect(renderObject!['description'], startsWith('RenderFlex'));

        final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?;
        expect(parentRenderElement, isNotNull);
        expect(parentRenderElement!['description'], equals('Center'));

        final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?;
        expect(constraints, isNotNull);
        expect(constraints!['type'], equals('BoxConstraints'));
        expect(constraints['minWidth'], equals('0.0'));
        expect(constraints['minHeight'], equals('0.0'));
        expect(constraints['maxWidth'], equals('800.0'));
        expect(constraints['maxHeight'], equals('600.0'));

        expect(result['isBox'], equals(true));

        final Map<String, Object?>? size = result['size'] as Map<String, Object?>?;
        expect(size, isNotNull);
        expect(size!['width'], equals('800.0'));
        expect(size['height'], equals('14.0'));

        expect(result['flexFactor'], isNull);
        expect(result['flexFit'], isNull);

        final Map<String, Object?>? parentData = result['parentData'] as Map<String, Object?>?;
        expect(parentData, isNotNull);
        expect(parentData!['offsetX'], equals('0.0'));
        expect(parentData['offsetY'], equals('293.0'));
      });

      testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with FlexParentData',(WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element flexibleElement = tester.element(find.byType(Flexible).first);
        service.setSelection(flexibleElement, group);

        final DiagnosticsNode diagnostic = flexibleElement.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        final Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Flexible'));

        final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?;
        expect(renderObject, isNotNull);
        expect(renderObject!['description'], startsWith('_RenderColoredBox'));

        final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?;
        expect(parentRenderElement, isNotNull);
        expect(parentRenderElement!['description'], equals('Row'));

        final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?;
        expect(constraints, isNotNull);
        expect(constraints!['type'], equals('BoxConstraints'));
        expect(constraints['minWidth'], equals('0.0'));
        expect(constraints['minHeight'], equals('0.0'));
        expect(constraints['maxWidth'], equals('786.0'));
        expect(constraints['maxHeight'], equals('600.0'));

        expect(result['isBox'], equals(true));

        final Map<String, Object?>? size = result['size'] as Map<String, Object?>?;
        expect(size, isNotNull);
        expect(size!['width'], equals('14.0'));
        expect(size['height'], equals('14.0'));

        expect(result['flexFactor'], equals(1));
        expect(result['flexFit'], equals('loose'));

        expect(result['parentData'], isNull);
      });


      testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderView',(WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element element = tester.element(find.byType(Directionality).first);
        Element? root;
        element.visitAncestorElements((Element ancestor) {
4475
          root = ancestor;
4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631
          return true;
        });
        expect(root, isNotNull);
        service.setSelection(root, group);

        final DiagnosticsNode diagnostic = root!.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        final Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('[root]'));

        final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?;
        expect(renderObject, isNotNull);
        expect(renderObject!['description'], startsWith('RenderView'));

        expect(result['parentRenderElement'], isNull);
        expect(result['constraints'], isNull);
        expect(result['isBox'], isNull);

        final Map<String, Object?>? size = result['size'] as Map<String, Object?>?;
        expect(size, isNotNull);
        expect(size!['width'], equals('800.0'));
        expect(size['height'], equals('600.0'));

        expect(result['flexFactor'], isNull);
        expect(result['flexFit'], isNull);
        expect(result['parentData'], isNull);
      });

      testWidgets('ext.flutter.inspector.setFlexFit', (WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element childElement = tester.element(find.byType(Flexible).first);
        service.setSelection(childElement, group);

        final DiagnosticsNode diagnostic = childElement.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Flexible'));
        expect(result['flexFit'], equals('loose'));

        final String valueId = result['valueId']! as String;

        final bool flexFitSuccess = (await service.testExtension(
          WidgetInspectorServiceExtensions.setFlexFit.name,
          <String, String>{'id': valueId, 'flexFit': 'FlexFit.tight'},
        ))! as bool;
        expect(flexFitSuccess, isTrue);

        result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Flexible'));
        expect(result['flexFit'], equals('tight'));
      });

      testWidgets('ext.flutter.inspector.setFlexFactor', (WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element childElement = tester.element(find.byType(Flexible).first);
        service.setSelection(childElement, group);

        final DiagnosticsNode diagnostic = childElement.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Flexible'));
        expect(result['flexFactor'], equals(1));

        final String valueId = result['valueId']! as String;

        final bool flexFactorSuccess = (await service.testExtension(
          WidgetInspectorServiceExtensions.setFlexFactor.name,
          <String, String>{'id': valueId, 'flexFactor': '3'},
        ))! as bool;
        expect(flexFactorSuccess, isTrue);

        result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Flexible'));
        expect(result['flexFactor'], equals(3));
      });

      testWidgets('ext.flutter.inspector.setFlexProperties', (WidgetTester tester) async {
        await pumpWidgetForLayoutExplorer(tester);

        final Element rowElement = tester.element(find.byType(Row).first);
        service.setSelection(rowElement, group);

        final DiagnosticsNode diagnostic = rowElement.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;
        Map<String, Object?> result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Row'));

        Map<String, Object?> renderObject = result['renderObject']! as Map<String, Object?>;
        List<Map<String, Object?>> properties =
            (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>();
        Map<String, Object?> mainAxisAlignmentProperties =
            properties.firstWhere(
          (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>',
        );
        Map<String, Object?> crossAxisAlignmentProperties =
            properties.firstWhere(
          (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>',
        );
        String mainAxisAlignment = mainAxisAlignmentProperties['description']! as String;
        String crossAxisAlignment = crossAxisAlignmentProperties['description']! as String;
        expect(mainAxisAlignment, equals('start'));
        expect(crossAxisAlignment, equals('center'));

        final String valueId = result['valueId']! as String;
        final bool flexFactorSuccess = (await service.testExtension(
          WidgetInspectorServiceExtensions.setFlexProperties.name,
          <String, String>{
            'id': valueId,
            'mainAxisAlignment': 'MainAxisAlignment.center',
            'crossAxisAlignment': 'CrossAxisAlignment.start',
          },
        ))! as bool;
        expect(flexFactorSuccess, isTrue);

        result = (await service.testExtension(
          WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
          <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
        ))! as Map<String, Object?>;
        expect(result['description'], equals('Row'));

        renderObject = result['renderObject']! as Map<String, Object?>;
        properties =
            (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>();
        mainAxisAlignmentProperties =
            properties.firstWhere(
          (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>',
        );
        crossAxisAlignmentProperties =
            properties.firstWhere(
          (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>',
        );
        mainAxisAlignment = mainAxisAlignmentProperties['description']! as String;
        crossAxisAlignment = crossAxisAlignmentProperties['description']! as String;
        expect(mainAxisAlignment, equals('center'));
        expect(crossAxisAlignment, equals('start'));
      });
4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661

      testWidgets('ext.flutter.inspector.getLayoutExplorerNode does not throw StackOverflowError',(WidgetTester tester) async {
        // Regression test for https://github.com/flutter/flutter/issues/115228
        const Key leafKey = ValueKey<String>('ColoredBox');
        await tester.pumpWidget(
          CupertinoApp(
            home: CupertinoPageScaffold(
              child: Builder(
                builder: (BuildContext context) => ColoredBox(key: leafKey, color: CupertinoTheme.of(context).primaryColor),
              ),
            ),
          ),
        );

        final Element leaf = tester.element(find.byKey(leafKey));
        service.setSelection(leaf, group);
        final DiagnosticsNode diagnostic = leaf.toDiagnosticsNode();
        final String id = service.toId(diagnostic, group)!;

        Object? error;
        try {
          await service.testExtension(
            WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
            <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'},
          );
        } catch (e) {
          error = e;
        }
        expect(error, isNull);
      });
4662 4663
    });

4664
    test('ext.flutter.inspector.structuredErrors', () async {
4665
      List<Map<Object, Object?>> flutterErrorEvents = service.dispatchedEvents('Flutter.Error');
4666 4667
      expect(flutterErrorEvents, isEmpty);

4668
      final FlutterExceptionHandler oldHandler = FlutterError.presentError;
4669 4670 4671

      try {
        // Enable structured errors.
4672
        expect(
4673 4674 4675 4676
          await service.testBoolExtension(
            WidgetInspectorServiceExtensions.structuredErrors.name,
            <String, String>{'enabled': 'true'},
          ),
4677 4678
          equals('true'),
        );
4679 4680

        // Create an error.
4681
        FlutterError.reportError(FlutterErrorDetails(
4682 4683 4684 4685 4686 4687
          library: 'rendering library',
          context: ErrorDescription('during layout'),
          exception: StackTrace.current,
        ));

        // Validate that we received an error.
4688
        flutterErrorEvents = service.dispatchedEvents('Flutter.Error');
4689 4690 4691
        expect(flutterErrorEvents, hasLength(1));

        // Validate the error contents.
4692
        Map<Object, Object?> error = flutterErrorEvents.first;
4693 4694 4695 4696 4697
        expect(error['description'], 'Exception caught by rendering library');
        expect(error['children'], isEmpty);

        // Validate that we received an error count.
        expect(error['errorsSinceReload'], 0);
4698
        expect(
4699 4700 4701
          error['renderedErrorText'],
          startsWith('══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞════════════'),
        );
4702 4703

        // Send a second error.
4704
        FlutterError.reportError(FlutterErrorDetails(
4705 4706 4707 4708 4709 4710
          library: 'rendering library',
          context: ErrorDescription('also during layout'),
          exception: StackTrace.current,
        ));

        // Validate that the error count increased.
4711
        flutterErrorEvents = service.dispatchedEvents('Flutter.Error');
4712 4713 4714
        expect(flutterErrorEvents, hasLength(2));
        error = flutterErrorEvents.last;
        expect(error['errorsSinceReload'], 1);
4715
        expect(error['renderedErrorText'], startsWith('Another exception was thrown:'));
4716

4717
        // Reloads the app.
4718
        final FlutterExceptionHandler? oldHandler = FlutterError.onError;
4719
        final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
4720 4721 4722 4723 4724 4725 4726 4727 4728 4729
        // 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();
4730 4731

        // Send another error.
4732
        FlutterError.reportError(FlutterErrorDetails(
4733 4734 4735 4736 4737 4738
          library: 'rendering library',
          context: ErrorDescription('during layout'),
          exception: StackTrace.current,
        ));

        // And, validate that the error count has been reset.
4739
        flutterErrorEvents = service.dispatchedEvents('Flutter.Error');
4740 4741 4742 4743
        expect(flutterErrorEvents, hasLength(3));
        error = flutterErrorEvents.last;
        expect(error['errorsSinceReload'], 0);
      } finally {
4744
        FlutterError.presentError = oldHandler;
4745 4746 4747
      }
    });

4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
    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.
4763 4764 4765 4766 4767
      final LayerLink link = LayerLink();
      final GlobalKey key = GlobalKey();
      final GlobalKey mainStackKey = GlobalKey();
      final GlobalKey transformTargetParent = GlobalKey();
      final GlobalKey stackWithTransformFollower = GlobalKey();
4768 4769

      await tester.pumpWidget(
4770
        Directionality(
4771
          textDirection: TextDirection.ltr,
4772 4773
          child: RepaintBoundary(
            child: Stack(
4774 4775
              key: mainStackKey,
              children: <Widget>[
4776
                Stack(
4777 4778
                  key: transformTargetParent,
                  children: <Widget>[
4779
                    Positioned(
4780 4781
                      left: 123.0,
                      top: 456.0,
4782
                      child: CompositedTransformTarget(
4783
                        link: link,
4784
                        child: Container(height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)),
4785 4786 4787 4788
                      ),
                    ),
                  ],
                ),
4789
                Positioned(
4790 4791
                  left: 787.0,
                  top: 343.0,
4792
                  child: Stack(
4793 4794 4795 4796
                    key: stackWithTransformFollower,
                    children: <Widget>[
                      // Container so we can see how the follower layer was
                      // transformed relative to its initial location.
4797 4798
                      Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)),
                      CompositedTransformFollower(
4799
                        link: link,
4800
                        child: Container(key: key, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)),
4801 4802 4803 4804 4805 4806 4807 4808 4809
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
4810
      final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox;
4811 4812 4813 4814
      expect(box.localToGlobal(Offset.zero), const Offset(123.0, 456.0));

      await expectLater(
        find.byKey(mainStackKey),
4815
        matchesGoldenFile('inspector.composited_transform.only_offsets.png'),
4816 4817 4818 4819 4820 4821 4822 4823
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformFollower).evaluate().first,
          width: 5000.0,
          height: 500.0,
        ),
4824
        matchesGoldenFile('inspector.composited_transform.only_offsets_follower.png'),
4825 4826 4827 4828
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(find.byType(Stack).evaluate().first, width: 300.0, height: 300.0),
4829
        matchesGoldenFile('inspector.composited_transform.only_offsets_small.png'),
4830 4831 4832 4833 4834 4835 4836 4837
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(transformTargetParent).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
4838
        matchesGoldenFile('inspector.composited_transform.only_offsets_target.png'),
4839
      );
4840
    });
4841 4842

    testWidgets('Screenshot composited transforms - with rotations', (WidgetTester tester) async {
4843 4844 4845 4846 4847 4848 4849 4850
      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();
4851 4852

      await tester.pumpWidget(
4853
        Directionality(
4854
          textDirection: TextDirection.ltr,
4855
          child: Stack(
4856 4857
            key: mainStackKey,
            children: <Widget>[
4858
              Stack(
4859 4860
                key: stackWithTransformTarget,
                children: <Widget>[
4861
                  Positioned(
4862 4863
                    top: 123.0,
                    left: 456.0,
4864
                    child: Transform.rotate(
4865 4866
                      key: rotate1,
                      angle: 1.0, // radians
4867
                      child: CompositedTransformTarget(
4868
                        link: link,
4869
                        child: Container(key: key1, height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)),
4870 4871 4872 4873 4874
                      ),
                    ),
                  ),
                ],
              ),
4875
              Positioned(
4876 4877
                top: 487.0,
                left: 243.0,
4878
                child: Stack(
4879 4880
                  key: stackWithTransformFollower,
                  children: <Widget>[
4881 4882
                    Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)),
                    Transform.rotate(
4883 4884
                      key: rotate2,
                      angle: -0.3, // radians
4885
                      child: CompositedTransformFollower(
4886
                        link: link,
4887
                        child: Container(key: key2, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)),
4888 4889 4890 4891 4892 4893 4894 4895 4896
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
4897 4898
      final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox;
      final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox;
4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
      // 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),
4910
        matchesGoldenFile('inspector.composited_transform.with_rotations.png'),
4911 4912 4913 4914 4915 4916 4917 4918
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(mainStackKey).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
4919
        matchesGoldenFile('inspector.composited_transform.with_rotations_small.png'),
4920 4921 4922 4923 4924 4925 4926 4927
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformTarget).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
4928
        matchesGoldenFile('inspector.composited_transform.with_rotations_target.png'),
4929 4930 4931 4932 4933 4934 4935 4936
      );

      await expectLater(
        WidgetInspectorService.instance.screenshot(
          find.byKey(stackWithTransformFollower).evaluate().first,
          width: 500.0,
          height: 500.0,
        ),
4937
        matchesGoldenFile('inspector.composited_transform.with_rotations_follower.png'),
4938 4939 4940 4941
      );

      // Make sure taking screenshots hasn't modified the positions of the
      // TransformTarget or TransformFollower layers.
4942 4943
      expect(identical(key1.currentContext!.findRenderObject(), box1), isTrue);
      expect(identical(key2.currentContext!.findRenderObject(), box2), isTrue);
4944 4945
      expect(box1.localToGlobal(Offset.zero), equals(position1));
      expect(box2.localToGlobal(Offset.zero), equals(position2));
4946
    });
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964

    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!'),
            ),
          ),
        ),
      );
4965
      service.setSelection(find.text('Hello, World!').evaluate().first, 'my-group');
4966 4967

      // Figure out the pubRootDirectory
4968
      final Map<String, Object?> jsonObject = (await service.testExtension(
4969 4970
        WidgetInspectorServiceExtensions.getSelectedWidget.name,
        <String, String>{'objectGroup': 'my-group'},
4971 4972
      ))! as Map<String, Object?>;
      final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>;
4973
      expect(creationLocation, isNotNull);
4974
      final String file = creationLocation['file']! as String;
4975 4976 4977
      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.
4978
      final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';
4979 4980
      service.resetPubRootDirectories();
      service.addPubRootDirectories(<String>[pubRootTest]);
4981 4982

      final String summary = service.getRootWidgetSummaryTree('foo1');
4983
      // ignore: avoid_dynamic_calls
4984 4985 4986
      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?>;
4987
      expect(scaffold['description'], 'Scaffold');
4988
      final String objectId = scaffold['objectId']! as String;
4989
      final String details = service.getDetailsSubtree(objectId, 'foo2');
4990
      // ignore: avoid_dynamic_calls
4991
      final List<Object?> detailedChildren = json.decode(details)['children'] as List<Object?>;
4992

4993 4994 4995
      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?>>()) {
4996 4997 4998 4999
          if (child['description'] == 'AppBar') {
            appBars.add(child);
          }
          if (child.containsKey('children')) {
5000
            visitChildren(child['children']! as List<Object?>);
5001 5002 5003 5004
          }
        }
      }
      visitChildren(detailedChildren);
5005
      expect(appBars.single, isNot(contains('children')));
5006
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
5007 5008 5009 5010 5011 5012 5013 5014 5015

    testWidgets('InspectorSerializationDelegate addAdditionalPropertiesCallback', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          title: 'Hello World!',
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Hello World!'),
            ),
5016
            body: const Center(
5017
              child: Column(
5018
                children: <Widget>[
5019 5020 5021 5022 5023
                  Text('Hello World!'),
                ],
              ),
            ),
          ),
5024
        ),
5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038
      );
      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,
          includeProperties: true,
          addAdditionalPropertiesCallback:
            (DiagnosticsNode node, InspectorSerializationDelegate delegate) {
              final Map<String, Object> additionalJson = <String, Object>{};
5039
              final Object? value = node.value;
5040
              if (value is Element) {
5041 5042 5043 5044 5045 5046 5047
                final RenderObject? renderObject = value.renderObject;
                if (renderObject != null) {
                  additionalJson['renderObject'] =
                      renderObject.toDiagnosticsNode().toJsonMap(
                        delegate.copyWith(subtreeDepth: 0),
                      );
                }
5048 5049 5050 5051 5052
              }
              additionalJson['callbackExecuted'] = true;
              return additionalJson;
            },
        );
5053
      final Map<String, Object?> json = node.toJsonMap(delegate);
5054 5055
      expect(json['callbackExecuted'], true);
      expect(json.containsKey('renderObject'), true);
5056 5057
      expect(json['renderObject'], isA<Map<String, Object?>>());
      final Map<String, Object?> renderObjectJson = json['renderObject']! as Map<String, Object?>;
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075
      expect(renderObjectJson['description'], startsWith('RenderFlex'));

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

    testWidgets('debugIsLocalCreationLocation test', (WidgetTester tester) async {
5078
      setupDefaultPubRootDirectory(service);
5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091

      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),
          ),
        ),
      );

5092
      final Element element = key.currentContext! as Element;
5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103

      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);
5104
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.
5105

5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145
    testWidgets('debugIsWidgetLocalCreation test', (WidgetTester tester) async {
      setupDefaultPubRootDirectory(service);

      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),
          ),
        ),
      );

      final Element element = key.currentContext! as Element;
      expect(debugIsWidgetLocalCreation(element.widget), isTrue);

      final Finder paddingFinder = find.byType(Padding);
      final Element paddingElement = paddingFinder.evaluate().first;
      expect(debugIsWidgetLocalCreation(paddingElement.widget), isFalse);
    }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag.

    testWidgets('debugIsWidgetLocalCreation false test', (WidgetTester tester) async {
      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),
          ),
        ),
      );

      final Element element = key.currentContext! as Element;
      expect(debugIsWidgetLocalCreation(element.widget), isFalse);
    }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag.

5146 5147
    test('devToolsInspectorUri test', () {
      activeDevToolsServerAddress = 'http://127.0.0.1:9100';
5148
      connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/';
5149
      expect(
5150
        WidgetInspectorService.instance.devToolsInspectorUri('inspector-0'),
5151 5152 5153
        equals('http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55269%2F798ay5al_FM%3D%2F&inspectorRef=inspector-0'),
      );
    });
5154 5155 5156 5157 5158

    test('DevToolsDeepLinkProperty test', () {
      final DevToolsDeepLinkProperty node =
      DevToolsDeepLinkProperty(
        'description of the deep link',
5159
        'http://the-deeplink/',
5160 5161 5162
      );
      expect(node.toString(), equals('description of the deep link'));
      expect(node.name, isEmpty);
5163
      expect(node.value, equals('http://the-deeplink/'));
5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
      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',
5175
          'value': 'http://the-deeplink/',
5176 5177 5178
        }),
      );
    });
5179
  }
5180

5181
  static String generateTestPubRootDirectory(TestWidgetInspectorService service) {
5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
    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;

    // Strip a couple subdirectories away to generate a plausible pub root
    // directory.
5193 5194 5195 5196 5197 5198
    final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}';

    return pubRootTest;
  }

  static void setupDefaultPubRootDirectory(TestWidgetInspectorService service) {
5199
    service.resetPubRootDirectories();
5200
    service
5201
        .addPubRootDirectories(<String>[generateTestPubRootDirectory(service)]);
5202
  }
5203
}
5204

5205
void _addToKnownLocationsMap({
5206
  required Map<int, _CreationLocation> knownLocations,
5207
  required Map<String, Map<String, List<Object?>>> newLocations,
5208
}) {
5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223
  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],
      );
5224 5225 5226
    }
  });
}
5227 5228 5229 5230 5231 5232 5233 5234

extension WidgetInspectorServiceExtension on WidgetInspectorService {
  Future<List<String>> get currentPubRootDirectories async {
    return ((await pubRootDirectories(
        <String, String>{},
      ))['result'] as List<Object?>).cast<String>();
  }
}