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

import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
7
import 'package:flutter_test/flutter_test.dart';
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

import 'semantics_tester.dart';

void main() {
  group(CustomPainter, () {
    setUp(() {
      debugResetSemanticsIdCounter();
      _PainterWithSemantics.shouldRebuildSemanticsCallCount = 0;
      _PainterWithSemantics.buildSemanticsCallCount = 0;
      _PainterWithSemantics.semanticsBuilderCallCount = 0;
    });

    _defineTests();
  });
}

void _defineTests() {
  testWidgets('builds no semantics by default', (WidgetTester tester) async {
26
    final SemanticsTester semanticsTester = SemanticsTester(tester);
27

28 29
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithoutSemantics(),
30 31 32
    ));

    expect(semanticsTester, hasSemantics(
33
      TestSemantics.root(),
34 35 36 37 38 39
    ));

    semanticsTester.dispose();
  });

  testWidgets('provides foreground semantics', (WidgetTester tester) async {
40
    final SemanticsTester semanticsTester = SemanticsTester(tester);
41

42 43
    await tester.pumpWidget(CustomPaint(
      foregroundPainter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
44
        semantics: const CustomPainterSemantics(
45
          rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
46
          properties: SemanticsProperties(
47 48 49 50 51 52 53 54
            label: 'foreground',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
    ));

    expect(semanticsTester, hasSemantics(
55
      TestSemantics.root(
56
        children: <TestSemantics>[
57
          TestSemantics.rootChild(
58 59 60
            id: 1,
            rect: TestSemantics.fullScreen,
            children: <TestSemantics>[
61
              TestSemantics(
62 63
                id: 2,
                label: 'foreground',
Dan Field's avatar
Dan Field committed
64
                rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
65 66 67 68 69 70 71 72 73 74 75
              ),
            ],
          ),
        ],
      ),
    ));

    semanticsTester.dispose();
  });

  testWidgets('provides background semantics', (WidgetTester tester) async {
76
    final SemanticsTester semanticsTester = SemanticsTester(tester);
77

78 79
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
80
        semantics: const CustomPainterSemantics(
81
          rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
82
          properties: SemanticsProperties(
83 84 85 86 87 88 89 90
            label: 'background',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
    ));

    expect(semanticsTester, hasSemantics(
91
      TestSemantics.root(
92
        children: <TestSemantics>[
93
          TestSemantics.rootChild(
94 95 96
            id: 1,
            rect: TestSemantics.fullScreen,
            children: <TestSemantics>[
97
              TestSemantics(
98 99
                id: 2,
                label: 'background',
Dan Field's avatar
Dan Field committed
100
                rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
101 102 103 104 105 106 107 108 109 110 111
              ),
            ],
          ),
        ],
      ),
    ));

    semanticsTester.dispose();
  });

  testWidgets('combines background, child and foreground semantics', (WidgetTester tester) async {
112
    final SemanticsTester semanticsTester = SemanticsTester(tester);
113

114 115
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
116
        semantics: const CustomPainterSemantics(
117
          rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
118
          properties: SemanticsProperties(
119 120 121 122 123
            label: 'background',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
124
      foregroundPainter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
125
        semantics: const CustomPainterSemantics(
126
          rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
127
          properties: SemanticsProperties(
128 129 130 131 132
            label: 'foreground',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
133 134 135 136
      child: Semantics(
        container: true,
        child: const Text('Hello', textDirection: TextDirection.ltr),
      ),
137 138 139
    ));

    expect(semanticsTester, hasSemantics(
140
      TestSemantics.root(
141
        children: <TestSemantics>[
142
          TestSemantics.rootChild(
143 144 145
            id: 1,
            rect: TestSemantics.fullScreen,
            children: <TestSemantics>[
146
              TestSemantics(
147 148
                id: 3,
                label: 'background',
Dan Field's avatar
Dan Field committed
149
                rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
150
              ),
151
              TestSemantics(
152 153
                id: 2,
                label: 'Hello',
Dan Field's avatar
Dan Field committed
154
                rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
155
              ),
156
              TestSemantics(
157 158
                id: 4,
                label: 'foreground',
Dan Field's avatar
Dan Field committed
159
                rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
160 161 162 163 164 165 166 167 168 169 170
              ),
            ],
          ),
        ],
      ),
    ));

    semanticsTester.dispose();
  });

  testWidgets('applies $SemanticsProperties', (WidgetTester tester) async {
171
    final SemanticsTester semanticsTester = SemanticsTester(tester);
172

173 174
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
175 176
        semantics: const CustomPainterSemantics(
          key: ValueKey<int>(1),
177
          rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
Dan Field's avatar
Dan Field committed
178
          properties: SemanticsProperties(
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            checked: false,
            selected: false,
            button: false,
            label: 'label-before',
            value: 'value-before',
            increasedValue: 'increase-before',
            decreasedValue: 'decrease-before',
            hint: 'hint-before',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
    ));

    expect(semanticsTester, hasSemantics(
194
      TestSemantics.root(
195
        children: <TestSemantics>[
196
          TestSemantics.rootChild(
197 198 199
            id: 1,
            rect: TestSemantics.fullScreen,
            children: <TestSemantics>[
200
              TestSemantics(
Dan Field's avatar
Dan Field committed
201
                rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
                id: 2,
                flags: 1,
                label: 'label-before',
                value: 'value-before',
                increasedValue: 'increase-before',
                decreasedValue: 'decrease-before',
                hint: 'hint-before',
                textDirection: TextDirection.rtl,
              ),
            ],
          ),
        ],
      ),
    ));

217 218 219
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
        semantics: CustomPainterSemantics(
220
          key: const ValueKey<int>(1),
Dan Field's avatar
Dan Field committed
221
          rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0),
222
          properties: SemanticsProperties(
223 224 225 226 227 228 229 230 231
            checked: true,
            selected: true,
            button: true,
            label: 'label-after',
            value: 'value-after',
            increasedValue: 'increase-after',
            decreasedValue: 'decrease-after',
            hint: 'hint-after',
            textDirection: TextDirection.ltr,
232 233 234 235 236 237 238 239
            onScrollDown: () { },
            onLongPress: () { },
            onDecrease: () { },
            onIncrease: () { },
            onScrollLeft: () { },
            onScrollRight: () { },
            onScrollUp: () { },
            onTap: () { },
240 241 242 243 244 245
          ),
        ),
      ),
    ));

    expect(semanticsTester, hasSemantics(
246
      TestSemantics.root(
247
        children: <TestSemantics>[
248
          TestSemantics.rootChild(
249 250 251
            id: 1,
            rect: TestSemantics.fullScreen,
            children: <TestSemantics>[
252
              TestSemantics(
Dan Field's avatar
Dan Field committed
253
                rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0),
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
                actions: 255,
                id: 2,
                flags: 15,
                label: 'label-after',
                value: 'value-after',
                increasedValue: 'increase-after',
                decreasedValue: 'decrease-after',
                hint: 'hint-after',
                textDirection: TextDirection.ltr,
              ),
            ],
          ),
        ],
      ),
    ));

    semanticsTester.dispose();
  });

