1 /* 2 * 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.glance.unit 18 19 import android.content.Context 20 import android.os.Build 21 import androidx.annotation.ColorInt 22 import androidx.annotation.ColorRes 23 import androidx.annotation.RequiresApi 24 import androidx.annotation.RestrictTo 25 import androidx.compose.ui.graphics.Color 26 27 /** Provider of colors for a glance composable's attributes. */ 28 interface ColorProvider { 29 /** Returns the color the provider would use in the given [context]. */ getColornull30 fun getColor(context: Context): Color 31 } 32 33 /** Returns a [ColorProvider] that always resolves to the [Color]. */ 34 fun ColorProvider(color: Color): ColorProvider { 35 return FixedColorProvider(color) 36 } 37 38 /** 39 * Returns a [ColorProvider] that resolves to the color resource. This should not be used outside of 40 * the Glance Libraries due to inconsistencies with regards to what process (app vs launcher) colors 41 * are resolved in 42 */ 43 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) ColorProvidernull44fun ColorProvider(@ColorRes resId: Int): ColorProvider { 45 return ResourceColorProvider(resId) 46 } 47 48 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 49 data class FixedColorProvider(val color: Color) : ColorProvider { getColornull50 override fun getColor(context: Context) = color 51 } 52 53 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 54 data class ResourceColorProvider(@ColorRes val resId: Int) : ColorProvider { 55 override fun getColor(context: Context): Color { 56 val androidColor = 57 if (Build.VERSION.SDK_INT >= 23) { 58 ColorProviderApi23Impl.getColor(context, resId) 59 } else { 60 @Suppress("DEPRECATION") // Resources.getColor must be used on < 23. 61 context.resources.getColor(resId) 62 } 63 return Color(androidColor) 64 } 65 } 66 67 @RequiresApi(23) 68 private object ColorProviderApi23Impl { 69 @ColorInt getColornull70 fun getColor(context: Context, @ColorRes resId: Int): Int { 71 return context.getColor(resId) 72 } 73 } 74