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

import 'dart:ui' as ui show Codec, FrameInfo, instantiateImageCodec;

import 'package:flutter/foundation.dart';

/// A [ui.Codec] implementation for testing that pre-fetches all the image
/// frames, and provides synchronous [getNextFrame] implementation.
///
/// This is useful for running in the test Zone, where it is tricky to receive
/// callbacks originating from the IO thread.
14
class FakeCodec implements ui.Codec {
15 16
  FakeCodec._(this._frameCount, this._repetitionCount, this._frameInfos);

17 18 19 20
  final int _frameCount;
  final int _repetitionCount;
  final List<ui.FrameInfo> _frameInfos;
  int _nextFrame = 0;
21
  int _numFramesAsked = 0;
22 23 24 25 26 27 28

  /// Creates a FakeCodec from encoded image data.
  ///
  /// Only call this method outside of the test zone.
  static Future<FakeCodec> fromData(Uint8List data) async {
    final ui.Codec codec = await ui.instantiateImageCodec(data);
    final int frameCount = codec.frameCount;
29
    final List<ui.FrameInfo> frameInfos = <ui.FrameInfo>[];
30
    for (int i = 0; i < frameCount; i += 1) {
31
      frameInfos.add(await codec.getNextFrame());
32
    }
33
    return FakeCodec._(frameCount, codec.repetitionCount, frameInfos);
34 35 36 37 38 39 40 41
  }

  @override
  int get frameCount => _frameCount;

  @override
  int get repetitionCount => _repetitionCount;

42 43
  int get numFramesAsked => _numFramesAsked;

44 45
  @override
  Future<ui.FrameInfo> getNextFrame() {
46
    _numFramesAsked += 1;
47
    final SynchronousFuture<ui.FrameInfo> result =
48
      SynchronousFuture<ui.FrameInfo>(_frameInfos[_nextFrame]);
49 50 51
    _nextFrame = (_nextFrame + 1) % _frameCount;
    return result;
  }
52 53 54

  @override
  void dispose() { }
55
}