decoration_test.dart 17.4 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:typed_data';
7
import 'dart:ui' as ui show Image, ImageByteFormat, ColorFilter;
8 9

import 'package:flutter/foundation.dart';
10
import 'package:flutter/painting.dart';
11
import 'package:quiver/testing/async.dart';
12
import '../flutter_test_alternative.dart';
13 14 15

import '../painting/mocks_for_image_cache.dart';
import '../rendering/rendering_tester.dart';
16 17

class TestCanvas implements Canvas {
18 19 20 21
  TestCanvas([this.invocations]);

  final List<Invocation> invocations;

22
  @override
23 24 25
  void noSuchMethod(Invocation invocation) {
    invocations?.add(invocation);
  }
26 27 28 29 30
}

class SynchronousTestImageProvider extends ImageProvider<int> {
  @override
  Future<int> obtainKey(ImageConfiguration configuration) {
31
    return SynchronousFuture<int>(1);
32 33 34 35
  }

  @override
  ImageStreamCompleter load(int key) {
36 37
    return OneFrameImageStreamCompleter(
      SynchronousFuture<ImageInfo>(TestImageInfo(key, image: TestImage(), scale: 1.0))
38 39 40 41 42 43 44
    );
  }
}

class AsyncTestImageProvider extends ImageProvider<int> {
  @override
  Future<int> obtainKey(ImageConfiguration configuration) {
45
    return Future<int>.value(2);
46 47 48 49
  }

  @override
  ImageStreamCompleter load(int key) {
50 51
    return OneFrameImageStreamCompleter(
      Future<ImageInfo>.value(TestImageInfo(key))
52 53 54
    );
  }
}
55

56
class DelayedImageProvider extends ImageProvider<DelayedImageProvider> {
57
  final Completer<ImageInfo> _completer = Completer<ImageInfo>();
58 59

  @override
60
  Future<DelayedImageProvider> obtainKey(ImageConfiguration configuration) {
61
    return SynchronousFuture<DelayedImageProvider>(this);
62 63 64
  }

  @override
65
  ImageStreamCompleter load(DelayedImageProvider key) {
66
    return OneFrameImageStreamCompleter(_completer.future);
67 68 69
  }

  void complete() {
70
    _completer.complete(ImageInfo(image: TestImage()));
71 72 73
  }

  @override
74
  String toString() => '${describeIdentity(this)}()';
75 76
}

77
class TestImage implements ui.Image {
78 79 80 81 82 83 84 85
  @override
  int get width => 100;

  @override
  int get height => 100;

  @override
  void dispose() { }
86 87

  @override
88
  Future<ByteData> toByteData({ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) async {
89
    throw UnsupportedError('Cannot encode test image');
90
  }
91 92
}

93
void main() {
94
  TestRenderingFlutterBinding(); // initializes the imageCache
95

96
  test('Decoration.lerp()', () {
97 98
    const BoxDecoration a = BoxDecoration(color: Color(0xFFFFFFFF));
    const BoxDecoration b = BoxDecoration(color: Color(0x00000000));
99 100

    BoxDecoration c = Decoration.lerp(a, b, 0.0);
101
    expect(c.color, equals(a.color));
102 103

    c = Decoration.lerp(a, b, 0.25);
104
    expect(c.color, equals(Color.lerp(const Color(0xFFFFFFFF), const Color(0x00000000), 0.25)));
105 106

    c = Decoration.lerp(a, b, 1.0);
107
    expect(c.color, equals(b.color));
108
  });
109

110
  test('BoxDecorationImageListenerSync', () {
111 112
    final ImageProvider imageProvider = SynchronousTestImageProvider();
    final DecorationImage backgroundImage = DecorationImage(image: imageProvider);
113

114
    final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage);
115
    bool onChangedCalled = false;
116
    final BoxPainter boxPainter = boxDecoration.createBoxPainter(() {
117 118 119
      onChangedCalled = true;
    });

120
    final TestCanvas canvas = TestCanvas();
121
    const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size.zero);
122 123 124 125 126 127
    boxPainter.paint(canvas, Offset.zero, imageConfiguration);

    // The onChanged callback should not be invoked during the call to boxPainter.paint
    expect(onChangedCalled, equals(false));
  });

