1 /*
<lambda>null2  * Copyright 2024 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.window.layout.adapter.extensions
18 
19 import android.content.Context
20 import androidx.annotation.GuardedBy
21 import androidx.core.util.Consumer
22 import androidx.window.RequiresWindowSdkExtension
23 import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
24 import androidx.window.layout.WindowLayoutInfo
25 import androidx.window.reflection.Consumer2
26 import java.util.concurrent.locks.ReentrantLock
27 import kotlin.concurrent.withLock
28 
29 /** A [Consumer] that handles multicasting to multiple [Consumer]s downstream. */
30 @RequiresWindowSdkExtension(2)
31 internal class MulticastConsumerApi2(private val context: Context) :
32     Consumer<OEMWindowLayoutInfo>, Consumer2<OEMWindowLayoutInfo> {
33     private val globalLock = ReentrantLock()
34 
35     @GuardedBy("globalLock") private var lastKnownValue: WindowLayoutInfo? = null
36     @GuardedBy("globalLock")
37     private val registeredListeners = mutableSetOf<Consumer<WindowLayoutInfo>>()
38 
39     override fun accept(value: OEMWindowLayoutInfo) {
40         globalLock.withLock {
41             val newValue = ExtensionsWindowLayoutInfoAdapter.translate(context, value)
42             lastKnownValue = newValue
43             registeredListeners.forEach { consumer -> consumer.accept(newValue) }
44         }
45     }
46 
47     fun addListener(listener: Consumer<WindowLayoutInfo>) {
48         globalLock.withLock {
49             lastKnownValue?.let { value -> listener.accept(value) }
50             registeredListeners.add(listener)
51         }
52     }
53 
54     fun removeListener(listener: Consumer<WindowLayoutInfo>) {
55         globalLock.withLock { registeredListeners.remove(listener) }
56     }
57 
58     fun isEmpty(): Boolean {
59         return registeredListeners.isEmpty()
60     }
61 }
62