fake_codec.dart 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2017 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.

import 'dart:async';
import 'dart:typed_data';
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.
16
class FakeCodec implements ui.Codec {
17 18
  FakeCodec._(this._frameCount, this._repetitionCount, this._frameInfos);

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

  /// 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;
30
    final List<ui.FrameInfo> frameInfos = List<ui.FrameInfo>(frameCount);
31
    for (int i = 0; i < frameCount; i += 1)
32
      frameInfos[i] = await codec.getNextFrame();
33
    return FakeCodec._(frameCount, codec.repetitionCount, frameInfos);
34 35 36 37 38 39 40 41 42 43 44
  }

  @override
  int get frameCount => _frameCount;

  @override
  int get repetitionCount => _repetitionCount;

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

  @override
  void dispose() { }
52
}