273
  testWidgets('Can toggle semantics on, off, on without crash', (WidgetTester tester) async {
274 275
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
276 277
        semantics: const CustomPainterSemantics(
          key: ValueKey<int>(1),
278
          rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
Dan Field's avatar
Dan Field committed
279
          properties: SemanticsProperties(
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            checked: false,
            selected: false,
            button: false,
            label: 'label-before',
            value: 'value-before',
            increasedValue: 'increase-before',
            decreasedValue: 'decrease-before',
            hint: 'hint-before',
            textDirection: TextDirection.rtl,
          ),
        ),
      ),
    ));

    // Start with semantics off.
    expect(tester.binding.pipelineOwner.semanticsOwner, isNull);

    // Semantics on
298
    SemanticsTester semantics = SemanticsTester(tester);
299 300 301 302 303 304 305 306 307
    await tester.pumpAndSettle();
    expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull);

    // Semantics off
    semantics.dispose();
    await tester.pumpAndSettle();
    expect(tester.binding.pipelineOwner.semanticsOwner, isNull);

    // Semantics on
308
    semantics = SemanticsTester(tester);
309 310 311 312
    await tester.pumpAndSettle();
    expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull);

    semantics.dispose();
313
  }, semanticsEnabled: false);
314

315
  testWidgets('Supports all actions', (WidgetTester tester) async {
316
    final SemanticsTester semantics = SemanticsTester(tester);
317 318
    final List<SemanticsAction> performedActions = <SemanticsAction>[];

319 320 321
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
        semantics: CustomPainterSemantics(
322
          key: const ValueKey<int>(1),
Dan Field's avatar
Dan Field committed
323
          rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
324
          properties: SemanticsProperties(
325
            onDismiss: () => performedActions.add(SemanticsAction.dismiss),
326 327 328 329 330 331 332 333 334 335 336 337 338
            onTap: () => performedActions.add(SemanticsAction.tap),
            onLongPress: () => performedActions.add(SemanticsAction.longPress),
            onScrollLeft: () => performedActions.add(SemanticsAction.scrollLeft),
            onScrollRight: () => performedActions.add(SemanticsAction.scrollRight),
            onScrollUp: () => performedActions.add(SemanticsAction.scrollUp),
            onScrollDown: () => performedActions.add(SemanticsAction.scrollDown),
            onIncrease: () => performedActions.add(SemanticsAction.increase),
            onDecrease: () => performedActions.add(SemanticsAction.decrease),
            onCopy: () => performedActions.add(SemanticsAction.copy),
            onCut: () => performedActions.add(SemanticsAction.cut),
            onPaste: () => performedActions.add(SemanticsAction.paste),
            onMoveCursorForwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter),
            onMoveCursorBackwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter),
339 340
            onMoveCursorForwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByWord),
            onMoveCursorBackwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByWord),
