1 /*
<lambda>null2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.compose.ui.platform
18 
19 import android.view.Choreographer
20 import kotlin.coroutines.ContinuationInterceptor
21 import kotlin.coroutines.coroutineContext
22 import kotlinx.coroutines.suspendCancellableCoroutine
23 
24 class AndroidUiFrameClock
25 internal constructor(
26     val choreographer: Choreographer,
27     private val dispatcher: AndroidUiDispatcher?
28 ) : androidx.compose.runtime.MonotonicFrameClock {
29 
30     constructor(choreographer: Choreographer) : this(choreographer, null)
31 
32     override suspend fun <R> withFrameNanos(onFrame: (Long) -> R): R {
33         val uiDispatcher =
34             dispatcher ?: coroutineContext[ContinuationInterceptor] as? AndroidUiDispatcher
35         return suspendCancellableCoroutine { co ->
36             // Important: this callback won't throw, and AndroidUiDispatcher counts on it.
37             val callback =
38                 Choreographer.FrameCallback { frameTimeNanos ->
39                     co.resumeWith(runCatching { onFrame(frameTimeNanos) })
40                 }
41 
42             // If we're on an AndroidUiDispatcher then we post callback to happen *after*
43             // the greedy trampoline dispatch is complete.
44             // This means that onFrame will run on the current choreographer frame if one is
45             // already in progress, but withFrameNanos will *not* resume until the frame
46             // is complete. This prevents multiple calls to withFrameNanos immediately dispatching
47             // on the same frame.
48 
49             if (uiDispatcher != null && uiDispatcher.choreographer == choreographer) {
50                 uiDispatcher.postFrameCallback(callback)
51                 co.invokeOnCancellation { uiDispatcher.removeFrameCallback(callback) }
52             } else {
53                 choreographer.postFrameCallback(callback)
54                 co.invokeOnCancellation { choreographer.removeFrameCallback(callback) }
55             }
56         }
57     }
58 }
59