• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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.statusbar;
18 
19 import static com.android.systemui.plugins.DarkIconDispatcher.getTint;
20 
21 import android.animation.Animator;
22 import android.animation.AnimatorListenerAdapter;
23 import android.animation.ObjectAnimator;
24 import android.animation.ValueAnimator;
25 import android.app.Notification;
26 import android.content.Context;
27 import android.content.pm.ApplicationInfo;
28 import android.content.res.ColorStateList;
29 import android.content.res.Configuration;
30 import android.content.res.Resources;
31 import android.graphics.Canvas;
32 import android.graphics.Color;
33 import android.graphics.ColorMatrixColorFilter;
34 import android.graphics.Paint;
35 import android.graphics.Rect;
36 import android.graphics.drawable.BitmapDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.graphics.drawable.Icon;
39 import android.os.Parcelable;
40 import android.os.UserHandle;
41 import android.service.notification.StatusBarNotification;
42 import android.text.TextUtils;
43 import android.util.AttributeSet;
44 import android.util.FloatProperty;
45 import android.util.Log;
46 import android.util.Property;
47 import android.util.TypedValue;
48 import android.view.ViewDebug;
49 import android.view.accessibility.AccessibilityEvent;
50 import android.view.animation.Interpolator;
51 
52 import androidx.core.graphics.ColorUtils;
53 
54 import com.android.internal.statusbar.StatusBarIcon;
55 import com.android.internal.util.ContrastColorUtil;
56 import com.android.systemui.Interpolators;
57 import com.android.systemui.R;
58 import com.android.systemui.statusbar.notification.NotificationIconDozeHelper;
59 import com.android.systemui.statusbar.notification.NotificationUtils;
60 
61 import java.text.NumberFormat;
62 import java.util.Arrays;
63 
64 public class StatusBarIconView extends AnimatedImageView implements StatusIconDisplayable {
65     public static final int NO_COLOR = 0;
66 
67     /**
68      * Multiply alpha values with (1+DARK_ALPHA_BOOST) when dozing. The chosen value boosts
69      * everything above 30% to 50%, making it appear on 1bit color depths.
70      */
71     private static final float DARK_ALPHA_BOOST = 0.67f;
72     /**
73      * Status icons are currently drawn with the intention of being 17dp tall, but we
74      * want to scale them (in a way that doesn't require an asset dump) down 2dp. So
75      * 17dp * (15 / 17) = 15dp, the new height. After the first call to {@link #reloadDimens} all
76      * values will be in px.
77      */
78     private float mSystemIconDesiredHeight = 15f;
79     private float mSystemIconIntrinsicHeight = 17f;
80     private float mSystemIconDefaultScale = mSystemIconDesiredHeight / mSystemIconIntrinsicHeight;
81     private final int ANIMATION_DURATION_FAST = 100;
82 
83     public static final int STATE_ICON = 0;
84     public static final int STATE_DOT = 1;
85     public static final int STATE_HIDDEN = 2;
86 
87     /**
88      * Maximum allowed byte count for an icon bitmap
89      * @see android.graphics.RecordingCanvas.MAX_BITMAP_SIZE
90      */
91     private static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB
92     /**
93      * Maximum allowed width or height for an icon drawable, if we can't get byte count
94      */
95     private static final int MAX_IMAGE_SIZE = 5000;
96 
97     private static final String TAG = "StatusBarIconView";
98     private static final Property<StatusBarIconView, Float> ICON_APPEAR_AMOUNT
99             = new FloatProperty<StatusBarIconView>("iconAppearAmount") {
100 
101         @Override
102         public void setValue(StatusBarIconView object, float value) {
103             object.setIconAppearAmount(value);
104         }
105 
106         @Override
107         public Float get(StatusBarIconView object) {
108             return object.getIconAppearAmount();
109         }
110     };
111     private static final Property<StatusBarIconView, Float> DOT_APPEAR_AMOUNT
112             = new FloatProperty<StatusBarIconView>("dot_appear_amount") {
113 
114         @Override
115         public void setValue(StatusBarIconView object, float value) {
116             object.setDotAppearAmount(value);
117         }
118 
119         @Override
120         public Float get(StatusBarIconView object) {
121             return object.getDotAppearAmount();
122         }
123     };
124 
125     private boolean mAlwaysScaleIcon;
126     private int mStatusBarIconDrawingSizeIncreased = 1;
127     private int mStatusBarIconDrawingSize = 1;
128     private int mStatusBarIconSize = 1;
129     private StatusBarIcon mIcon;
130     @ViewDebug.ExportedProperty private String mSlot;
131     private Drawable mNumberBackground;
132     private Paint mNumberPain;
133     private int mNumberX;
134     private int mNumberY;
135     private String mNumberText;
136     private StatusBarNotification mNotification;
137     private final boolean mBlocked;
138     private int mDensity;
139     private boolean mNightMode;
140     private float mIconScale = 1.0f;
141     private final Paint mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
142     private float mDotRadius;
143     private int mStaticDotRadius;
144     private int mVisibleState = STATE_ICON;
145     private float mIconAppearAmount = 1.0f;
146     private ObjectAnimator mIconAppearAnimator;
147     private ObjectAnimator mDotAnimator;
148     private float mDotAppearAmount;
149     private OnVisibilityChangedListener mOnVisibilityChangedListener;
150     private int mDrawableColor;
151     private int mIconColor;
152     private int mDecorColor;
153     private float mDozeAmount;
154     private ValueAnimator mColorAnimator;
155     private int mCurrentSetColor = NO_COLOR;
156     private int mAnimationStartColor = NO_COLOR;
157     private final ValueAnimator.AnimatorUpdateListener mColorUpdater
158             = animation -> {
159         int newColor = NotificationUtils.interpolateColors(mAnimationStartColor, mIconColor,
160                 animation.getAnimatedFraction());
161         setColorInternal(newColor);
162     };
163     private final NotificationIconDozeHelper mDozer;
164     private int mContrastedDrawableColor;
165     private int mCachedContrastBackgroundColor = NO_COLOR;
166     private float[] mMatrix;
167     private ColorMatrixColorFilter mMatrixColorFilter;
168     private boolean mIsInShelf;
169     private Runnable mLayoutRunnable;
170     private boolean mDismissed;
171     private Runnable mOnDismissListener;
172     private boolean mIncreasedSize;
173     private boolean mShowsConversation;
174 
StatusBarIconView(Context context, String slot, StatusBarNotification sbn)175     public StatusBarIconView(Context context, String slot, StatusBarNotification sbn) {
176         this(context, slot, sbn, false);
177     }
178 
StatusBarIconView(Context context, String slot, StatusBarNotification sbn, boolean blocked)179     public StatusBarIconView(Context context, String slot, StatusBarNotification sbn,
180             boolean blocked) {
181         super(context);
182         mDozer = new NotificationIconDozeHelper(context);
183         mBlocked = blocked;
184         mSlot = slot;
185         mNumberPain = new Paint();
186         mNumberPain.setTextAlign(Paint.Align.CENTER);
187         mNumberPain.setColor(context.getColor(R.drawable.notification_number_text_color));
188         mNumberPain.setAntiAlias(true);
189         setNotification(sbn);
190         setScaleType(ScaleType.CENTER);
191         mDensity = context.getResources().getDisplayMetrics().densityDpi;
192         Configuration configuration = context.getResources().getConfiguration();
193         mNightMode = (configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK)
194                 == Configuration.UI_MODE_NIGHT_YES;
195         initializeDecorColor();
196         reloadDimens();
197         maybeUpdateIconScaleDimens();
198     }
199 
StatusBarIconView(Context context, AttributeSet attrs)200     public StatusBarIconView(Context context, AttributeSet attrs) {
201         super(context, attrs);
202         mDozer = new NotificationIconDozeHelper(context);
203         mBlocked = false;
204         mAlwaysScaleIcon = true;
205         reloadDimens();
206         maybeUpdateIconScaleDimens();
207         mDensity = context.getResources().getDisplayMetrics().densityDpi;
208     }
209 
210     /** Should always be preceded by {@link #reloadDimens()} */
maybeUpdateIconScaleDimens()211     private void maybeUpdateIconScaleDimens() {
212         // We do not resize and scale system icons (on the right), only notification icons (on the
213         // left).
214         if (mNotification != null || mAlwaysScaleIcon) {
215             updateIconScaleForNotifications();
216         } else {
217             updateIconScaleForSystemIcons();
218         }
219     }
220 
updateIconScaleForNotifications()221     private void updateIconScaleForNotifications() {
222         final float imageBounds = mIncreasedSize ?
223                 mStatusBarIconDrawingSizeIncreased : mStatusBarIconDrawingSize;
224         final int outerBounds = mStatusBarIconSize;
225         mIconScale = imageBounds / (float)outerBounds;
226         updatePivot();
227     }
228 
229     // Makes sure that all icons are scaled to the same height (15dp). If we cannot get a height
230     // for the icon, it uses the default SCALE (15f / 17f) which is the old behavior
updateIconScaleForSystemIcons()231     private void updateIconScaleForSystemIcons() {
232         float iconHeight = getIconHeight();
233         if (iconHeight != 0) {
234             mIconScale = mSystemIconDesiredHeight / iconHeight;
235         } else {
236             mIconScale = mSystemIconDefaultScale;
237         }
238     }
239 
getIconHeight()240     private float getIconHeight() {
241         Drawable d = getDrawable();
242         if (d != null) {
243             return (float) getDrawable().getIntrinsicHeight();
244         } else {
245             return mSystemIconIntrinsicHeight;
246         }
247     }
248 
getIconScaleIncreased()249     public float getIconScaleIncreased() {
250         return (float) mStatusBarIconDrawingSizeIncreased / mStatusBarIconDrawingSize;
251     }
252 
getIconScale()253     public float getIconScale() {
254         return mIconScale;
255     }
256 
257     @Override
onConfigurationChanged(Configuration newConfig)258     protected void onConfigurationChanged(Configuration newConfig) {
259         super.onConfigurationChanged(newConfig);
260         int density = newConfig.densityDpi;
261         if (density != mDensity) {
262             mDensity = density;
263             reloadDimens();
264             updateDrawable();
265             maybeUpdateIconScaleDimens();
266         }
267         boolean nightMode = (newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK)
268                 == Configuration.UI_MODE_NIGHT_YES;
269         if (nightMode != mNightMode) {
270             mNightMode = nightMode;
271             initializeDecorColor();
272         }
273     }
274 
reloadDimens()275     private void reloadDimens() {
276         boolean applyRadius = mDotRadius == mStaticDotRadius;
277         Resources res = getResources();
278         mStaticDotRadius = res.getDimensionPixelSize(R.dimen.overflow_dot_radius);
279         mStatusBarIconSize = res.getDimensionPixelSize(R.dimen.status_bar_icon_size);
280         mStatusBarIconDrawingSizeIncreased =
281                 res.getDimensionPixelSize(R.dimen.status_bar_icon_drawing_size_dark);
282         mStatusBarIconDrawingSize =
283                 res.getDimensionPixelSize(R.dimen.status_bar_icon_drawing_size);
284         if (applyRadius) {
285             mDotRadius = mStaticDotRadius;
286         }
287         mSystemIconDesiredHeight = res.getDimension(
288                 com.android.internal.R.dimen.status_bar_system_icon_size);
289         mSystemIconIntrinsicHeight = res.getDimension(
290                 com.android.internal.R.dimen.status_bar_system_icon_intrinsic_size);
291         mSystemIconDefaultScale = mSystemIconDesiredHeight / mSystemIconIntrinsicHeight;
292     }
293 
setNotification(StatusBarNotification notification)294     public void setNotification(StatusBarNotification notification) {
295         mNotification = notification;
296         if (notification != null) {
297             setContentDescription(notification.getNotification());
298         }
299         maybeUpdateIconScaleDimens();
300     }
301 
streq(String a, String b)302     private static boolean streq(String a, String b) {
303         if (a == b) {
304             return true;
305         }
306         if (a == null && b != null) {
307             return false;
308         }
309         if (a != null && b == null) {
310             return false;
311         }
312         return a.equals(b);
313     }
314 
equalIcons(Icon a, Icon b)315     public boolean equalIcons(Icon a, Icon b) {
316         if (a == b) return true;
317         if (a.getType() != b.getType()) return false;
318         switch (a.getType()) {
319             case Icon.TYPE_RESOURCE:
320                 return a.getResPackage().equals(b.getResPackage()) && a.getResId() == b.getResId();
321             case Icon.TYPE_URI:
322             case Icon.TYPE_URI_ADAPTIVE_BITMAP:
323                 return a.getUriString().equals(b.getUriString());
324             default:
325                 return false;
326         }
327     }
328     /**
329      * Returns whether the set succeeded.
330      */
set(StatusBarIcon icon)331     public boolean set(StatusBarIcon icon) {
332         final boolean iconEquals = mIcon != null && equalIcons(mIcon.icon, icon.icon);
333         final boolean levelEquals = iconEquals
334                 && mIcon.iconLevel == icon.iconLevel;
335         final boolean visibilityEquals = mIcon != null
336                 && mIcon.visible == icon.visible;
337         final boolean numberEquals = mIcon != null
338                 && mIcon.number == icon.number;
339         mIcon = icon.clone();
340         setContentDescription(icon.contentDescription);
341         if (!iconEquals) {
342             if (!updateDrawable(false /* no clear */)) return false;
343             // we have to clear the grayscale tag since it may have changed
344             setTag(R.id.icon_is_grayscale, null);
345             // Maybe set scale based on icon height
346             maybeUpdateIconScaleDimens();
347         }
348         if (!levelEquals) {
349             setImageLevel(icon.iconLevel);
350         }
351 
352         if (!numberEquals) {
353             if (icon.number > 0 && getContext().getResources().getBoolean(
354                         R.bool.config_statusBarShowNumber)) {
355                 if (mNumberBackground == null) {
356                     mNumberBackground = getContext().getResources().getDrawable(
357                             R.drawable.ic_notification_overlay);
358                 }
359                 placeNumber();
360             } else {
361                 mNumberBackground = null;
362                 mNumberText = null;
363             }
364             invalidate();
365         }
366         if (!visibilityEquals) {
367             setVisibility(icon.visible && !mBlocked ? VISIBLE : GONE);
368         }
369         return true;
370     }
371 
updateDrawable()372     public void updateDrawable() {
373         updateDrawable(true /* with clear */);
374     }
375 
updateDrawable(boolean withClear)376     private boolean updateDrawable(boolean withClear) {
377         if (mIcon == null) {
378             return false;
379         }
380         Drawable drawable;
381         try {
382             drawable = getIcon(mIcon);
383         } catch (OutOfMemoryError e) {
384             Log.w(TAG, "OOM while inflating " + mIcon.icon + " for slot " + mSlot);
385             return false;
386         }
387 
388         if (drawable == null) {
389             Log.w(TAG, "No icon for slot " + mSlot + "; " + mIcon.icon);
390             return false;
391         }
392 
393         if (drawable instanceof BitmapDrawable && ((BitmapDrawable) drawable).getBitmap() != null) {
394             // If it's a bitmap we can check the size directly
395             int byteCount = ((BitmapDrawable) drawable).getBitmap().getByteCount();
396             if (byteCount > MAX_BITMAP_SIZE) {
397                 Log.w(TAG, "Drawable is too large (" + byteCount + " bytes) " + mIcon);
398                 return false;
399             }
400         } else if (drawable.getIntrinsicWidth() > MAX_IMAGE_SIZE
401                 || drawable.getIntrinsicHeight() > MAX_IMAGE_SIZE) {
402             // Otherwise, check dimensions
403             Log.w(TAG, "Drawable is too large (" + drawable.getIntrinsicWidth() + "x"
404                     + drawable.getIntrinsicHeight() + ") " + mIcon);
405             return false;
406         }
407 
408         if (withClear) {
409             setImageDrawable(null);
410         }
411         setImageDrawable(drawable);
412         return true;
413     }
414 
getSourceIcon()415     public Icon getSourceIcon() {
416         return mIcon.icon;
417     }
418 
getIcon(StatusBarIcon icon)419     private Drawable getIcon(StatusBarIcon icon) {
420         return getIcon(getContext(), icon);
421     }
422 
423     /**
424      * Returns the right icon to use for this item
425      *
426      * @param context Context to use to get resources
427      * @return Drawable for this item, or null if the package or item could not
428      *         be found
429      */
getIcon(Context context, StatusBarIcon statusBarIcon)430     public static Drawable getIcon(Context context, StatusBarIcon statusBarIcon) {
431         int userId = statusBarIcon.user.getIdentifier();
432         if (userId == UserHandle.USER_ALL) {
433             userId = UserHandle.USER_SYSTEM;
434         }
435 
436         Drawable icon = statusBarIcon.icon.loadDrawableAsUser(context, userId);
437 
438         TypedValue typedValue = new TypedValue();
439         context.getResources().getValue(R.dimen.status_bar_icon_scale_factor, typedValue, true);
440         float scaleFactor = typedValue.getFloat();
441 
442         // No need to scale the icon, so return it as is.
443         if (scaleFactor == 1.f) {
444             return icon;
445         }
446 
447         return new ScalingDrawableWrapper(icon, scaleFactor);
448     }
449 
getStatusBarIcon()450     public StatusBarIcon getStatusBarIcon() {
451         return mIcon;
452     }
453 
454     @Override
onInitializeAccessibilityEvent(AccessibilityEvent event)455     public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
456         super.onInitializeAccessibilityEvent(event);
457         if (mNotification != null) {
458             event.setParcelableData(mNotification.getNotification());
459         }
460     }
461 
462     @Override
onSizeChanged(int w, int h, int oldw, int oldh)463     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
464         super.onSizeChanged(w, h, oldw, oldh);
465         if (mNumberBackground != null) {
466             placeNumber();
467         }
468     }
469 
470     @Override
onRtlPropertiesChanged(int layoutDirection)471     public void onRtlPropertiesChanged(int layoutDirection) {
472         super.onRtlPropertiesChanged(layoutDirection);
473         updateDrawable();
474     }
475 
476     @Override
onDraw(Canvas canvas)477     protected void onDraw(Canvas canvas) {
478         if (mIconAppearAmount > 0.0f) {
479             canvas.save();
480             canvas.scale(mIconScale * mIconAppearAmount, mIconScale * mIconAppearAmount,
481                     getWidth() / 2, getHeight() / 2);
482             super.onDraw(canvas);
483             canvas.restore();
484         }
485 
486         if (mNumberBackground != null) {
487             mNumberBackground.draw(canvas);
488             canvas.drawText(mNumberText, mNumberX, mNumberY, mNumberPain);
489         }
490         if (mDotAppearAmount != 0.0f) {
491             float radius;
492             float alpha = Color.alpha(mDecorColor) / 255.f;
493             if (mDotAppearAmount <= 1.0f) {
494                 radius = mDotRadius * mDotAppearAmount;
495             } else {
496                 float fadeOutAmount = mDotAppearAmount - 1.0f;
497                 alpha = alpha * (1.0f - fadeOutAmount);
498                 radius = NotificationUtils.interpolate(mDotRadius, getWidth() / 4, fadeOutAmount);
499             }
500             mDotPaint.setAlpha((int) (alpha * 255));
501             canvas.drawCircle(mStatusBarIconSize / 2, getHeight() / 2, radius, mDotPaint);
502         }
503     }
504 
505     @Override
debug(int depth)506     protected void debug(int depth) {
507         super.debug(depth);
508         Log.d("View", debugIndent(depth) + "slot=" + mSlot);
509         Log.d("View", debugIndent(depth) + "icon=" + mIcon);
510     }
511 
placeNumber()512     void placeNumber() {
513         final String str;
514         final int tooBig = getContext().getResources().getInteger(
515                 android.R.integer.status_bar_notification_info_maxnum);
516         if (mIcon.number > tooBig) {
517             str = getContext().getResources().getString(
518                         android.R.string.status_bar_notification_info_overflow);
519         } else {
520             NumberFormat f = NumberFormat.getIntegerInstance();
521             str = f.format(mIcon.number);
522         }
523         mNumberText = str;
524 
525         final int w = getWidth();
526         final int h = getHeight();
527         final Rect r = new Rect();
528         mNumberPain.getTextBounds(str, 0, str.length(), r);
529         final int tw = r.right - r.left;
530         final int th = r.bottom - r.top;
531         mNumberBackground.getPadding(r);
532         int dw = r.left + tw + r.right;
533         if (dw < mNumberBackground.getMinimumWidth()) {
534             dw = mNumberBackground.getMinimumWidth();
535         }
536         mNumberX = w-r.right-((dw-r.right-r.left)/2);
537         int dh = r.top + th + r.bottom;
538         if (dh < mNumberBackground.getMinimumWidth()) {
539             dh = mNumberBackground.getMinimumWidth();
540         }
541         mNumberY = h-r.bottom-((dh-r.top-th-r.bottom)/2);
542         mNumberBackground.setBounds(w-dw, h-dh, w, h);
543     }
544 
setContentDescription(Notification notification)545     private void setContentDescription(Notification notification) {
546         if (notification != null) {
547             String d = contentDescForNotification(mContext, notification);
548             if (!TextUtils.isEmpty(d)) {
549                 setContentDescription(d);
550             }
551         }
552     }
553 
toString()554     public String toString() {
555         return "StatusBarIconView(slot=" + mSlot + " icon=" + mIcon
556             + " notification=" + mNotification + ")";
557     }
558 
getNotification()559     public StatusBarNotification getNotification() {
560         return mNotification;
561     }
562 
getSlot()563     public String getSlot() {
564         return mSlot;
565     }
566 
567 
contentDescForNotification(Context c, Notification n)568     public static String contentDescForNotification(Context c, Notification n) {
569         String appName = "";
570         try {
571             Notification.Builder builder = Notification.Builder.recoverBuilder(c, n);
572             appName = builder.loadHeaderAppName();
573         } catch (RuntimeException e) {
574             Log.e(TAG, "Unable to recover builder", e);
575             // Trying to get the app name from the app info instead.
576             Parcelable appInfo = n.extras.getParcelable(
577                     Notification.EXTRA_BUILDER_APPLICATION_INFO);
578             if (appInfo instanceof ApplicationInfo) {
579                 appName = String.valueOf(((ApplicationInfo) appInfo).loadLabel(
580                         c.getPackageManager()));
581             }
582         }
583 
584         CharSequence title = n.extras.getCharSequence(Notification.EXTRA_TITLE);
585         CharSequence text = n.extras.getCharSequence(Notification.EXTRA_TEXT);
586         CharSequence ticker = n.tickerText;
587 
588         // Some apps just put the app name into the title
589         CharSequence titleOrText = TextUtils.equals(title, appName) ? text : title;
590 
591         CharSequence desc = !TextUtils.isEmpty(titleOrText) ? titleOrText
592                 : !TextUtils.isEmpty(ticker) ? ticker : "";
593 
594         return c.getString(R.string.accessibility_desc_notification_icon, appName, desc);
595     }
596 
597     /**
598      * Set the color that is used to draw decoration like the overflow dot. This will not be applied
599      * to the drawable.
600      */
setDecorColor(int iconTint)601     public void setDecorColor(int iconTint) {
602         mDecorColor = iconTint;
603         updateDecorColor();
604     }
605 
initializeDecorColor()606     private void initializeDecorColor() {
607         if (mNotification != null) {
608             setDecorColor(getContext().getColor(mNightMode
609                     ? com.android.internal.R.color.notification_default_color_dark
610                     : com.android.internal.R.color.notification_default_color_light));
611         }
612     }
613 
updateDecorColor()614     private void updateDecorColor() {
615         int color = NotificationUtils.interpolateColors(mDecorColor, Color.WHITE, mDozeAmount);
616         if (mDotPaint.getColor() != color) {
617             mDotPaint.setColor(color);
618 
619             if (mDotAppearAmount != 0) {
620                 invalidate();
621             }
622         }
623     }
624 
625     /**
626      * Set the static color that should be used for the drawable of this icon if it's not
627      * transitioning this also immediately sets the color.
628      */
setStaticDrawableColor(int color)629     public void setStaticDrawableColor(int color) {
630         mDrawableColor = color;
631         setColorInternal(color);
632         updateContrastedStaticColor();
633         mIconColor = color;
634         mDozer.setColor(color);
635     }
636 
setColorInternal(int color)637     private void setColorInternal(int color) {
638         mCurrentSetColor = color;
639         updateIconColor();
640     }
641 
updateIconColor()642     private void updateIconColor() {
643         if (mShowsConversation) {
644             setColorFilter(null);
645             return;
646         }
647 
648         if (mCurrentSetColor != NO_COLOR) {
649             if (mMatrixColorFilter == null) {
650                 mMatrix = new float[4 * 5];
651                 mMatrixColorFilter = new ColorMatrixColorFilter(mMatrix);
652             }
653             int color = NotificationUtils.interpolateColors(
654                     mCurrentSetColor, Color.WHITE, mDozeAmount);
655             updateTintMatrix(mMatrix, color, DARK_ALPHA_BOOST * mDozeAmount);
656             mMatrixColorFilter.setColorMatrixArray(mMatrix);
657             setColorFilter(null);  // setColorFilter only invalidates if the instance changed.
658             setColorFilter(mMatrixColorFilter);
659         } else {
660             mDozer.updateGrayscale(this, mDozeAmount);
661         }
662     }
663 
664     /**
665      * Updates {@param array} such that it represents a matrix that changes RGB to {@param color}
666      * and multiplies the alpha channel with the color's alpha+{@param alphaBoost}.
667      */
updateTintMatrix(float[] array, int color, float alphaBoost)668     private static void updateTintMatrix(float[] array, int color, float alphaBoost) {
669         Arrays.fill(array, 0);
670         array[4] = Color.red(color);
671         array[9] = Color.green(color);
672         array[14] = Color.blue(color);
673         array[18] = Color.alpha(color) / 255f + alphaBoost;
674     }
675 
setIconColor(int iconColor, boolean animate)676     public void setIconColor(int iconColor, boolean animate) {
677         if (mIconColor != iconColor) {
678             mIconColor = iconColor;
679             if (mColorAnimator != null) {
680                 mColorAnimator.cancel();
681             }
682             if (mCurrentSetColor == iconColor) {
683                 return;
684             }
685             if (animate && mCurrentSetColor != NO_COLOR) {
686                 mAnimationStartColor = mCurrentSetColor;
687                 mColorAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
688                 mColorAnimator.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
689                 mColorAnimator.setDuration(ANIMATION_DURATION_FAST);
690                 mColorAnimator.addUpdateListener(mColorUpdater);
691                 mColorAnimator.addListener(new AnimatorListenerAdapter() {
692                     @Override
693                     public void onAnimationEnd(Animator animation) {
694                         mColorAnimator = null;
695                         mAnimationStartColor = NO_COLOR;
696                     }
697                 });
698                 mColorAnimator.start();
699             } else {
700                 setColorInternal(iconColor);
701             }
702         }
703     }
704 
getStaticDrawableColor()705     public int getStaticDrawableColor() {
706         return mDrawableColor;
707     }
708 
709     /**
710      * A drawable color that passes GAR on a specific background.
711      * This value is cached.
712      *
713      * @param backgroundColor Background to test against.
714      * @return GAR safe version of {@link StatusBarIconView#getStaticDrawableColor()}.
715      */
getContrastedStaticDrawableColor(int backgroundColor)716     int getContrastedStaticDrawableColor(int backgroundColor) {
717         if (mCachedContrastBackgroundColor != backgroundColor) {
718             mCachedContrastBackgroundColor = backgroundColor;
719             updateContrastedStaticColor();
720         }
721         return mContrastedDrawableColor;
722     }
723 
updateContrastedStaticColor()724     private void updateContrastedStaticColor() {
725         if (Color.alpha(mCachedContrastBackgroundColor) != 255) {
726             mContrastedDrawableColor = mDrawableColor;
727             return;
728         }
729         // We'll modify the color if it doesn't pass GAR
730         int contrastedColor = mDrawableColor;
731         if (!ContrastColorUtil.satisfiesTextContrast(mCachedContrastBackgroundColor,
732                 contrastedColor)) {
733             float[] hsl = new float[3];
734             ColorUtils.colorToHSL(mDrawableColor, hsl);
735             // This is basically a light grey, pushing the color will only distort it.
736             // Best thing to do in here is to fallback to the default color.
737             if (hsl[1] < 0.2f) {
738                 contrastedColor = Notification.COLOR_DEFAULT;
739             }
740             boolean isDark = !ContrastColorUtil.isColorLight(mCachedContrastBackgroundColor);
741             contrastedColor = ContrastColorUtil.resolveContrastColor(mContext,
742                     contrastedColor, mCachedContrastBackgroundColor, isDark);
743         }
744         mContrastedDrawableColor = contrastedColor;
745     }
746 
747     @Override
setVisibleState(int state)748     public void setVisibleState(int state) {
749         setVisibleState(state, true /* animate */, null /* endRunnable */);
750     }
751 
setVisibleState(int state, boolean animate)752     public void setVisibleState(int state, boolean animate) {
753         setVisibleState(state, animate, null);
754     }
755 
756     @Override
hasOverlappingRendering()757     public boolean hasOverlappingRendering() {
758         return false;
759     }
760 
setVisibleState(int visibleState, boolean animate, Runnable endRunnable)761     public void setVisibleState(int visibleState, boolean animate, Runnable endRunnable) {
762         setVisibleState(visibleState, animate, endRunnable, 0);
763     }
764 
765     /**
766      * Set the visibleState of this view.
767      *
768      * @param visibleState The new state.
769      * @param animate Should we animate?
770      * @param endRunnable The runnable to run at the end.
771      * @param duration The duration of an animation or 0 if the default should be taken.
772      */
setVisibleState(int visibleState, boolean animate, Runnable endRunnable, long duration)773     public void setVisibleState(int visibleState, boolean animate, Runnable endRunnable,
774             long duration) {
775         boolean runnableAdded = false;
776         if (visibleState != mVisibleState) {
777             mVisibleState = visibleState;
778             if (mIconAppearAnimator != null) {
779                 mIconAppearAnimator.cancel();
780             }
781             if (mDotAnimator != null) {
782                 mDotAnimator.cancel();
783             }
784             if (animate) {
785                 float targetAmount = 0.0f;
786                 Interpolator interpolator = Interpolators.FAST_OUT_LINEAR_IN;
787                 if (visibleState == STATE_ICON) {
788                     targetAmount = 1.0f;
789                     interpolator = Interpolators.LINEAR_OUT_SLOW_IN;
790                 }
791                 float currentAmount = getIconAppearAmount();
792                 if (targetAmount != currentAmount) {
793                     mIconAppearAnimator = ObjectAnimator.ofFloat(this, ICON_APPEAR_AMOUNT,
794                             currentAmount, targetAmount);
795                     mIconAppearAnimator.setInterpolator(interpolator);
796                     mIconAppearAnimator.setDuration(duration == 0 ? ANIMATION_DURATION_FAST
797                             : duration);
798                     mIconAppearAnimator.addListener(new AnimatorListenerAdapter() {
799                         @Override
800                         public void onAnimationEnd(Animator animation) {
801                             mIconAppearAnimator = null;
802                             runRunnable(endRunnable);
803                         }
804                     });
805                     mIconAppearAnimator.start();
806                     runnableAdded = true;
807                 }
808 
809                 targetAmount = visibleState == STATE_ICON ? 2.0f : 0.0f;
810                 interpolator = Interpolators.FAST_OUT_LINEAR_IN;
811                 if (visibleState == STATE_DOT) {
812                     targetAmount = 1.0f;
813                     interpolator = Interpolators.LINEAR_OUT_SLOW_IN;
814                 }
815                 currentAmount = getDotAppearAmount();
816                 if (targetAmount != currentAmount) {
817                     mDotAnimator = ObjectAnimator.ofFloat(this, DOT_APPEAR_AMOUNT,
818                             currentAmount, targetAmount);
819                     mDotAnimator.setInterpolator(interpolator);;
820                     mDotAnimator.setDuration(duration == 0 ? ANIMATION_DURATION_FAST
821                             : duration);
822                     final boolean runRunnable = !runnableAdded;
823                     mDotAnimator.addListener(new AnimatorListenerAdapter() {
824                         @Override
825                         public void onAnimationEnd(Animator animation) {
826                             mDotAnimator = null;
827                             if (runRunnable) {
828                                 runRunnable(endRunnable);
829                             }
830                         }
831                     });
832                     mDotAnimator.start();
833                     runnableAdded = true;
834                 }
835             } else {
836                 setIconAppearAmount(visibleState == STATE_ICON ? 1.0f : 0.0f);
837                 setDotAppearAmount(visibleState == STATE_DOT ? 1.0f
838                         : visibleState == STATE_ICON ? 2.0f
839                         : 0.0f);
840             }
841         }
842         if (!runnableAdded) {
843             runRunnable(endRunnable);
844         }
845     }
846 
runRunnable(Runnable runnable)847     private void runRunnable(Runnable runnable) {
848         if (runnable != null) {
849             runnable.run();
850         }
851     }
852 
setIconAppearAmount(float iconAppearAmount)853     public void setIconAppearAmount(float iconAppearAmount) {
854         if (mIconAppearAmount != iconAppearAmount) {
855             mIconAppearAmount = iconAppearAmount;
856             invalidate();
857         }
858     }
859 
getIconAppearAmount()860     public float getIconAppearAmount() {
861         return mIconAppearAmount;
862     }
863 
getVisibleState()864     public int getVisibleState() {
865         return mVisibleState;
866     }
867 
setDotAppearAmount(float dotAppearAmount)868     public void setDotAppearAmount(float dotAppearAmount) {
869         if (mDotAppearAmount != dotAppearAmount) {
870             mDotAppearAmount = dotAppearAmount;
871             invalidate();
872         }
873     }
874 
875     @Override
setVisibility(int visibility)876     public void setVisibility(int visibility) {
877         super.setVisibility(visibility);
878         if (mOnVisibilityChangedListener != null) {
879             mOnVisibilityChangedListener.onVisibilityChanged(visibility);
880         }
881     }
882 
getDotAppearAmount()883     public float getDotAppearAmount() {
884         return mDotAppearAmount;
885     }
886 
setOnVisibilityChangedListener(OnVisibilityChangedListener listener)887     public void setOnVisibilityChangedListener(OnVisibilityChangedListener listener) {
888         mOnVisibilityChangedListener = listener;
889     }
890 
setDozing(boolean dozing, boolean fade, long delay)891     public void setDozing(boolean dozing, boolean fade, long delay) {
892         mDozer.setDozing(f -> {
893             mDozeAmount = f;
894             updateDecorColor();
895             updateIconColor();
896             updateAllowAnimation();
897         }, dozing, fade, delay, this);
898     }
899 
updateAllowAnimation()900     private void updateAllowAnimation() {
901         if (mDozeAmount == 0 || mDozeAmount == 1) {
902             setAllowAnimation(mDozeAmount == 0);
903         }
904     }
905 
906     /**
907      * This method returns the drawing rect for the view which is different from the regular
908      * drawing rect, since we layout all children at position 0 and usually the translation is
909      * neglected. The standard implementation doesn't account for translation.
910      *
911      * @param outRect The (scrolled) drawing bounds of the view.
912      */
913     @Override
getDrawingRect(Rect outRect)914     public void getDrawingRect(Rect outRect) {
915         super.getDrawingRect(outRect);
916         float translationX = getTranslationX();
917         float translationY = getTranslationY();
918         outRect.left += translationX;
919         outRect.right += translationX;
920         outRect.top += translationY;
921         outRect.bottom += translationY;
922     }
923 
setIsInShelf(boolean isInShelf)924     public void setIsInShelf(boolean isInShelf) {
925         mIsInShelf = isInShelf;
926     }
927 
isInShelf()928     public boolean isInShelf() {
929         return mIsInShelf;
930     }
931 
932     @Override
onLayout(boolean changed, int left, int top, int right, int bottom)933     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
934         super.onLayout(changed, left, top, right, bottom);
935         if (mLayoutRunnable != null) {
936             mLayoutRunnable.run();
937             mLayoutRunnable = null;
938         }
939         updatePivot();
940     }
941 
updatePivot()942     private void updatePivot() {
943         if (isLayoutRtl()) {
944             setPivotX((1 + mIconScale) / 2.0f * getWidth());
945         } else {
946             setPivotX((1 - mIconScale) / 2.0f * getWidth());
947         }
948         setPivotY((getHeight() - mIconScale * getWidth()) / 2.0f);
949     }
950 
executeOnLayout(Runnable runnable)951     public void executeOnLayout(Runnable runnable) {
952         mLayoutRunnable = runnable;
953     }
954 
setDismissed()955     public void setDismissed() {
956         mDismissed = true;
957         if (mOnDismissListener != null) {
958             mOnDismissListener.run();
959         }
960     }
961 
isDismissed()962     public boolean isDismissed() {
963         return mDismissed;
964     }
965 
setOnDismissListener(Runnable onDismissListener)966     public void setOnDismissListener(Runnable onDismissListener) {
967         mOnDismissListener = onDismissListener;
968     }
969 
970     @Override
onDarkChanged(Rect area, float darkIntensity, int tint)971     public void onDarkChanged(Rect area, float darkIntensity, int tint) {
972         int areaTint = getTint(area, this, tint);
973         ColorStateList color = ColorStateList.valueOf(areaTint);
974         setImageTintList(color);
975         setDecorColor(areaTint);
976     }
977 
978     @Override
isIconVisible()979     public boolean isIconVisible() {
980         return mIcon != null && mIcon.visible;
981     }
982 
983     @Override
isIconBlocked()984     public boolean isIconBlocked() {
985         return mBlocked;
986     }
987 
setIncreasedSize(boolean increasedSize)988     public void setIncreasedSize(boolean increasedSize) {
989         mIncreasedSize = increasedSize;
990         maybeUpdateIconScaleDimens();
991     }
992 
993     /**
994      * Sets whether this icon shows a person and should be tinted.
995      * If the state differs from the supplied setting, this
996      * will update the icon colors.
997      *
998      * @param showsConversation Whether the icon shows a person
999      */
setShowsConversation(boolean showsConversation)1000     public void setShowsConversation(boolean showsConversation) {
1001         if (mShowsConversation != showsConversation) {
1002             mShowsConversation = showsConversation;
1003             updateIconColor();
1004         }
1005     }
1006 
1007     /**
1008      * @return if this icon shows a conversation
1009      */
showsConversation()1010     public boolean showsConversation() {
1011         return mShowsConversation;
1012     }
1013 
1014     public interface OnVisibilityChangedListener {
onVisibilityChanged(int newVisibility)1015         void onVisibilityChanged(int newVisibility);
1016     }
1017 }
1018