341
            onSetSelection: (TextSelection _) => performedActions.add(SemanticsAction.setSelection),
342
            onSetText: (String text) => performedActions.add(SemanticsAction.setText),
343 344 345 346 347 348 349
            onDidGainAccessibilityFocus: () => performedActions.add(SemanticsAction.didGainAccessibilityFocus),
            onDidLoseAccessibilityFocus: () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus),
          ),
        ),
      ),
    ));
    final Set<SemanticsAction> allActions = SemanticsAction.values.values.toSet()
350
      ..remove(SemanticsAction.customAction) // customAction is not user-exposed.
351
      ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed
352 353

    const int expectedId = 2;
354
    final TestSemantics expectedSemantics = TestSemantics.root(
355
      children: <TestSemantics>[
356
        TestSemantics.rootChild(
357 358
          id: 1,
          children: <TestSemantics>[
359
            TestSemantics.rootChild(
360 361
              id: expectedId,
              rect: TestSemantics.fullScreen,
362
              actions: allActions.fold<int>(0, (int previous, SemanticsAction action) => previous | action.index),
363
            ),
364
          ],
365 366 367 368 369 370
        ),
      ],
    );
    expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true));

    // Do the actions work?
371
    final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!;
372
    int expectedLength = 1;
373
    for (final SemanticsAction action in allActions) {
374 375 376
      switch (action) {
        case SemanticsAction.moveCursorBackwardByCharacter:
        case SemanticsAction.moveCursorForwardByCharacter:
377 378
        case SemanticsAction.moveCursorBackwardByWord:
        case SemanticsAction.moveCursorForwardByWord:
379 380 381 382 383 384 385 386
          semanticsOwner.performAction(expectedId, action, true);
          break;
        case SemanticsAction.setSelection:
          semanticsOwner.performAction(expectedId, action, <String, int>{
            'base': 4,
            'extent': 5,
          });
          break;
387 388 389
        case SemanticsAction.setText:
          semanticsOwner.performAction(expectedId, action, 'text');
          break;
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        case SemanticsAction.copy:
        case SemanticsAction.customAction:
        case SemanticsAction.cut:
        case SemanticsAction.decrease:
        case SemanticsAction.didGainAccessibilityFocus:
        case SemanticsAction.didLoseAccessibilityFocus:
        case SemanticsAction.dismiss:
        case SemanticsAction.increase:
        case SemanticsAction.longPress:
        case SemanticsAction.paste:
        case SemanticsAction.scrollDown:
        case SemanticsAction.scrollLeft:
        case SemanticsAction.scrollRight:
        case SemanticsAction.scrollUp:
        case SemanticsAction.showOnScreen:
        case SemanticsAction.tap:
406
          semanticsOwner.performAction(expectedId, action);
407
          break;
408 409 410 411 412 413 414
      }
      expect(performedActions.length, expectedLength);
      expect(performedActions.last, action);
      expectedLength += 1;
    }

    semantics.dispose();
415
  });
416

417
  testWidgets('Supports all flags', (WidgetTester tester) async {
418
    final SemanticsTester semantics = SemanticsTester(tester);
419
    // checked state and toggled state are mutually exclusive.
420 421
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
422 423
        semantics: const CustomPainterSemantics(
          key: ValueKey<int>(1),
424
          rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
Dan Field's avatar
Dan Field committed
425
          properties: SemanticsProperties(
426 427 428
            enabled: true,
            checked: true,
            selected: true,
429
            hidden: true,
430
            button: true,
431
            slider: true,
432
            keyboardKey: true,
433
            link: true,
434
            textField: true,
435
            readOnly: true,
436
            focused: true,
437
            focusable: true,
438 439
            inMutuallyExclusiveGroup: true,
            header: true,
440
            obscured: true,
441
            multiline: true,
442 443
            scopesRoute: true,
            namesRoute: true,
444 445
            image: true,
            liveRegion: true,
446
            toggled: true,
447 448 449 450
          ),
        ),
      ),
    ));