128
  test('BoxDecorationImageListenerAsync', () {
129 130 131
    FakeAsync().run((FakeAsync async) {
      final ImageProvider imageProvider = AsyncTestImageProvider();
      final DecorationImage backgroundImage = DecorationImage(image: imageProvider);
132

133
      final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage);
134
      bool onChangedCalled = false;
135
      final BoxPainter boxPainter = boxDecoration.createBoxPainter(() {
136 137 138
        onChangedCalled = true;
      });

139
      final TestCanvas canvas = TestCanvas();
140
      const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size.zero);
141 142 143 144 145 146 147 148
      boxPainter.paint(canvas, Offset.zero, imageConfiguration);

      // The onChanged callback should be invoked asynchronously.
      expect(onChangedCalled, equals(false));
      async.flushMicrotasks();
      expect(onChangedCalled, equals(true));
    });
  });
149 150 151

  // Regression test for https://github.com/flutter/flutter/issues/7289.
  // A reference test would be better.
152
  test('BoxDecoration backgroundImage clip', () {
153
    void testDecoration({ BoxShape shape = BoxShape.rectangle, BorderRadius borderRadius, bool expectClip}) {
154
      assert(shape != null);
155 156 157
      FakeAsync().run((FakeAsync async) {
        final DelayedImageProvider imageProvider = DelayedImageProvider();
        final DecorationImage backgroundImage = DecorationImage(image: imageProvider);
158

159
        final BoxDecoration boxDecoration = BoxDecoration(
160 161
          shape: shape,
          borderRadius: borderRadius,
162
          image: backgroundImage,
163 164
        );

165
        final List<Invocation> invocations = <Invocation>[];
166
        final TestCanvas canvas = TestCanvas(invocations);
167 168
        const ImageConfiguration imageConfiguration = ImageConfiguration(
            size: Size(100.0, 100.0)
169 170
        );
        bool onChangedCalled = false;
171
        final BoxPainter boxPainter = boxDecoration.createBoxPainter(() {
172 173 174
          onChangedCalled = true;
        });

175
        // _BoxDecorationPainter._paintDecorationImage() resolves the background
176 177 178 179 180 181 182 183 184 185
        // image and adds a listener to the resolved image stream.
        boxPainter.paint(canvas, Offset.zero, imageConfiguration);
        imageProvider.complete();

        // Run the listener which calls onChanged() which saves an internal
        // reference to the TestImage.
        async.flushMicrotasks();
        expect(onChangedCalled, isTrue);
        boxPainter.paint(canvas, Offset.zero, imageConfiguration);

Josh Soref's avatar
Josh Soref committed
186
        // We expect a clip to precede the drawImageRect call.
187
        final List<Invocation> commands = canvas.invocations.where((Invocation invocation) {
188 189
          return invocation.memberName == #clipPath || invocation.memberName == #drawImageRect;
        }).toList();
Josh Soref's avatar
Josh Soref committed
190
        if (expectClip) { // We expect a clip to precede the drawImageRect call.
191 192 193 194 195 196 197 198 199 200 201
          expect(commands.length, 2);
          expect(commands[0].memberName, equals(#clipPath));
          expect(commands[1].memberName, equals(#drawImageRect));
        } else {
          expect(commands.length, 1);
          expect(commands[0].memberName, equals(#drawImageRect));
        }
      });
    }

    testDecoration(shape: BoxShape.circle, expectClip: true);
202
    testDecoration(borderRadius: const BorderRadius.all(Radius.circular(16.0)), expectClip: true);
203 204
    testDecoration(expectClip: false);
  });
205 206

  test('DecorationImage test', () {
207
    const ColorFilter colorFilter = ui.ColorFilter.mode(Color(0xFF00FF00), BlendMode.src);
208 209
    final DecorationImage backgroundImage = DecorationImage(
      image: SynchronousTestImageProvider(),
210 211
      colorFilter: colorFilter,
      fit: BoxFit.contain,
212
      alignment: Alignment.bottomLeft,
213
      centerSlice: Rect.fromLTWH(10.0, 20.0, 30.0, 40.0),
214 215 216
      repeat: ImageRepeat.repeatY,
    );

217
    final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage);
218
    final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); });
219
    final TestCanvas canvas = TestCanvas(<Invocation>[]);
220
    boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0)));
221 222 223 224

    final Invocation call = canvas.invocations.singleWhere((Invocation call) => call.memberName == #drawImageNine);
    expect(call.isMethod, isTrue);
    expect(call.positionalArguments, hasLength(4));
225
    expect(call.positionalArguments[0], isInstanceOf<TestImage>());
226 227
    expect(call.positionalArguments[1], Rect.fromLTRB(10.0, 20.0, 40.0, 60.0));
    expect(call.positionalArguments[2], Rect.fromLTRB(0.0, 0.0, 100.0, 100.0));
228
    expect(call.positionalArguments[3], isInstanceOf<Paint>());
229 230 231 232
    expect(call.positionalArguments[3].isAntiAlias, false);
    expect(call.positionalArguments[3].colorFilter, colorFilter);
    expect(call.positionalArguments[3].filterQuality, FilterQuality.low);
  });
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

  test('BoxDecoration.lerp - shapes', () {
    // We don't lerp the shape, we just switch from one to the other at t=0.5.
    // (Use a ShapeDecoration and ShapeBorder if you want to lerp the shapes...)
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        -1.0,
      ),
      const BoxDecoration(shape: BoxShape.rectangle)
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        0.0,
      ),
      const BoxDecoration(shape: BoxShape.rectangle)
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        0.25,
      ),
      const BoxDecoration(shape: BoxShape.rectangle)
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        0.75,
      ),
      const BoxDecoration(shape: BoxShape.circle)
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        1.0,
      ),
      const BoxDecoration(shape: BoxShape.circle)
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(shape: BoxShape.rectangle),
        const BoxDecoration(shape: BoxShape.circle),
        2.0,
      ),
      const BoxDecoration(shape: BoxShape.circle)
    );
  });

  test('BoxDecoration.lerp - gradients', () {
288
    const Gradient gradient = LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xFFFFFFFF) ]);
