1 /*
2  * Copyright (C) 2020 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 com.android.systemui.controls
18 
19 import android.content.ComponentName
20 import android.graphics.drawable.Icon
21 import androidx.annotation.GuardedBy
22 import com.android.systemui.dagger.SysUISingleton
23 import javax.inject.Inject
24 
25 /**
26  * Icon cache for custom icons sent with controls.
27  *
28  * It assumes that only one component can be current at the time, to minimize the number of icons
29  * stored at a given time.
30  */
31 @SysUISingleton
32 class CustomIconCache @Inject constructor() {
33 
34     private var currentComponent: ComponentName? = null
35     @GuardedBy("cache")
36     private val cache: MutableMap<String, Icon> = LinkedHashMap()
37 
38     /**
39      * Store an icon in the cache.
40      *
41      * If the icons currently stored do not correspond to the component to be stored, the cache is
42      * cleared first.
43      */
storenull44     fun store(component: ComponentName, controlId: String, icon: Icon?) {
45         if (component != currentComponent) {
46             clear()
47             currentComponent = component
48         }
49         synchronized(cache) {
50             if (icon != null) {
51                 cache.put(controlId, icon)
52             } else {
53                 cache.remove(controlId)
54             }
55         }
56     }
57 
58     /**
59      * Retrieves a custom icon stored in the cache.
60      *
61      * It will return null if the component requested is not the one whose icons are stored, or if
62      * there is no icon cached for that id.
63      */
retrievenull64     fun retrieve(component: ComponentName, controlId: String): Icon? {
65         if (component != currentComponent) return null
66         return synchronized(cache) {
67             cache.get(controlId)
68         }
69     }
70 
clearnull71     private fun clear() {
72         synchronized(cache) {
73             cache.clear()
74         }
75     }
76 }