451
    List<SemanticsFlag> flags = SemanticsFlag.values.values.toList();
452 453
    // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties]
    // therefore it has to be removed.
454 455 456
    flags
      ..remove(SemanticsFlag.hasImplicitScrolling)
      ..remove(SemanticsFlag.isCheckStateMixed);
457
    TestSemantics expectedSemantics = TestSemantics.root(
458
      children: <TestSemantics>[
459
        TestSemantics.rootChild(
460 461
            id: 1,
            children: <TestSemantics>[
462
              TestSemantics.rootChild(
463
                id: 2,
464
                rect: TestSemantics.fullScreen,
465
                flags: flags,
466
              ),
467
            ],
468 469 470 471 472
        ),
      ],
    );
    expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true));

473 474
    await tester.pumpWidget(CustomPaint(
      painter: _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
475 476
        semantics: const CustomPainterSemantics(
          key: ValueKey<int>(1),
477
          rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0),
Dan Field's avatar
Dan Field committed
478
          properties: SemanticsProperties(
479
            enabled: true,
480 481
            checked: false,
            mixed: true,
482 483 484 485
            toggled: true,
            selected: true,
            hidden: true,
            button: true,
486
            slider: true,
487
            keyboardKey: true,
488
            link: true,
489
            textField: true,
490
            readOnly: true,
491
            focused: true,
492
            focusable: true,
493 494 495
            inMutuallyExclusiveGroup: true,
            header: true,
            obscured: true,
496
            multiline: true,
497 498 499 500 501 502 503 504 505
            scopesRoute: true,
            namesRoute: true,
            image: true,
            liveRegion: true,
          ),
        ),
      ),
    ));
    flags = SemanticsFlag.values.values.toList();
506 507
    // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties]
    // therefore it has to be removed.
508 509 510
    flags
      ..remove(SemanticsFlag.hasImplicitScrolling)
      ..remove(SemanticsFlag.isChecked);
511
    expectedSemantics = TestSemantics.root(
512
      children: <TestSemantics>[
513
        TestSemantics.rootChild(
514 515
            id: 1,
            children: <TestSemantics>[
516
              TestSemantics.rootChild(
517 518 519 520
                id: 2,
                rect: TestSemantics.fullScreen,
                flags: flags,
              ),
521
            ],
522 523 524 525
        ),
      ],
    );
    expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true));
526
    semantics.dispose();
527
  });
528

