1 /*
2  * Copyright (C) 2022 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 package com.android.wallpaper.util
17 
18 import android.annotation.AttrRes
19 import android.annotation.ColorInt
20 import android.content.Context
21 import android.util.TypedValue
22 import androidx.core.content.ContextCompat
23 
24 object SystemColors {
25 
26     /**
27      * Returns the color by fetching the resId from the theme. Throws an exception when resource Id
28      * is not available in the theme.
29      */
30     @JvmStatic
31     @ColorInt
getColornull32     fun getColor(context: Context, @AttrRes resId: Int): Int {
33         val colorValue = TypedValue()
34         val theme = context.theme
35         if (theme.resolveAttribute(resId, colorValue, /* resolveRefs= */ true)) {
36             if (
37                 TypedValue.TYPE_FIRST_COLOR_INT <= colorValue.type &&
38                     colorValue.type <= TypedValue.TYPE_LAST_COLOR_INT
39             ) {
40                 return colorValue.data
41             }
42             if (colorValue.type == TypedValue.TYPE_STRING) {
43                 return ContextCompat.getColor(context, colorValue.resourceId)
44             }
45         }
46         throw IllegalArgumentException(
47             "Theme is missing expected color ${context.resources.getResourceName(resId)} " +
48                 "($resId) references a missing resource."
49         )
50     }
51 }
52