// Copyright 2015 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.

package org.domokit.vsync;

import android.view.Choreographer;

import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojom.vsync.VSyncProvider;

/**
 * Android implementation of VSyncProvider.
 */
public class VSyncProviderImpl implements VSyncProvider, Choreographer.FrameCallback {
    private Choreographer mChoreographer;
    private AwaitVSyncResponse mCallback;
    private MessagePipeHandle mPipe;

    public VSyncProviderImpl(MessagePipeHandle pipe) {
        mPipe = pipe;
        mChoreographer = Choreographer.getInstance();
    }

    @Override
    public void close() {}

    @Override
    public void onConnectionError(MojoException e) {}

    @Override
    public void awaitVSync(final AwaitVSyncResponse callback) {
        if (mCallback != null) {
            mPipe.close();
            return;
        }
        mCallback = callback;
        mChoreographer.postFrameCallback(this);
    }

    @Override
    public void doFrame(long frameTimeNanos) {
        mCallback.call(frameTimeNanos / 1000);
        mCallback = null;
    }
}

@@ -369,16 +369,45 @@
 vider;%0A%0A
+import java.util.ArrayList;%0A%0A
 /**%0A * A
@@ -591,16 +591,26 @@
 private 
+ArrayList%3C
 AwaitVSy
@@ -619,16 +619,17 @@
 Response
+%3E
  mCallba
@@ -626,24 +626,63 @@
 e%3E mCallback
+s = new ArrayList%3CAwaitVSyncResponse%3E()
 ;%0A    privat
@@ -1048,12 +1048,8 @@
     
-if (
 mCal
@@ -1057,107 +1057,67 @@
 back
- != null) %7B%0A            mPipe.close();%0A            return;%0A        %7D%0A        mCallback = callback;%0A
+s.add(callback);%0A        if (mCallbacks.size() == 1) %7B%0A    
     
@@ -1160,16 +1160,26 @@
 (this);%0A
+        %7D%0A
     %7D%0A%0A 
@@ -1250,23 +1250,31 @@
     
-mCallback.call(
+long frameTimeMicros = 
 fram
@@ -1290,17 +1290,16 @@
 s / 1000
-)
 ;%0A      
@@ -1304,24 +1304,137 @@
     
-mCallback = null
+for (AwaitVSyncResponse callback : mCallbacks) %7B%0A            callback.call(frameTimeMicros);%0A        %7D%0A        mCallbacks.clear()
 ;%0A  

Allow multiple callbacks in the VSyncProvider