1/*
2 * Copyright (C) 2017 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
17package com.android.launcher3.util;
18
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.graphics.Color;
22import android.graphics.ColorMatrix;
23import android.view.ContextThemeWrapper;
24
25/**
26 * Various utility methods associated with theming.
27 */
28public class Themes {
29
30    public static int getColorAccent(Context context) {
31        return getAttrColor(context, android.R.attr.colorAccent);
32    }
33
34    public static int getColorPrimary(Context context, int theme) {
35        return getAttrColor(new ContextThemeWrapper(context, theme), android.R.attr.colorPrimary);
36    }
37
38    public static int getAttrColor(Context context, int attr) {
39        TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
40        int colorAccent = ta.getColor(0, 0);
41        ta.recycle();
42        return colorAccent;
43    }
44
45    /**
46     * Returns the alpha corresponding to the theme attribute {@param attr}, in the range [0, 255].
47     */
48    public static int getAlpha(Context context, int attr) {
49        TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
50        float alpha = ta.getFloat(0, 0);
51        ta.recycle();
52        return (int) (255 * alpha + 0.5f);
53    }
54
55    /**
56     * Scales a color matrix such that, when applied to color R G B A, it produces R' G' B' A' where
57     * R' = r * R
58     * G' = g * G
59     * B' = b * B
60     * A' = a * A
61     *
62     * The matrix will, for instance, turn white into r g b a, and black will remain black.
63     *
64     * @param color The color r g b a
65     * @param target The ColorMatrix to scale
66     */
67    public static void setColorScaleOnMatrix(int color, ColorMatrix target) {
68        target.setScale(Color.red(color) / 255f, Color.green(color) / 255f,
69                Color.blue(color) / 255f, Color.alpha(color) / 255f);
70    }
71}
72