529 530
  group('diffing', () {
    testWidgets('complains about duplicate keys', (WidgetTester tester) async {
531 532 533
      final SemanticsTester semanticsTester = SemanticsTester(tester);
      await tester.pumpWidget(CustomPaint(
        painter: _SemanticsDiffTest(<String>[
534 535 536 537 538 539 540 541
          'a-k',
          'a-k',
        ]),
      ));
      expect(tester.takeException(), isFlutterError);
      semanticsTester.dispose();
    });

542
    _testDiff('adds one item to an empty list', (_DiffTester tester) async {
543 544 545 546 547 548
      await tester.diff(
        from: <String>[],
        to: <String>['a'],
      );
    });

549
    _testDiff('removes the last item from the list', (_DiffTester tester) async {
550 551 552 553 554 555
      await tester.diff(
        from: <String>['a'],
        to: <String>[],
      );
    });

556
    _testDiff('appends one item at the end of a non-empty list', (_DiffTester tester) async {
557 558 559 560 561 562
      await tester.diff(
        from: <String>['a'],
        to: <String>['a', 'b'],
      );
    });

563
    _testDiff('prepends one item at the beginning of a non-empty list', (_DiffTester tester) async {
564 565 566 567 568 569
      await tester.diff(
        from: <String>['b'],
        to: <String>['a', 'b'],
      );
    });

570
    _testDiff('inserts one item in the middle of a list', (_DiffTester tester) async {
571 572 573 574 575 576 577 578 579 580 581 582 583
      await tester.diff(
        from: <String>[
          'a-k',
          'c-k',
        ],
        to: <String>[
          'a-k',
          'b-k',
          'c-k',
        ],
      );
    });

584
    _testDiff('removes one item from the middle of a list', (_DiffTester tester) async {
585 586 587 588 589 590 591 592 593 594 595 596 597
      await tester.diff(
        from: <String>[
          'a-k',
          'b-k',
          'c-k',
        ],
        to: <String>[
          'a-k',
          'c-k',
        ],
      );
    });

598
    _testDiff('swaps two items', (_DiffTester tester) async {
599 600 601 602 603 604 605 606 607 608 609 610
      await tester.diff(
        from: <String>[
          'a-k',
          'b-k',
        ],
        to: <String>[
          'b-k',
          'a-k',
        ],
      );
    });

611
    _testDiff('finds and moved one keyed item', (_DiffTester tester) async {
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
      await tester.diff(
        from: <String>[
          'a-k',
          'b',
          'c',
        ],
        to: <String>[
          'b',
          'c',
          'a-k',
        ],
      );
    });
  });

  testWidgets('rebuilds semantics upon resize', (WidgetTester tester) async {
628
    final SemanticsTester semanticsTester = SemanticsTester(tester);
629

630
    final _PainterWithSemantics painter = _PainterWithSemantics(
Dan Field's avatar
Dan Field committed
631
      semantics: const CustomPainterSemantics(
632
        rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
633
        properties: SemanticsProperties(
634 635 636 637 638 639
          label: 'background',
          textDirection: TextDirection.rtl,
        ),
      ),
    );

640
    final CustomPaint paint = CustomPaint(painter: painter);
641

642
    await tester.pumpWidget(SizedBox(
643 644 645 646 647 648 649 650
      height: 20.0,
      width: 20.0,
      child: paint,
    ));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0);
    expect(_PainterWithSemantics.buildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);

651
    await tester.pumpWidget(SizedBox(
652 653 654 655 656 657 658 659
      height: 20.0,
      width: 20.0,
      child: paint,
    ));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0);
    expect(_PainterWithSemantics.buildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);

660
    await tester.pumpWidget(SizedBox(
661 662 663 664 665 666 667 668 669 670 671 672
      height: 40.0,
      width: 40.0,
      child: paint,
    ));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0);
    expect(_PainterWithSemantics.buildSemanticsCallCount, 2);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);

    semanticsTester.dispose();
  });

  testWidgets('does not rebuild when shouldRebuildSemantics is false', (WidgetTester tester) async {
673
    final SemanticsTester semanticsTester = SemanticsTester(tester);
674

Dan Field's avatar
Dan Field committed
675
    const CustomPainterSemantics testSemantics = CustomPainterSemantics(
676
      rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
677
      properties: SemanticsProperties(
678 679 680 681 682
        label: 'background',
        textDirection: TextDirection.rtl,
      ),
    );

683
    await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(
684 685 686 687 688 689
      semantics: testSemantics,
    )));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0);
    expect(_PainterWithSemantics.buildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);

690
    await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(
691 692 693 694 695 696
      semantics: testSemantics,
    )));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.buildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);

Dan Field's avatar
Dan Field committed
697
    const CustomPainterSemantics testSemantics2 = CustomPainterSemantics(
698
      rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
Dan Field's avatar
Dan Field committed
699
      properties: SemanticsProperties(
700 701 702 703 704
        label: 'background',
        textDirection: TextDirection.rtl,
      ),
    );

705
    await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(
706 707 708
      semantics: testSemantics2,
    )));
    expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 2);
Dan Field's avatar
Dan Field committed
709 710
    expect(_PainterWithSemantics.buildSemanticsCallCount, 1);
    expect(_PainterWithSemantics.semanticsBuilderCallCount, 4);
711 712 713 714 715

    semanticsTester.dispose();
  });
}

716
void _testDiff(String description, Future<void> Function(_DiffTester tester) testFunction) {
717
  testWidgets(description, (WidgetTester tester) async {
718
    await testFunction(_DiffTester(tester));
719 720 721 722 723 724 725 726 727 728
  });
}

class _DiffTester {
  _DiffTester(this.tester);

  final WidgetTester tester;