289 290 291
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
292
        const BoxDecoration(gradient: gradient),
293 294
        -1.0,
      ),
295
      const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x00FFFFFF) ]))
296 297 298 299
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
300
        const BoxDecoration(gradient: gradient),
301 302 303 304 305 306 307
        0.0,
      ),
      const BoxDecoration()
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
308
        const BoxDecoration(gradient: gradient),
309 310
        0.25,
      ),
311
      const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x40FFFFFF) ]))
312 313 314 315
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
316
        const BoxDecoration(gradient: gradient),
317 318
        0.75,
      ),
319
      const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xBFFFFFFF) ]))
320 321 322 323
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
324
        const BoxDecoration(gradient: gradient),
325 326
        1.0,
      ),
327
      const BoxDecoration(gradient: gradient)
328 329 330 331
    );
    expect(
      BoxDecoration.lerp(
        const BoxDecoration(),
332
        const BoxDecoration(gradient: gradient),
333 334
        2.0,
      ),
335
      const BoxDecoration(gradient: gradient)
336 337
    );
  });
338 339

  test('Decoration.lerp with unrelated decorations', () {
340 341 342 343
    expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.0), isInstanceOf<FlutterLogoDecoration>()); // ignore: CONST_EVAL_THROWS_EXCEPTION
    expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.25), isInstanceOf<FlutterLogoDecoration>()); // ignore: CONST_EVAL_THROWS_EXCEPTION
    expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.75), isInstanceOf<BoxDecoration>()); // ignore: CONST_EVAL_THROWS_EXCEPTION
    expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 1.0), isInstanceOf<BoxDecoration>()); // ignore: CONST_EVAL_THROWS_EXCEPTION
344
  });
