1 /*
2 * Copyright (C) 2025 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.wm.shell.windowdecor.common
17
18 import android.annotation.ColorInt
19 import android.content.res.ColorStateList
20 import android.graphics.Color
21 import android.graphics.drawable.Drawable
22 import android.graphics.drawable.LayerDrawable
23 import android.graphics.drawable.ShapeDrawable
24 import android.graphics.drawable.shapes.RoundRectShape
25
26 /**
27 * Represents drawable insets, specifying the number of pixels to inset a drawable from its bounds.
28 */
29 data class DrawableInsets(val l: Int, val t: Int, val r: Int, val b: Int) {
30 constructor(vertical: Int = 0, horizontal: Int = 0) :
31 this(horizontal, vertical, horizontal, vertical)
32 constructor(vertical: Int = 0, horizontalLeft: Int = 0, horizontalRight: Int = 0) :
33 this(horizontalLeft, vertical, horizontalRight, vertical)
34 }
35
36 /**
37 * Replaces the alpha component of a color with the given alpha value.
38 */
39 @ColorInt
replaceColorAlphanull40 fun replaceColorAlpha(@ColorInt color: Int, alpha: Int): Int {
41 return Color.argb(
42 alpha,
43 Color.red(color),
44 Color.green(color),
45 Color.blue(color)
46 )
47 }
48
49 /**
50 * Creates a background drawable with specified color, corner radius, and insets.
51 */
createBackgroundDrawablenull52 fun createBackgroundDrawable(
53 @ColorInt color: Int, cornerRadius: Int, drawableInsets: DrawableInsets
54 ): Drawable = createBackgroundDrawable(
55 color,
56 FloatArray(8) { cornerRadius.toFloat() },
57 drawableInsets)
58
59 /**
60 * Creates a background drawable with specified color, corner radius, and insets.
61 */
createBackgroundDrawablenull62 fun createBackgroundDrawable(
63 @ColorInt color: Int, cornerRadius: FloatArray, drawableInsets: DrawableInsets
64 ): Drawable = LayerDrawable(arrayOf(
65 ShapeDrawable().apply {
66 shape = RoundRectShape(
67 cornerRadius,
68 /* inset= */ null,
69 /* innerRadii= */ null
70 )
71 setTintList(ColorStateList(
72 arrayOf(
73 intArrayOf(android.R.attr.state_hovered),
74 intArrayOf(android.R.attr.state_pressed),
75 ),
76 intArrayOf(
77 replaceColorAlpha(color, OPACITY_11),
78 replaceColorAlpha(color, OPACITY_15),
79 )
80 ))
81 }
<lambda>null82 )).apply {
83 require(numberOfLayers == 1) { "Must only contain one layer" }
84 setLayerInset(/* index= */ 0,
85 drawableInsets.l, drawableInsets.t, drawableInsets.r, drawableInsets.b)
86 }
87