fake_codec.dart 1.71 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
// @dart = 2.8

7 8 9 10 11 12 13 14 15 16 17
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.
18
class FakeCodec implements ui.Codec {
19 20
  FakeCodec._(this._frameCount, this._repetitionCount, this._frameInfos);

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

  @override
  int get frameCount => _frameCount;

  @override
  int get repetitionCount => _repetitionCount;

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

  @override
  void dispose() { }
54
}