345 346 347

  test('paintImage BoxFit.none scale test', () {
    for (double scale = 1.0; scale <= 4.0; scale += 1.0) {
348
      final TestCanvas canvas = TestCanvas(<Invocation>[]);
349

350 351
      final Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0);
      final ui.Image image = TestImage();
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

      paintImage(
        canvas: canvas,
        rect: outputRect,
        image: image,
        scale: scale,
        alignment: Alignment.bottomRight,
        fit: BoxFit.none,
        repeat: ImageRepeat.noRepeat,
        flipHorizontally: false,
      );

      const Size imageSize = Size(100.0, 100.0);

      final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect);

      expect(call.isMethod, isTrue);
      expect(call.positionalArguments, hasLength(4));

      expect(call.positionalArguments[0], isInstanceOf<TestImage>());

      // sourceRect should contain all pixels of the source image
      expect(call.positionalArguments[1], Offset.zero & imageSize);

      // Image should be scaled down (divided by scale)
      // and be positioned in the bottom right of the outputRect
      final Size expectedTileSize = imageSize / scale;
379
      final Rect expectedTileRect = Rect.fromPoints(
380 381 382 383 384 385 386 387 388 389 390
        outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height),
        outputRect.bottomRight,
      );
      expect(call.positionalArguments[2], expectedTileRect);

      expect(call.positionalArguments[3], isInstanceOf<Paint>());
    }
  });

  test('paintImage BoxFit.scaleDown scale test', () {
    for (double scale = 1.0; scale <= 4.0; scale += 1.0) {
391
      final TestCanvas canvas = TestCanvas(<Invocation>[]);
392 393

      // container size > scaled image size
394 395
      final Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0);
      final ui.Image image = TestImage();
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

      paintImage(
        canvas: canvas,
        rect: outputRect,
        image: image,
        scale: scale,
        alignment: Alignment.bottomRight,
        fit: BoxFit.scaleDown,
        repeat: ImageRepeat.noRepeat,
        flipHorizontally: false,
      );

      const Size imageSize = Size(100.0, 100.0);

      final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect);

      expect(call.isMethod, isTrue);
      expect(call.positionalArguments, hasLength(4));

      expect(call.positionalArguments[0], isInstanceOf<TestImage>());

      // sourceRect should contain all pixels of the source image
      expect(call.positionalArguments[1], Offset.zero & imageSize);

      // Image should be scaled down (divided by scale)
      // and be positioned in the bottom right of the outputRect
      final Size expectedTileSize = imageSize / scale;
423
      final Rect expectedTileRect = Rect.fromPoints(
424 425 426 427 428 429 430 431 432 433
        outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height),
        outputRect.bottomRight,
      );
      expect(call.positionalArguments[2], expectedTileRect);

      expect(call.positionalArguments[3], isInstanceOf<Paint>());
    }
  });

  test('paintImage BoxFit.scaleDown test', () {
434
    final TestCanvas canvas = TestCanvas(<Invocation>[]);
435 436

    // container height (20 px) < scaled image height (50 px)
437 438
    final Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 20.0);
    final ui.Image image = TestImage();
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

    paintImage(
      canvas: canvas,
      rect: outputRect,
      image: image,
      scale: 2.0,
      alignment: Alignment.bottomRight,
      fit: BoxFit.scaleDown,
      repeat: ImageRepeat.noRepeat,
      flipHorizontally: false,
    );

    const Size imageSize = Size(100.0, 100.0);

    final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect);

    expect(call.isMethod, isTrue);
    expect(call.positionalArguments, hasLength(4));

    expect(call.positionalArguments[0], isInstanceOf<TestImage>());

    // sourceRect should contain all pixels of the source image
    expect(call.positionalArguments[1], Offset.zero & imageSize);

    // Image should be scaled down to fit in hejght
    // and be positioned in the bottom right of the outputRect
    const Size expectedTileSize = Size(20.0, 20.0);
466
    final Rect expectedTileRect = Rect.fromPoints(
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
      outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height),
      outputRect.bottomRight,
    );
    expect(call.positionalArguments[2], expectedTileRect);

    expect(call.positionalArguments[3], isInstanceOf<Paint>());
  });

  test('paintImage boxFit, scale and alignment test', () {
    const List<BoxFit> boxFits = <BoxFit>[
      BoxFit.contain,
      BoxFit.cover,
      BoxFit.fitWidth,
      BoxFit.fitWidth,
      BoxFit.fitHeight,
      BoxFit.none,
      BoxFit.scaleDown,
    ];

    for(BoxFit boxFit in boxFits) {
487
      final TestCanvas canvas = TestCanvas(<Invocation>[]);
488

489 490
      final Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0);
      final ui.Image image = TestImage();
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

      paintImage(
        canvas: canvas,
        rect: outputRect,
        image: image,
        scale: 3.0,
        alignment: Alignment.center,
        fit: boxFit,
        repeat: ImageRepeat.noRepeat,
        flipHorizontally: false,
      );

      final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect);

      expect(call.isMethod, isTrue);
      expect(call.positionalArguments, hasLength(4));

      // Image should be positioned in the center of the container
      expect(call.positionalArguments[2].center, outputRect.center);
    }
  });
512
}