  /// Creates an initial semantics list using the `from` list, then updates the
  /// list to the `to` list. This causes [RenderCustomPaint] to diff the two
729
  /// lists and apply the changes. This method asserts the changes were
730 731 732 733
  /// applied correctly, specifically:
  ///
  /// - checks that initial and final configurations are in the desired states.
  /// - checks that keyed nodes have stable IDs.
734
  Future<void> diff({ required List<String> from, required List<String> to }) async {
735
    final SemanticsTester semanticsTester = SemanticsTester(tester);
736 737

    TestSemantics createExpectations(List<String> labels) {
738
      return TestSemantics.root(
739
        children: <TestSemantics>[
740
          TestSemantics.rootChild(
741
            rect: TestSemantics.fullScreen,
742
            children: <TestSemantics>[
743
              for (final String label in labels)
744 745 746 747 748
                TestSemantics(
                  rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
                  label: label,
                ),
            ],
749 750 751 752 753
          ),
        ],
      );
    }

754 755
    await tester.pumpWidget(CustomPaint(
      painter: _SemanticsDiffTest(from),
756 757 758
    ));
    expect(semanticsTester, hasSemantics(createExpectations(from), ignoreId: true));

759
    SemanticsNode root = RendererBinding.instance.renderView.debugSemantics!;
760 761 762 763
    final Map<Key, int> idAssignments = <Key, int>{};
    root.visitChildren((SemanticsNode firstChild) {
      firstChild.visitChildren((SemanticsNode node) {
        if (node.key != null) {
764
          idAssignments[node.key!] = node.id;
765 766 767 768 769 770
        }
        return true;
      });
      return true;
    });

771 772
    await tester.pumpWidget(CustomPaint(
      painter: _SemanticsDiffTest(to),
773 774 775 776
    ));
    await tester.pumpAndSettle();
    expect(semanticsTester, hasSemantics(createExpectations(to), ignoreId: true));

777
    root = RendererBinding.instance.renderView.debugSemantics!;
778 779 780 781
    root.visitChildren((SemanticsNode firstChild) {
      firstChild.visitChildren((SemanticsNode node) {
        if (node.key != null && idAssignments[node.key] != null) {
          expect(idAssignments[node.key], node.id, reason:
782
            'Node with key ${node.key} was previously assigned ID ${idAssignments[node.key]}. '
783
            'After diffing the child list, its ID changed to ${node.id}. IDs must be stable.',
784
          );
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        }
        return true;
      });
      return true;
    });

    semanticsTester.dispose();
  }
}

class _SemanticsDiffTest extends CustomPainter {
  _SemanticsDiffTest(this.data);

  final List<String> data;

  @override
  void paint(Canvas canvas, Size size) {
    // We don't test painting.
  }

  @override
  SemanticsBuilderCallback get semanticsBuilder => buildSemantics;

  List<CustomPainterSemantics> buildSemantics(Size size) {
    final List<CustomPainterSemantics> semantics = <CustomPainterSemantics>[];
810
    for (final String label in data) {
811
      Key? key;
812
      if (label.endsWith('-k')) {
813
        key = ValueKey<String>(label);
814 815
      }
      semantics.add(
816
        CustomPainterSemantics(
Dan Field's avatar
Dan Field committed
817
          rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
818
          key: key,
819
          properties: SemanticsProperties(
820 821 822 823 824 825 826 827 828 829 830 831 832 833
            label: label,
            textDirection: TextDirection.rtl,
          ),
        ),
      );
    }
    return semantics;
  }

  @override
  bool shouldRepaint(_SemanticsDiffTest oldPainter) => true;
}

class _PainterWithSemantics extends CustomPainter {
834
  _PainterWithSemantics({ required this.semantics });
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

  final CustomPainterSemantics semantics;

  static int semanticsBuilderCallCount = 0;
  static int buildSemanticsCallCount = 0;
  static int shouldRebuildSemanticsCallCount = 0;

  @override
  void paint(Canvas canvas, Size size) {
    // We don't test painting.
  }

  @override
  SemanticsBuilderCallback get semanticsBuilder {
    semanticsBuilderCallCount += 1;
    return buildSemantics;
  }

  List<CustomPainterSemantics> buildSemantics(Size size) {
    buildSemanticsCallCount += 1;
    return <CustomPainterSemantics>[semantics];
  }

  @override
  bool shouldRepaint(_PainterWithSemantics oldPainter) {
    return true;
  }

  @override
  bool shouldRebuildSemantics(_PainterWithSemantics oldPainter) {
    shouldRebuildSemanticsCallCount += 1;
    return !identical(oldPainter.semantics, semantics);
  }
}

class _PainterWithoutSemantics extends CustomPainter {
  _PainterWithoutSemantics();

  @override
  void paint(Canvas canvas, Size size) {
    // We don't test painting.
  }

  @override
  bool shouldRepaint(_PainterWithSemantics oldPainter) => true;
}