StatusBar.java revision 88e61aad090a05e482e8f007cb5d92bcb338a2c1
1
2
3/*
4 * Copyright (C) 2010 The Android Open Source Project
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *      http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package com.android.systemui.statusbar.phone;
20
21import static android.app.StatusBarManager.WINDOW_STATE_HIDDEN;
22import static android.app.StatusBarManager.WINDOW_STATE_SHOWING;
23import static android.app.StatusBarManager.windowStateToString;
24
25import static com.android.systemui.statusbar.notification.NotificationInflater.InflationCallback;
26import static com.android.systemui.statusbar.phone.BarTransitions.MODE_LIGHTS_OUT;
27import static com.android.systemui.statusbar.phone.BarTransitions.MODE_LIGHTS_OUT_TRANSPARENT;
28import static com.android.systemui.statusbar.phone.BarTransitions.MODE_OPAQUE;
29import static com.android.systemui.statusbar.phone.BarTransitions.MODE_SEMI_TRANSPARENT;
30import static com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSLUCENT;
31import static com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSPARENT;
32import static com.android.systemui.statusbar.phone.BarTransitions.MODE_WARNING;
33
34import android.R.style;
35import android.animation.Animator;
36import android.animation.AnimatorListenerAdapter;
37import android.annotation.NonNull;
38import android.app.ActivityManager;
39import android.app.ActivityOptions;
40import android.app.Notification;
41import android.app.NotificationManager;
42import android.app.PendingIntent;
43import android.app.StatusBarManager;
44import android.app.admin.DevicePolicyManager;
45import android.content.BroadcastReceiver;
46import android.content.ComponentCallbacks2;
47import android.content.ComponentName;
48import android.content.Context;
49import android.content.Intent;
50import android.content.IntentFilter;
51import android.content.IntentSender;
52import android.content.pm.IPackageManager;
53import android.content.pm.PackageManager;
54import android.content.res.Configuration;
55import android.content.res.Resources;
56import android.database.ContentObserver;
57import android.graphics.Bitmap;
58import android.graphics.Canvas;
59import android.graphics.ColorFilter;
60import android.graphics.PixelFormat;
61import android.graphics.Point;
62import android.graphics.PointF;
63import android.graphics.PorterDuff;
64import android.graphics.PorterDuffXfermode;
65import android.graphics.Rect;
66import android.graphics.drawable.BitmapDrawable;
67import android.graphics.drawable.ColorDrawable;
68import android.graphics.drawable.Drawable;
69import android.media.AudioAttributes;
70import android.media.MediaMetadata;
71import android.media.session.MediaController;
72import android.media.session.MediaSession;
73import android.media.session.MediaSessionManager;
74import android.media.session.PlaybackState;
75import android.metrics.LogMaker;
76import android.net.Uri;
77import android.os.AsyncTask;
78import android.os.Bundle;
79import android.os.IBinder;
80import android.os.Message;
81import android.os.PowerManager;
82import android.os.RemoteException;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
86import android.os.SystemService;
87import android.os.Trace;
88import android.os.UserHandle;
89import android.os.UserManager;
90import android.os.Vibrator;
91import android.provider.Settings;
92import android.service.notification.NotificationListenerService.RankingMap;
93import android.service.notification.StatusBarNotification;
94import android.util.ArraySet;
95import android.util.DisplayMetrics;
96import android.util.EventLog;
97import android.util.Log;
98import android.view.ContextThemeWrapper;
99import android.view.Display;
100import android.view.KeyEvent;
101import android.view.LayoutInflater;
102import android.view.MotionEvent;
103import android.view.ThreadedRenderer;
104import android.view.View;
105import android.view.ViewGroup;
106import android.view.ViewParent;
107import android.view.ViewStub;
108import android.view.ViewTreeObserver;
109import android.view.WindowManager;
110import android.view.WindowManagerGlobal;
111import android.view.animation.AccelerateInterpolator;
112import android.view.animation.Interpolator;
113import android.widget.DateTimeView;
114import android.widget.ImageView;
115import android.widget.TextView;
116
117import com.android.internal.logging.MetricsLogger;
118import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
119import com.android.internal.statusbar.NotificationVisibility;
120import com.android.internal.statusbar.StatusBarIcon;
121import com.android.internal.util.NotificationMessagingUtil;
122import com.android.keyguard.KeyguardHostView.OnDismissAction;
123import com.android.keyguard.KeyguardStatusView;
124import com.android.keyguard.KeyguardUpdateMonitor;
125import com.android.keyguard.KeyguardUpdateMonitorCallback;
126import com.android.keyguard.ViewMediatorCallback;
127import com.android.systemui.ActivityStarterDelegate;
128import com.android.systemui.DemoMode;
129import com.android.systemui.Dependency;
130import com.android.systemui.EventLogTags;
131import com.android.systemui.Interpolators;
132import com.android.systemui.Prefs;
133import com.android.systemui.R;
134import com.android.systemui.SystemUIFactory;
135import com.android.systemui.UiOffloadThread;
136import com.android.systemui.assist.AssistManager;
137import com.android.systemui.classifier.FalsingLog;
138import com.android.systemui.classifier.FalsingManager;
139import com.android.systemui.doze.DozeHost;
140import com.android.systemui.doze.DozeLog;
141import com.android.systemui.fragments.FragmentHostManager;
142import com.android.systemui.fragments.PluginFragmentListener;
143import com.android.systemui.keyguard.KeyguardViewMediator;
144import com.android.systemui.plugins.qs.QS;
145import com.android.systemui.plugins.ActivityStarter;
146import com.android.systemui.plugins.statusbar.NotificationSwipeActionHelper.SnoozeOption;
147import com.android.systemui.qs.QSFragment;
148import com.android.systemui.qs.QSPanel;
149import com.android.systemui.qs.QSTileHost;
150import com.android.systemui.recents.ScreenPinningRequest;
151import com.android.systemui.recents.events.EventBus;
152import com.android.systemui.recents.events.activity.AppTransitionFinishedEvent;
153import com.android.systemui.recents.events.activity.UndockingTaskEvent;
154import com.android.systemui.recents.misc.SystemServicesProxy;
155import com.android.systemui.stackdivider.Divider;
156import com.android.systemui.stackdivider.WindowManagerProxy;
157import com.android.systemui.statusbar.ActivatableNotificationView;
158import com.android.systemui.statusbar.BackDropView;
159import com.android.systemui.statusbar.CommandQueue;
160import com.android.systemui.statusbar.DismissView;
161import com.android.systemui.statusbar.DragDownHelper;
162import com.android.systemui.statusbar.EmptyShadeView;
163import com.android.systemui.statusbar.ExpandableNotificationRow;
164import com.android.systemui.statusbar.GestureRecorder;
165import com.android.systemui.statusbar.KeyboardShortcuts;
166import com.android.systemui.statusbar.KeyguardIndicationController;
167import com.android.systemui.statusbar.NotificationData;
168import com.android.systemui.statusbar.NotificationData.Entry;
169import com.android.systemui.statusbar.NotificationGuts;
170import com.android.systemui.statusbar.NotificationInfo;
171import com.android.systemui.statusbar.NotificationShelf;
172import com.android.systemui.statusbar.NotificationSnooze;
173import com.android.systemui.statusbar.RemoteInputController;
174import com.android.systemui.statusbar.ScrimView;
175import com.android.systemui.statusbar.SignalClusterView;
176import com.android.systemui.statusbar.StatusBarState;
177import com.android.systemui.statusbar.notification.InflationException;
178import com.android.systemui.statusbar.notification.RowInflaterTask;
179import com.android.systemui.statusbar.notification.VisualStabilityManager;
180import com.android.systemui.statusbar.phone.StatusBarIconController.IconManager;
181import com.android.systemui.statusbar.phone.UnlockMethodCache.OnUnlockMethodChangedListener;
182import com.android.systemui.statusbar.policy.BatteryController;
183import com.android.systemui.statusbar.policy.BatteryController.BatteryStateChangeCallback;
184import com.android.systemui.statusbar.policy.BrightnessMirrorController;
185import com.android.systemui.statusbar.policy.ConfigurationController;
186import com.android.systemui.statusbar.policy.ConfigurationController.ConfigurationListener;
187import com.android.systemui.statusbar.policy.DarkIconDispatcher;
188import com.android.systemui.statusbar.policy.DeviceProvisionedController;
189import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
190import com.android.systemui.statusbar.policy.HeadsUpManager;
191import com.android.systemui.statusbar.policy.KeyguardMonitor;
192import com.android.systemui.statusbar.policy.KeyguardMonitorImpl;
193import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
194import com.android.systemui.statusbar.policy.NetworkController;
195import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
196import com.android.systemui.statusbar.policy.PreviewInflater;
197import com.android.systemui.statusbar.policy.UserInfoController;
198import com.android.systemui.statusbar.policy.UserInfoControllerImpl;
199import com.android.systemui.statusbar.policy.UserSwitcherController;
200import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
201import com.android.systemui.statusbar.stack.NotificationStackScrollLayout.OnChildLocationsChangedListener;
202import com.android.systemui.util.leak.LeakDetector;
203import com.android.systemui.volume.VolumeComponent;
204
205import java.io.FileDescriptor;
206import java.io.PrintWriter;
207import java.io.StringWriter;
208import java.util.ArrayList;
209import java.util.Collection;
210import java.util.Collections;
211import java.util.HashMap;
212import java.util.List;
213import java.util.Map;
214
215import android.app.ActivityManager.StackId;
216import android.app.INotificationManager;
217import android.app.KeyguardManager;
218import android.app.NotificationChannel;
219import android.app.RemoteInput;
220import android.app.TaskStackBuilder;
221import android.content.pm.ApplicationInfo;
222import android.content.pm.PackageManager.NameNotFoundException;
223import android.content.pm.UserInfo;
224import android.os.Build;
225import android.os.Handler;
226import android.service.notification.NotificationListenerService;
227import android.service.vr.IVrManager;
228import android.service.vr.IVrStateCallbacks;
229import android.text.TextUtils;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.view.IWindowManager;
234import android.view.ViewAnimationUtils;
235import android.view.accessibility.AccessibilityManager;
236import android.widget.RemoteViews;
237import android.widget.Toast;
238
239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.statusbar.IStatusBarService;
241import com.android.internal.widget.LockPatternUtils;
242import com.android.systemui.DejankUtils;
243import com.android.systemui.RecentsComponent;
244import com.android.systemui.SwipeHelper;
245import com.android.systemui.SystemUI;
246import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin.MenuItem;
247import com.android.systemui.recents.Recents;
248import com.android.systemui.statusbar.policy.RemoteInputView;
249import com.android.systemui.statusbar.stack.StackStateAnimator;
250import com.android.systemui.util.NotificationChannels;
251
252import java.util.HashSet;
253import java.util.Locale;
254import java.util.Set;
255import java.util.Stack;
256
257public class StatusBar extends SystemUI implements DemoMode,
258        DragDownHelper.DragDownCallback, ActivityStarter, OnUnlockMethodChangedListener,
259        OnHeadsUpChangedListener, VisualStabilityManager.Callback, CommandQueue.Callbacks,
260        ActivatableNotificationView.OnActivatedListener,
261        ExpandableNotificationRow.ExpansionLogger, NotificationData.Environment,
262        ExpandableNotificationRow.OnExpandClickListener, InflationCallback {
263    public static final boolean MULTIUSER_DEBUG = false;
264
265    public static final boolean ENABLE_REMOTE_INPUT =
266            SystemProperties.getBoolean("debug.enable_remote_input", true);
267    public static final boolean ENABLE_CHILD_NOTIFICATIONS
268            = SystemProperties.getBoolean("debug.child_notifs", true);
269    public static final boolean FORCE_REMOTE_INPUT_HISTORY =
270            SystemProperties.getBoolean("debug.force_remoteinput_history", false);
271    private static boolean ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT = false;
272
273    protected static final int MSG_SHOW_RECENT_APPS = 1019;
274    protected static final int MSG_HIDE_RECENT_APPS = 1020;
275    protected static final int MSG_TOGGLE_RECENTS_APPS = 1021;
276    protected static final int MSG_PRELOAD_RECENT_APPS = 1022;
277    protected static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 1023;
278    protected static final int MSG_TOGGLE_KEYBOARD_SHORTCUTS_MENU = 1026;
279    protected static final int MSG_DISMISS_KEYBOARD_SHORTCUTS_MENU = 1027;
280
281    protected static final boolean ENABLE_HEADS_UP = true;
282    protected static final String SETTING_HEADS_UP_TICKER = "ticker_gets_heads_up";
283
284    // Must match constant in Settings. Used to highlight preferences when linking to Settings.
285    private static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
286
287    private static final String PERMISSION_SELF = "com.android.systemui.permission.SELF";
288
289    // Should match the values in PhoneWindowManager
290    public static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
291    public static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
292
293    private static final String BANNER_ACTION_CANCEL =
294            "com.android.systemui.statusbar.banner_action_cancel";
295    private static final String BANNER_ACTION_SETUP =
296            "com.android.systemui.statusbar.banner_action_setup";
297    private static final String NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION
298            = "com.android.systemui.statusbar.work_challenge_unlocked_notification_action";
299    public static final String TAG = "StatusBar";
300    public static final boolean DEBUG = false;
301    public static final boolean SPEW = false;
302    public static final boolean DUMPTRUCK = true; // extra dumpsys info
303    public static final boolean DEBUG_GESTURES = false;
304    public static final boolean DEBUG_MEDIA = false;
305    public static final boolean DEBUG_MEDIA_FAKE_ARTWORK = false;
306
307    public static final boolean DEBUG_WINDOW_STATE = false;
308
309    // additional instrumentation for testing purposes; intended to be left on during development
310    public static final boolean CHATTY = DEBUG;
311
312    public static final boolean SHOW_LOCKSCREEN_MEDIA_ARTWORK = true;
313
314    public static final String ACTION_FAKE_ARTWORK = "fake_artwork";
315
316    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
317    private static final int MSG_CLOSE_PANELS = 1001;
318    private static final int MSG_OPEN_SETTINGS_PANEL = 1002;
319    private static final int MSG_LAUNCH_TRANSITION_TIMEOUT = 1003;
320    // 1020-1040 reserved for BaseStatusBar
321
322    // Time after we abort the launch transition.
323    private static final long LAUNCH_TRANSITION_TIMEOUT_MS = 5000;
324
325    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
326
327    private static final int STATUS_OR_NAV_TRANSIENT =
328            View.STATUS_BAR_TRANSIENT | View.NAVIGATION_BAR_TRANSIENT;
329    private static final long AUTOHIDE_TIMEOUT_MS = 3000;
330
331    /** The minimum delay in ms between reports of notification visibility. */
332    private static final int VISIBILITY_REPORT_MIN_DELAY_MS = 500;
333
334    /**
335     * The delay to reset the hint text when the hint animation is finished running.
336     */
337    private static final int HINT_RESET_DELAY_MS = 1200;
338
339    private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
340            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
341            .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
342            .build();
343
344    public static final int FADE_KEYGUARD_START_DELAY = 100;
345    public static final int FADE_KEYGUARD_DURATION = 300;
346    public static final int FADE_KEYGUARD_DURATION_PULSING = 96;
347
348    /** If true, the system is in the half-boot-to-decryption-screen state.
349     * Prudently disable QS and notifications.  */
350    private static final boolean ONLY_CORE_APPS;
351
352    /** If true, the lockscreen will show a distinct wallpaper */
353    private static final boolean ENABLE_LOCKSCREEN_WALLPAPER = true;
354
355    /* If true, the device supports freeform window management.
356     * This affects the status bar UI. */
357    private static final boolean FREEFORM_WINDOW_MANAGEMENT;
358
359    /**
360     * How long to wait before auto-dismissing a notification that was kept for remote input, and
361     * has now sent a remote input. We auto-dismiss, because the app may not see a reason to cancel
362     * these given that they technically don't exist anymore. We wait a bit in case the app issues
363     * an update.
364     */
365    private static final int REMOTE_INPUT_KEPT_ENTRY_AUTO_CANCEL_DELAY = 200;
366
367    /**
368     * Never let the alpha become zero for surfaces that draw with SRC - otherwise the RenderNode
369     * won't draw anything and uninitialized memory will show through
370     * if mScrimSrcModeEnabled. Note that 0.001 is rounded down to 0 in
371     * libhwui.
372     */
373    private static final float SRC_MIN_ALPHA = 0.002f;
374
375    static {
376        boolean onlyCoreApps;
377        boolean freeformWindowManagement;
378        try {
379            IPackageManager packageManager =
380                    IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
381            onlyCoreApps = packageManager.isOnlyCoreApps();
382            freeformWindowManagement = packageManager.hasSystemFeature(
383                    PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT, 0);
384        } catch (RemoteException e) {
385            onlyCoreApps = false;
386            freeformWindowManagement = false;
387        }
388        ONLY_CORE_APPS = onlyCoreApps;
389        FREEFORM_WINDOW_MANAGEMENT = freeformWindowManagement;
390    }
391
392    /**
393     * The {@link StatusBarState} of the status bar.
394     */
395    protected int mState;
396    protected boolean mBouncerShowing;
397    protected boolean mShowLockscreenNotifications;
398    protected boolean mAllowLockscreenRemoteInput;
399
400    PhoneStatusBarPolicy mIconPolicy;
401
402    VolumeComponent mVolumeComponent;
403    BrightnessMirrorController mBrightnessMirrorController;
404    protected FingerprintUnlockController mFingerprintUnlockController;
405    LightBarController mLightBarController;
406    protected LockscreenWallpaper mLockscreenWallpaper;
407
408    int mNaturalBarHeight = -1;
409
410    Point mCurrentDisplaySize = new Point();
411
412    protected StatusBarWindowView mStatusBarWindow;
413    protected PhoneStatusBarView mStatusBarView;
414    private int mStatusBarWindowState = WINDOW_STATE_SHOWING;
415    protected StatusBarWindowManager mStatusBarWindowManager;
416    protected UnlockMethodCache mUnlockMethodCache;
417    private DozeServiceHost mDozeServiceHost;
418    private boolean mWakeUpComingFromTouch;
419    private PointF mWakeUpTouchLocation;
420    private boolean mScreenTurningOn;
421
422    int mPixelFormat;
423    Object mQueueLock = new Object();
424
425    protected StatusBarIconController mIconController;
426
427    // expanded notifications
428    protected NotificationPanelView mNotificationPanel; // the sliding/resizing panel within the notification window
429    View mExpandedContents;
430    TextView mNotificationPanelDebugText;
431
432    // settings
433    private QSPanel mQSPanel;
434
435    // top bar
436    protected KeyguardStatusBarView mKeyguardStatusBar;
437    KeyguardStatusView mKeyguardStatusView;
438    KeyguardBottomAreaView mKeyguardBottomArea;
439    boolean mLeaveOpenOnKeyguardHide;
440    KeyguardIndicationController mKeyguardIndicationController;
441
442    // Keyguard is going away soon.
443    private boolean mKeyguardGoingAway;
444    // Keyguard is actually fading away now.
445    protected boolean mKeyguardFadingAway;
446    protected long mKeyguardFadingAwayDelay;
447    protected long mKeyguardFadingAwayDuration;
448
449    // RemoteInputView to be activated after unlock
450    private View mPendingRemoteInputView;
451    private View mPendingWorkRemoteInputView;
452
453    private View mReportRejectedTouch;
454
455    int mMaxAllowedKeyguardNotifications;
456
457    boolean mExpandedVisible;
458
459    // the tracker view
460    int mTrackingPosition; // the position of the top of the tracking view.
461
462    // Tracking finger for opening/closing.
463    boolean mTracking;
464
465    int[] mAbsPos = new int[2];
466    ArrayList<Runnable> mPostCollapseRunnables = new ArrayList<>();
467
468    // for disabling the status bar
469    int mDisabled1 = 0;
470    int mDisabled2 = 0;
471
472    // tracking calls to View.setSystemUiVisibility()
473    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
474    private final Rect mLastFullscreenStackBounds = new Rect();
475    private final Rect mLastDockedStackBounds = new Rect();
476
477    // last value sent to window manager
478    private int mLastDispatchedSystemUiVisibility = ~View.SYSTEM_UI_FLAG_VISIBLE;
479
480    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
481
482    // XXX: gesture research
483    private final GestureRecorder mGestureRec = DEBUG_GESTURES
484        ? new GestureRecorder("/sdcard/statusbar_gestures.dat")
485        : null;
486
487    private ScreenPinningRequest mScreenPinningRequest;
488
489    private final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
490
491    // ensure quick settings is disabled until the current user makes it through the setup wizard
492    private boolean mUserSetup = false;
493    private DeviceProvisionedListener mUserSetupObserver = new DeviceProvisionedListener() {
494        @Override
495        public void onUserSetupChanged() {
496            final boolean userSetup = mDeviceProvisionedController.isUserSetup(
497                    mDeviceProvisionedController.getCurrentUser());
498            if (MULTIUSER_DEBUG) Log.d(TAG, String.format("User setup changed: " +
499                    "userSetup=%s mUserSetup=%s", userSetup, mUserSetup));
500
501            if (userSetup != mUserSetup) {
502                mUserSetup = userSetup;
503                if (!mUserSetup && mStatusBarView != null)
504                    animateCollapseQuickSettings();
505                if (mKeyguardBottomArea != null) {
506                    mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
507                }
508                updateQsExpansionEnabled();
509            }
510        }
511    };
512
513    protected H mHandler = createHandler();
514    final private ContentObserver mHeadsUpObserver = new ContentObserver(mHandler) {
515        @Override
516        public void onChange(boolean selfChange) {
517            boolean wasUsing = mUseHeadsUp;
518            mUseHeadsUp = ENABLE_HEADS_UP && !mDisableNotificationAlerts
519                    && Settings.Global.HEADS_UP_OFF != Settings.Global.getInt(
520                    mContext.getContentResolver(), Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED,
521                    Settings.Global.HEADS_UP_OFF);
522            mHeadsUpTicker = mUseHeadsUp && 0 != Settings.Global.getInt(
523                    mContext.getContentResolver(), SETTING_HEADS_UP_TICKER, 0);
524            Log.d(TAG, "heads up is " + (mUseHeadsUp ? "enabled" : "disabled"));
525            if (wasUsing != mUseHeadsUp) {
526                if (!mUseHeadsUp) {
527                    Log.d(TAG, "dismissing any existing heads up notification on disable event");
528                    mHeadsUpManager.releaseAllImmediately();
529                }
530            }
531        }
532    };
533
534    private int mInteractingWindows;
535    private boolean mAutohideSuspended;
536    private int mStatusBarMode;
537    private int mMaxKeyguardNotifications;
538
539    private ViewMediatorCallback mKeyguardViewMediatorCallback;
540    protected ScrimController mScrimController;
541    protected DozeScrimController mDozeScrimController;
542    private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
543
544    private final Runnable mAutohide = new Runnable() {
545        @Override
546        public void run() {
547            int requested = mSystemUiVisibility & ~STATUS_OR_NAV_TRANSIENT;
548            if (mSystemUiVisibility != requested) {
549                notifyUiVisibilityChanged(requested);
550            }
551        }};
552
553    private boolean mWaitingForKeyguardExit;
554    private boolean mDozing;
555    private boolean mDozingRequested;
556    protected boolean mScrimSrcModeEnabled;
557
558    public static final Interpolator ALPHA_IN = Interpolators.ALPHA_IN;
559    public static final Interpolator ALPHA_OUT = Interpolators.ALPHA_OUT;
560
561    protected BackDropView mBackdrop;
562    protected ImageView mBackdropFront, mBackdropBack;
563    protected PorterDuffXfermode mSrcXferMode = new PorterDuffXfermode(PorterDuff.Mode.SRC);
564    protected PorterDuffXfermode mSrcOverXferMode =
565            new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER);
566
567    private MediaSessionManager mMediaSessionManager;
568    private MediaController mMediaController;
569    private String mMediaNotificationKey;
570    private MediaMetadata mMediaMetadata;
571    private MediaController.Callback mMediaListener
572            = new MediaController.Callback() {
573        @Override
574        public void onPlaybackStateChanged(PlaybackState state) {
575            super.onPlaybackStateChanged(state);
576            if (DEBUG_MEDIA) Log.v(TAG, "DEBUG_MEDIA: onPlaybackStateChanged: " + state);
577            if (state != null) {
578                if (!isPlaybackActive(state.getState())) {
579                    clearCurrentMediaNotification();
580                    updateMediaMetaData(true, true);
581                }
582            }
583        }
584
585        @Override
586        public void onMetadataChanged(MediaMetadata metadata) {
587            super.onMetadataChanged(metadata);
588            if (DEBUG_MEDIA) Log.v(TAG, "DEBUG_MEDIA: onMetadataChanged: " + metadata);
589            mMediaMetadata = metadata;
590            updateMediaMetaData(true, true);
591        }
592    };
593
594    private final OnChildLocationsChangedListener mOnChildLocationsChangedListener =
595            new OnChildLocationsChangedListener() {
596        @Override
597        public void onChildLocationsChanged(NotificationStackScrollLayout stackScrollLayout) {
598            userActivity();
599        }
600    };
601
602    private int mDisabledUnmodified1;
603    private int mDisabledUnmodified2;
604
605    /** Keys of notifications currently visible to the user. */
606    private final ArraySet<NotificationVisibility> mCurrentlyVisibleNotifications =
607            new ArraySet<>();
608    private long mLastVisibilityReportUptimeMs;
609
610    private Runnable mLaunchTransitionEndRunnable;
611    protected boolean mLaunchTransitionFadingAway;
612    private ExpandableNotificationRow mDraggedDownRow;
613    private boolean mLaunchCameraOnScreenTurningOn;
614    private boolean mLaunchCameraOnFinishedGoingToSleep;
615    private int mLastCameraLaunchSource;
616    private PowerManager.WakeLock mGestureWakeLock;
617    private Vibrator mVibrator;
618    private long[] mCameraLaunchGestureVibePattern;
619
620    private final int[] mTmpInt2 = new int[2];
621
622    // Fingerprint (as computed by getLoggingFingerprint() of the last logged state.
623    private int mLastLoggedStateFingerprint;
624
625    /**
626     * If set, the device has started going to sleep but isn't fully non-interactive yet.
627     */
628    protected boolean mStartedGoingToSleep;
629
630    private final OnChildLocationsChangedListener mNotificationLocationsChangedListener =
631            new OnChildLocationsChangedListener() {
632                @Override
633                public void onChildLocationsChanged(
634                        NotificationStackScrollLayout stackScrollLayout) {
635                    if (mHandler.hasCallbacks(mVisibilityReporter)) {
636                        // Visibilities will be reported when the existing
637                        // callback is executed.
638                        return;
639                    }
640                    // Calculate when we're allowed to run the visibility
641                    // reporter. Note that this timestamp might already have
642                    // passed. That's OK, the callback will just be executed
643                    // ASAP.
644                    long nextReportUptimeMs =
645                            mLastVisibilityReportUptimeMs + VISIBILITY_REPORT_MIN_DELAY_MS;
646                    mHandler.postAtTime(mVisibilityReporter, nextReportUptimeMs);
647                }
648            };
649
650    // Tracks notifications currently visible in mNotificationStackScroller and
651    // emits visibility events via NoMan on changes.
652    private final Runnable mVisibilityReporter = new Runnable() {
653        private final ArraySet<NotificationVisibility> mTmpNewlyVisibleNotifications =
654                new ArraySet<>();
655        private final ArraySet<NotificationVisibility> mTmpCurrentlyVisibleNotifications =
656                new ArraySet<>();
657        private final ArraySet<NotificationVisibility> mTmpNoLongerVisibleNotifications =
658                new ArraySet<>();
659
660        @Override
661        public void run() {
662            mLastVisibilityReportUptimeMs = SystemClock.uptimeMillis();
663            final String mediaKey = getCurrentMediaNotificationKey();
664
665            // 1. Loop over mNotificationData entries:
666            //   A. Keep list of visible notifications.
667            //   B. Keep list of previously hidden, now visible notifications.
668            // 2. Compute no-longer visible notifications by removing currently
669            //    visible notifications from the set of previously visible
670            //    notifications.
671            // 3. Report newly visible and no-longer visible notifications.
672            // 4. Keep currently visible notifications for next report.
673            ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
674            int N = activeNotifications.size();
675            for (int i = 0; i < N; i++) {
676                Entry entry = activeNotifications.get(i);
677                String key = entry.notification.getKey();
678                boolean isVisible = mStackScroller.isInVisibleLocation(entry.row);
679                NotificationVisibility visObj = NotificationVisibility.obtain(key, i, isVisible);
680                boolean previouslyVisible = mCurrentlyVisibleNotifications.contains(visObj);
681                if (isVisible) {
682                    // Build new set of visible notifications.
683                    mTmpCurrentlyVisibleNotifications.add(visObj);
684                    if (!previouslyVisible) {
685                        mTmpNewlyVisibleNotifications.add(visObj);
686                    }
687                } else {
688                    // release object
689                    visObj.recycle();
690                }
691            }
692            mTmpNoLongerVisibleNotifications.addAll(mCurrentlyVisibleNotifications);
693            mTmpNoLongerVisibleNotifications.removeAll(mTmpCurrentlyVisibleNotifications);
694
695            logNotificationVisibilityChanges(
696                    mTmpNewlyVisibleNotifications, mTmpNoLongerVisibleNotifications);
697
698            recycleAllVisibilityObjects(mCurrentlyVisibleNotifications);
699            mCurrentlyVisibleNotifications.addAll(mTmpCurrentlyVisibleNotifications);
700
701            recycleAllVisibilityObjects(mTmpNoLongerVisibleNotifications);
702            mTmpCurrentlyVisibleNotifications.clear();
703            mTmpNewlyVisibleNotifications.clear();
704            mTmpNoLongerVisibleNotifications.clear();
705        }
706    };
707
708    private NotificationMessagingUtil mMessagingUtil;
709    private KeyguardUserSwitcher mKeyguardUserSwitcher;
710    private UserSwitcherController mUserSwitcherController;
711    private NetworkController mNetworkController;
712    private KeyguardMonitorImpl mKeyguardMonitor;
713    private BatteryController mBatteryController;
714    private boolean mPanelExpanded;
715    private LogMaker mStatusBarStateLog;
716    private LockscreenGestureLogger mLockscreenGestureLogger = new LockscreenGestureLogger();
717    private NotificationIconAreaController mNotificationIconAreaController;
718    private ConfigurationListener mConfigurationListener;
719    private boolean mReinflateNotificationsOnUserSwitched;
720    private HashMap<String, Entry> mPendingNotifications = new HashMap<>();
721
722    private void recycleAllVisibilityObjects(ArraySet<NotificationVisibility> array) {
723        final int N = array.size();
724        for (int i = 0 ; i < N; i++) {
725            array.valueAt(i).recycle();
726        }
727        array.clear();
728    }
729
730    private final View.OnClickListener mGoToLockedShadeListener = v -> {
731        if (mState == StatusBarState.KEYGUARD) {
732            wakeUpIfDozing(SystemClock.uptimeMillis(), v);
733            goToLockedShade(null);
734        }
735    };
736    private HashMap<ExpandableNotificationRow, List<ExpandableNotificationRow>> mTmpChildOrderMap
737            = new HashMap<>();
738    private RankingMap mLatestRankingMap;
739    private boolean mNoAnimationOnNextBarModeChange;
740    private FalsingManager mFalsingManager;
741
742    private KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
743        @Override
744        public void onDreamingStateChanged(boolean dreaming) {
745            if (dreaming) {
746                maybeEscalateHeadsUp();
747            }
748        }
749    };
750
751    private NavigationBarFragment mNavigationBar;
752    private View mNavigationBarView;
753
754    @Override
755    public void start() {
756        mNetworkController = Dependency.get(NetworkController.class);
757        mUserSwitcherController = Dependency.get(UserSwitcherController.class);
758        mKeyguardMonitor = (KeyguardMonitorImpl) Dependency.get(KeyguardMonitor.class);
759        mBatteryController = Dependency.get(BatteryController.class);
760        mAssistManager = Dependency.get(AssistManager.class);
761        mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
762
763        mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
764        mDisplay = mWindowManager.getDefaultDisplay();
765        updateDisplaySize();
766        mScrimSrcModeEnabled = mContext.getResources().getBoolean(
767                R.bool.config_status_bar_scrim_behind_use_src);
768
769        DateTimeView.setReceiverHandler(Dependency.get(Dependency.TIME_TICK_HANDLER));
770        putComponent(StatusBar.class, this);
771
772        // start old BaseStatusBar.start().
773        mWindowManagerService = WindowManagerGlobal.getWindowManagerService();
774        mDevicePolicyManager = (DevicePolicyManager)mContext.getSystemService(
775                Context.DEVICE_POLICY_SERVICE);
776
777        mNotificationData = new NotificationData(this);
778        mMessagingUtil = new NotificationMessagingUtil(mContext);
779
780        mAccessibilityManager = (AccessibilityManager)
781                mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
782
783        mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
784
785        mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
786        mDeviceProvisionedController.addCallback(mDeviceProvisionedListener);
787        mContext.getContentResolver().registerContentObserver(
788                Settings.Global.getUriFor(Settings.Global.ZEN_MODE), false,
789                mSettingsObserver);
790        mContext.getContentResolver().registerContentObserver(
791                Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS), false,
792                mLockscreenSettingsObserver,
793                UserHandle.USER_ALL);
794        if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
795            mContext.getContentResolver().registerContentObserver(
796                    Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT),
797                    false,
798                    mSettingsObserver,
799                    UserHandle.USER_ALL);
800        }
801
802        mContext.getContentResolver().registerContentObserver(
803                Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS),
804                true,
805                mLockscreenSettingsObserver,
806                UserHandle.USER_ALL);
807
808        mBarService = IStatusBarService.Stub.asInterface(
809                ServiceManager.getService(Context.STATUS_BAR_SERVICE));
810
811        mRecents = getComponent(Recents.class);
812
813        final Configuration currentConfig = mContext.getResources().getConfiguration();
814        mLocale = currentConfig.locale;
815        mLayoutDirection = TextUtils.getLayoutDirectionFromLocale(mLocale);
816
817        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
818        mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
819        mLockPatternUtils = new LockPatternUtils(mContext);
820
821        // Connect in to the status bar manager service
822        mCommandQueue = getComponent(CommandQueue.class);
823        mCommandQueue.addCallbacks(this);
824
825        int[] switches = new int[9];
826        ArrayList<IBinder> binders = new ArrayList<IBinder>();
827        ArrayList<String> iconSlots = new ArrayList<>();
828        ArrayList<StatusBarIcon> icons = new ArrayList<>();
829        Rect fullscreenStackBounds = new Rect();
830        Rect dockedStackBounds = new Rect();
831        try {
832            mBarService.registerStatusBar(mCommandQueue, iconSlots, icons, switches, binders,
833                    fullscreenStackBounds, dockedStackBounds);
834        } catch (RemoteException ex) {
835            // If the system process isn't there we're doomed anyway.
836        }
837
838        createAndAddWindows();
839
840        mSettingsObserver.onChange(false); // set up
841        mCommandQueue.disable(switches[0], switches[6], false /* animate */);
842        setSystemUiVisibility(switches[1], switches[7], switches[8], 0xffffffff,
843                fullscreenStackBounds, dockedStackBounds);
844        topAppWindowChanged(switches[2] != 0);
845        // StatusBarManagerService has a back up of IME token and it's restored here.
846        setImeWindowStatus(binders.get(0), switches[3], switches[4], switches[5] != 0);
847
848        // Set up the initial icon state
849        int N = iconSlots.size();
850        int viewIndex = 0;
851        for (int i=0; i < N; i++) {
852            mCommandQueue.setIcon(iconSlots.get(i), icons.get(i));
853        }
854
855        // Set up the initial notification state.
856        try {
857            mNotificationListener.registerAsSystemService(mContext,
858                    new ComponentName(mContext.getPackageName(), getClass().getCanonicalName()),
859                    UserHandle.USER_ALL);
860        } catch (RemoteException e) {
861            Log.e(TAG, "Unable to register notification listener", e);
862        }
863
864
865        if (DEBUG) {
866            Log.d(TAG, String.format(
867                    "init: icons=%d disabled=0x%08x lights=0x%08x menu=0x%08x imeButton=0x%08x",
868                   icons.size(),
869                   switches[0],
870                   switches[1],
871                   switches[2],
872                   switches[3]
873                   ));
874        }
875
876        mCurrentUserId = ActivityManager.getCurrentUser();
877        setHeadsUpUser(mCurrentUserId);
878
879        IntentFilter filter = new IntentFilter();
880        filter.addAction(Intent.ACTION_USER_SWITCHED);
881        filter.addAction(Intent.ACTION_USER_ADDED);
882        filter.addAction(Intent.ACTION_USER_PRESENT);
883        mContext.registerReceiver(mBaseBroadcastReceiver, filter);
884
885        IntentFilter internalFilter = new IntentFilter();
886        internalFilter.addAction(NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION);
887        internalFilter.addAction(BANNER_ACTION_CANCEL);
888        internalFilter.addAction(BANNER_ACTION_SETUP);
889        mContext.registerReceiver(mBaseBroadcastReceiver, internalFilter, PERMISSION_SELF, null);
890
891        IntentFilter allUsersFilter = new IntentFilter();
892        allUsersFilter.addAction(
893                DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
894        allUsersFilter.addAction(Intent.ACTION_DEVICE_LOCKED_CHANGED);
895        mContext.registerReceiverAsUser(mAllUsersReceiver, UserHandle.ALL, allUsersFilter,
896                null, null);
897        updateCurrentProfilesCache();
898
899        IVrManager vrManager = IVrManager.Stub.asInterface(ServiceManager.getService(
900                Context.VR_SERVICE));
901        try {
902            vrManager.registerListener(mVrStateCallbacks);
903        } catch (RemoteException e) {
904            Slog.e(TAG, "Failed to register VR mode state listener: " + e);
905        }
906
907        mNonBlockablePkgs = new HashSet<String>();
908        Collections.addAll(mNonBlockablePkgs, mContext.getResources().getStringArray(
909                com.android.internal.R.array.config_nonBlockableNotificationPackages));
910        // end old BaseStatusBar.start().
911
912        mMediaSessionManager
913                = (MediaSessionManager) mContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
914        // TODO: use MediaSessionManager.SessionListener to hook us up to future updates
915        // in session state
916
917        // Lastly, call to the icon policy to install/update all the icons.
918        mIconPolicy = new PhoneStatusBarPolicy(mContext, mIconController);
919        mSettingsObserver.onChange(false); // set up
920
921        mHeadsUpObserver.onChange(true); // set up
922        if (ENABLE_HEADS_UP) {
923            mContext.getContentResolver().registerContentObserver(
924                    Settings.Global.getUriFor(Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED), true,
925                    mHeadsUpObserver);
926            mContext.getContentResolver().registerContentObserver(
927                    Settings.Global.getUriFor(SETTING_HEADS_UP_TICKER), true,
928                    mHeadsUpObserver);
929        }
930        mUnlockMethodCache = UnlockMethodCache.getInstance(mContext);
931        mUnlockMethodCache.addListener(this);
932        startKeyguard();
933
934        KeyguardUpdateMonitor.getInstance(mContext).registerCallback(mUpdateCallback);
935        mDozeServiceHost = new DozeServiceHost();
936        putComponent(DozeHost.class, mDozeServiceHost);
937
938        notifyUserAboutHiddenNotifications();
939
940        mScreenPinningRequest = new ScreenPinningRequest(mContext);
941        mFalsingManager = FalsingManager.getInstance(mContext);
942
943        Dependency.get(ActivityStarterDelegate.class).setActivityStarterImpl(this);
944
945        mConfigurationListener = new ConfigurationListener() {
946            @Override
947            public void onConfigChanged(Configuration newConfig) {
948                StatusBar.this.onConfigurationChanged(newConfig);
949            }
950
951            @Override
952            public void onDensityOrFontScaleChanged() {
953                StatusBar.this.onDensityOrFontScaleChanged();
954            }
955        };
956        Dependency.get(ConfigurationController.class).addCallback(mConfigurationListener);
957    }
958
959    protected void createIconController() {
960    }
961
962    // ================================================================================
963    // Constructing the view
964    // ================================================================================
965    protected void makeStatusBarView() {
966        final Context context = mContext;
967        updateDisplaySize(); // populates mDisplayMetrics
968        updateResources();
969
970        inflateStatusBarWindow(context);
971        mStatusBarWindow.setService(this);
972        mStatusBarWindow.setOnTouchListener(getStatusBarWindowTouchListener());
973
974        // TODO: Deal with the ugliness that comes from having some of the statusbar broken out
975        // into fragments, but the rest here, it leaves some awkward lifecycle and whatnot.
976        mNotificationPanel = (NotificationPanelView) mStatusBarWindow.findViewById(
977                R.id.notification_panel);
978        mStackScroller = (NotificationStackScrollLayout) mStatusBarWindow.findViewById(
979                R.id.notification_stack_scroller);
980        mNotificationPanel.setStatusBar(this);
981        mNotificationPanel.setGroupManager(mGroupManager);
982        mKeyguardStatusBar = (KeyguardStatusBarView) mStatusBarWindow.findViewById(R.id.keyguard_header);
983
984        mNotificationIconAreaController = SystemUIFactory.getInstance()
985                .createNotificationIconAreaController(context, this);
986        inflateShelf();
987        mNotificationIconAreaController.setupShelf(mNotificationShelf);
988        Dependency.get(DarkIconDispatcher.class).addDarkReceiver(mNotificationIconAreaController);
989        FragmentHostManager.get(mStatusBarWindow)
990                .addTagListener(CollapsedStatusBarFragment.TAG, (tag, fragment) -> {
991                    CollapsedStatusBarFragment statusBarFragment =
992                            (CollapsedStatusBarFragment) fragment;
993                    statusBarFragment.initNotificationIconArea(mNotificationIconAreaController);
994                    mStatusBarView = (PhoneStatusBarView) fragment.getView();
995                    mStatusBarView.setBar(this);
996                    mStatusBarView.setPanel(mNotificationPanel);
997                    mStatusBarView.setScrimController(mScrimController);
998                    setAreThereNotifications();
999                    checkBarModes();
1000                }).getFragmentManager()
1001                .beginTransaction()
1002                .replace(R.id.status_bar_container, new CollapsedStatusBarFragment(),
1003                        CollapsedStatusBarFragment.TAG)
1004                .commit();
1005        Dependency.get(StatusBarIconController.class).addIconGroup(
1006                new IconManager((ViewGroup) mKeyguardStatusBar.findViewById(R.id.statusIcons)));
1007        mIconController = Dependency.get(StatusBarIconController.class);
1008
1009        if (!ActivityManager.isHighEndGfx()) {
1010            mStatusBarWindow.setBackground(null);
1011            mNotificationPanel.setBackground(new FastColorDrawable(context.getColor(
1012                    R.color.notification_panel_solid_background)));
1013        }
1014
1015        mHeadsUpManager = new HeadsUpManager(context, mStatusBarWindow, mGroupManager);
1016        mHeadsUpManager.setBar(this);
1017        mHeadsUpManager.addListener(this);
1018        mHeadsUpManager.addListener(mNotificationPanel);
1019        mHeadsUpManager.addListener(mGroupManager);
1020        mHeadsUpManager.addListener(mVisualStabilityManager);
1021        mNotificationPanel.setHeadsUpManager(mHeadsUpManager);
1022        mNotificationData.setHeadsUpManager(mHeadsUpManager);
1023        mGroupManager.setHeadsUpManager(mHeadsUpManager);
1024        mHeadsUpManager.setVisualStabilityManager(mVisualStabilityManager);
1025
1026        if (MULTIUSER_DEBUG) {
1027            mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(
1028                    R.id.header_debug_info);
1029            mNotificationPanelDebugText.setVisibility(View.VISIBLE);
1030        }
1031
1032        try {
1033            boolean showNav = mWindowManagerService.hasNavigationBar();
1034            if (DEBUG) Log.v(TAG, "hasNavigationBar=" + showNav);
1035            if (showNav) {
1036                createNavigationBar();
1037            }
1038        } catch (RemoteException ex) {
1039            // no window manager? good luck with that
1040        }
1041
1042        // figure out which pixel-format to use for the status bar.
1043        mPixelFormat = PixelFormat.OPAQUE;
1044
1045        mStackScroller.setLongPressListener(getNotificationLongClicker());
1046        mStackScroller.setStatusBar(this);
1047        mStackScroller.setGroupManager(mGroupManager);
1048        mStackScroller.setHeadsUpManager(mHeadsUpManager);
1049        mGroupManager.setOnGroupChangeListener(mStackScroller);
1050        mVisualStabilityManager.setVisibilityLocationProvider(mStackScroller);
1051
1052        inflateEmptyShadeView();
1053        inflateDismissView();
1054        mExpandedContents = mStackScroller;
1055
1056        mBackdrop = (BackDropView) mStatusBarWindow.findViewById(R.id.backdrop);
1057        mBackdropFront = (ImageView) mBackdrop.findViewById(R.id.backdrop_front);
1058        mBackdropBack = (ImageView) mBackdrop.findViewById(R.id.backdrop_back);
1059
1060        if (ENABLE_LOCKSCREEN_WALLPAPER) {
1061            mLockscreenWallpaper = new LockscreenWallpaper(mContext, this, mHandler);
1062        }
1063
1064        mKeyguardStatusView =
1065                (KeyguardStatusView) mStatusBarWindow.findViewById(R.id.keyguard_status_view);
1066        mKeyguardBottomArea =
1067                (KeyguardBottomAreaView) mStatusBarWindow.findViewById(R.id.keyguard_bottom_area);
1068        mKeyguardIndicationController =
1069                SystemUIFactory.getInstance().createKeyguardIndicationController(mContext,
1070                (ViewGroup) mStatusBarWindow.findViewById(R.id.keyguard_indication_area),
1071                mKeyguardBottomArea.getLockIcon());
1072        mKeyguardBottomArea.setKeyguardIndicationController(mKeyguardIndicationController);
1073
1074        // set the initial view visibility
1075        setAreThereNotifications();
1076
1077        // TODO: Find better place for this callback.
1078        mBatteryController.addCallback(new BatteryStateChangeCallback() {
1079            @Override
1080            public void onPowerSaveChanged(boolean isPowerSave) {
1081                mHandler.post(mCheckBarModes);
1082                if (mDozeServiceHost != null) {
1083                    mDozeServiceHost.firePowerSaveChanged(isPowerSave);
1084                }
1085            }
1086
1087            @Override
1088            public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
1089                // noop
1090            }
1091        });
1092
1093        mLightBarController = new LightBarController();
1094        if (mNavigationBar != null) {
1095            mNavigationBar.setLightBarController(mLightBarController);
1096        }
1097
1098        ScrimView scrimBehind = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_behind);
1099        ScrimView scrimInFront = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_in_front);
1100        View headsUpScrim = mStatusBarWindow.findViewById(R.id.heads_up_scrim);
1101        mScrimController = SystemUIFactory.getInstance().createScrimController(mLightBarController,
1102                scrimBehind, scrimInFront, headsUpScrim, mLockscreenWallpaper);
1103        if (mScrimSrcModeEnabled) {
1104            Runnable runnable = new Runnable() {
1105                @Override
1106                public void run() {
1107                    boolean asSrc = mBackdrop.getVisibility() != View.VISIBLE;
1108                    mScrimController.setDrawBehindAsSrc(asSrc);
1109                    mStackScroller.setDrawBackgroundAsSrc(asSrc);
1110                }
1111            };
1112            mBackdrop.setOnVisibilityChangedRunnable(runnable);
1113            runnable.run();
1114        }
1115        mHeadsUpManager.addListener(mScrimController);
1116        mStackScroller.setScrimController(mScrimController);
1117        mDozeScrimController = new DozeScrimController(mScrimController, context);
1118
1119        // Other icons
1120        mVolumeComponent = getComponent(VolumeComponent.class);
1121
1122        mKeyguardBottomArea.setStatusBar(this);
1123        mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
1124        if (UserManager.get(mContext).isUserSwitcherEnabled()) {
1125            createUserSwitcher();
1126        }
1127
1128        // Set up the quick settings tile panel
1129        View container = mStatusBarWindow.findViewById(R.id.qs_frame);
1130        if (container != null) {
1131            FragmentHostManager fragmentHostManager = FragmentHostManager.get(container);
1132            fragmentHostManager.getFragmentManager().beginTransaction()
1133                    .replace(R.id.qs_frame, new QSFragment(), QS.TAG)
1134                    .commit();
1135            new PluginFragmentListener(container, QS.TAG, QSFragment.class, QS.class)
1136                    .startListening();
1137            final QSTileHost qsh = SystemUIFactory.getInstance().createQSTileHost(mContext, this,
1138                    mIconController);
1139            mBrightnessMirrorController = new BrightnessMirrorController(mStatusBarWindow);
1140            fragmentHostManager.addTagListener(QS.TAG, (tag, f) -> {
1141                QS qs = (QS) f;
1142                if (qs instanceof QSFragment) {
1143                    ((QSFragment) qs).setHost(qsh);
1144                    mQSPanel = ((QSFragment) qs).getQsPanel();
1145                    mQSPanel.setBrightnessMirror(mBrightnessMirrorController);
1146                    mKeyguardStatusBar.setQSPanel(mQSPanel);
1147                }
1148            });
1149        }
1150
1151        mReportRejectedTouch = mStatusBarWindow.findViewById(R.id.report_rejected_touch);
1152        if (mReportRejectedTouch != null) {
1153            updateReportRejectedTouchVisibility();
1154            mReportRejectedTouch.setOnClickListener(v -> {
1155                Uri session = mFalsingManager.reportRejectedTouch();
1156                if (session == null) { return; }
1157
1158                StringWriter message = new StringWriter();
1159                message.write("Build info: ");
1160                message.write(SystemProperties.get("ro.build.description"));
1161                message.write("\nSerial number: ");
1162                message.write(SystemProperties.get("ro.serialno"));
1163                message.write("\n");
1164
1165                PrintWriter falsingPw = new PrintWriter(message);
1166                FalsingLog.dump(falsingPw);
1167                falsingPw.flush();
1168
1169                startActivityDismissingKeyguard(Intent.createChooser(new Intent(Intent.ACTION_SEND)
1170                                .setType("*/*")
1171                                .putExtra(Intent.EXTRA_SUBJECT, "Rejected touch report")
1172                                .putExtra(Intent.EXTRA_STREAM, session)
1173                                .putExtra(Intent.EXTRA_TEXT, message.toString()),
1174                        "Share rejected touch report")
1175                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
1176                        true /* onlyProvisioned */, true /* dismissShade */);
1177            });
1178        }
1179
1180
1181        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
1182        if (!pm.isScreenOn()) {
1183            mBroadcastReceiver.onReceive(mContext, new Intent(Intent.ACTION_SCREEN_OFF));
1184        }
1185        mGestureWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
1186                "GestureWakeLock");
1187        mVibrator = mContext.getSystemService(Vibrator.class);
1188        int[] pattern = mContext.getResources().getIntArray(
1189                R.array.config_cameraLaunchGestureVibePattern);
1190        mCameraLaunchGestureVibePattern = new long[pattern.length];
1191        for (int i = 0; i < pattern.length; i++) {
1192            mCameraLaunchGestureVibePattern[i] = pattern[i];
1193        }
1194
1195        // receive broadcasts
1196        IntentFilter filter = new IntentFilter();
1197        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1198        filter.addAction(Intent.ACTION_SCREEN_OFF);
1199        filter.addAction(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
1200        context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1201
1202        IntentFilter demoFilter = new IntentFilter();
1203        if (DEBUG_MEDIA_FAKE_ARTWORK) {
1204            demoFilter.addAction(ACTION_FAKE_ARTWORK);
1205        }
1206        demoFilter.addAction(ACTION_DEMO);
1207        context.registerReceiverAsUser(mDemoReceiver, UserHandle.ALL, demoFilter,
1208                android.Manifest.permission.DUMP, null);
1209
1210        // listen for USER_SETUP_COMPLETE setting (per-user)
1211        mDeviceProvisionedController.addCallback(mUserSetupObserver);
1212        mUserSetupObserver.onUserSetupChanged();
1213
1214        // disable profiling bars, since they overlap and clutter the output on app windows
1215        ThreadedRenderer.overrideProperty("disableProfileBars", "true");
1216
1217        // Private API call to make the shadows look better for Recents
1218        ThreadedRenderer.overrideProperty("ambientRatio", String.valueOf(1.5f));
1219    }
1220
1221    protected void createNavigationBar() {
1222        mNavigationBarView = NavigationBarFragment.create(mContext, (tag, fragment) -> {
1223            mNavigationBar = (NavigationBarFragment) fragment;
1224            if (mLightBarController != null) {
1225                mNavigationBar.setLightBarController(mLightBarController);
1226            }
1227            mNavigationBar.setCurrentSysuiVisibility(mSystemUiVisibility);
1228        });
1229    }
1230
1231    /**
1232     * Returns the {@link android.view.View.OnTouchListener} that will be invoked when the
1233     * background window of the status bar is clicked.
1234     */
1235    protected View.OnTouchListener getStatusBarWindowTouchListener() {
1236        return (v, event) -> {
1237            checkUserAutohide(v, event);
1238            checkRemoteInputOutside(event);
1239            if (event.getAction() == MotionEvent.ACTION_DOWN) {
1240                if (mExpandedVisible) {
1241                    animateCollapsePanels();
1242                }
1243            }
1244            return mStatusBarWindow.onTouchEvent(event);
1245        };
1246    }
1247
1248    private void inflateShelf() {
1249        mNotificationShelf =
1250                (NotificationShelf) LayoutInflater.from(mContext).inflate(
1251                        R.layout.status_bar_notification_shelf, mStackScroller, false);
1252        mNotificationShelf.setOnActivatedListener(this);
1253        mStackScroller.setShelf(mNotificationShelf);
1254        mNotificationShelf.setOnClickListener(mGoToLockedShadeListener);
1255        mNotificationShelf.setStatusBarState(mState);
1256    }
1257
1258    protected void onDensityOrFontScaleChanged() {
1259        // start old BaseStatusBar.onDensityOrFontScaleChanged().
1260        if (!KeyguardUpdateMonitor.getInstance(mContext).isSwitchingUser()) {
1261            updateNotificationsOnDensityOrFontScaleChanged();
1262        } else {
1263            mReinflateNotificationsOnUserSwitched = true;
1264        }
1265        // end old BaseStatusBar.onDensityOrFontScaleChanged().
1266        mScrimController.onDensityOrFontScaleChanged();
1267        // TODO: Remove this.
1268        if (mStatusBarView != null) mStatusBarView.onDensityOrFontScaleChanged();
1269        if (mBrightnessMirrorController != null) {
1270            mBrightnessMirrorController.onDensityOrFontScaleChanged();
1271        }
1272        inflateSignalClusters();
1273        mNotificationIconAreaController.onDensityOrFontScaleChanged(mContext);
1274        inflateDismissView();
1275        updateClearAll();
1276        inflateEmptyShadeView();
1277        updateEmptyShadeView();
1278        mStatusBarKeyguardViewManager.onDensityOrFontScaleChanged();
1279        // TODO: Bring these out of StatusBar.
1280        ((UserInfoControllerImpl) Dependency.get(UserInfoController.class))
1281                .onDensityOrFontScaleChanged();
1282        Dependency.get(UserSwitcherController.class).onDensityOrFontScaleChanged();
1283        if (mKeyguardUserSwitcher != null) {
1284            mKeyguardUserSwitcher.onDensityOrFontScaleChanged();
1285        }
1286    }
1287
1288    private void updateNotificationsOnDensityOrFontScaleChanged() {
1289        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1290        for (int i = 0; i < activeNotifications.size(); i++) {
1291            Entry entry = activeNotifications.get(i);
1292            boolean exposedGuts = mNotificationGutsExposed != null
1293                    && entry.row.getGuts() == mNotificationGutsExposed;
1294            entry.row.onDensityOrFontScaleChanged();
1295            if (exposedGuts) {
1296                mNotificationGutsExposed = entry.row.getGuts();
1297                bindGuts(entry.row, mGutsMenuItem);
1298            }
1299        }
1300    }
1301
1302    private void inflateSignalClusters() {
1303        reinflateSignalCluster(mKeyguardStatusBar);
1304    }
1305
1306    public static SignalClusterView reinflateSignalCluster(View view) {
1307        Context context = view.getContext();
1308        SignalClusterView signalCluster =
1309                (SignalClusterView) view.findViewById(R.id.signal_cluster);
1310        if (signalCluster != null) {
1311            ViewParent parent = signalCluster.getParent();
1312            if (parent instanceof ViewGroup) {
1313                ViewGroup viewParent = (ViewGroup) parent;
1314                int index = viewParent.indexOfChild(signalCluster);
1315                viewParent.removeView(signalCluster);
1316                SignalClusterView newCluster = (SignalClusterView) LayoutInflater.from(context)
1317                        .inflate(R.layout.signal_cluster_view, viewParent, false);
1318                ViewGroup.MarginLayoutParams layoutParams =
1319                        (ViewGroup.MarginLayoutParams) viewParent.getLayoutParams();
1320                layoutParams.setMarginsRelative(
1321                        context.getResources().getDimensionPixelSize(
1322                                R.dimen.signal_cluster_margin_start),
1323                        0, 0, 0);
1324                newCluster.setLayoutParams(layoutParams);
1325                viewParent.addView(newCluster, index);
1326                return newCluster;
1327            }
1328            return signalCluster;
1329        }
1330        return null;
1331    }
1332
1333    private void inflateEmptyShadeView() {
1334        mEmptyShadeView = (EmptyShadeView) LayoutInflater.from(mContext).inflate(
1335                R.layout.status_bar_no_notifications, mStackScroller, false);
1336        mStackScroller.setEmptyShadeView(mEmptyShadeView);
1337    }
1338
1339    private void inflateDismissView() {
1340        // Always inflate with a dark theme, since this sits on the scrim.
1341        ContextThemeWrapper themedContext = new ContextThemeWrapper(mContext,
1342                style.Theme_DeviceDefault);
1343        mDismissView = (DismissView) LayoutInflater.from(themedContext).inflate(
1344                R.layout.status_bar_notification_dismiss_all, mStackScroller, false);
1345        mDismissView.setOnButtonClickListener(new View.OnClickListener() {
1346            @Override
1347            public void onClick(View v) {
1348                mMetricsLogger.action(MetricsEvent.ACTION_DISMISS_ALL_NOTES);
1349                clearAllNotifications();
1350            }
1351        });
1352        mStackScroller.setDismissView(mDismissView);
1353    }
1354
1355    protected void createUserSwitcher() {
1356        mKeyguardUserSwitcher = new KeyguardUserSwitcher(mContext,
1357                (ViewStub) mStatusBarWindow.findViewById(R.id.keyguard_user_switcher),
1358                mKeyguardStatusBar, mNotificationPanel);
1359    }
1360
1361    protected void inflateStatusBarWindow(Context context) {
1362        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
1363                R.layout.super_status_bar, null);
1364    }
1365
1366    public void clearAllNotifications() {
1367
1368        // animate-swipe all dismissable notifications, then animate the shade closed
1369        int numChildren = mStackScroller.getChildCount();
1370
1371        final ArrayList<View> viewsToHide = new ArrayList<View>(numChildren);
1372        for (int i = 0; i < numChildren; i++) {
1373            final View child = mStackScroller.getChildAt(i);
1374            if (child instanceof ExpandableNotificationRow) {
1375                if (mStackScroller.canChildBeDismissed(child)) {
1376                    if (child.getVisibility() == View.VISIBLE) {
1377                        viewsToHide.add(child);
1378                    }
1379                }
1380                ExpandableNotificationRow row = (ExpandableNotificationRow) child;
1381                List<ExpandableNotificationRow> children = row.getNotificationChildren();
1382                if (row.areChildrenExpanded() && children != null) {
1383                    for (ExpandableNotificationRow childRow : children) {
1384                        if (mStackScroller.canChildBeDismissed(childRow)) {
1385                            if (childRow.getVisibility() == View.VISIBLE) {
1386                                viewsToHide.add(childRow);
1387                            }
1388                        }
1389                    }
1390                }
1391            }
1392        }
1393        if (viewsToHide.isEmpty()) {
1394            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1395            return;
1396        }
1397
1398        addPostCollapseAction(new Runnable() {
1399            @Override
1400            public void run() {
1401                mStackScroller.setDismissAllInProgress(false);
1402                try {
1403                    mBarService.onClearAllNotifications(mCurrentUserId);
1404                } catch (Exception ex) { }
1405            }
1406        });
1407
1408        performDismissAllAnimations(viewsToHide);
1409
1410    }
1411
1412    private void performDismissAllAnimations(ArrayList<View> hideAnimatedList) {
1413        Runnable animationFinishAction = new Runnable() {
1414            @Override
1415            public void run() {
1416                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1417            }
1418        };
1419
1420        // let's disable our normal animations
1421        mStackScroller.setDismissAllInProgress(true);
1422
1423        // Decrease the delay for every row we animate to give the sense of
1424        // accelerating the swipes
1425        int rowDelayDecrement = 10;
1426        int currentDelay = 140;
1427        int totalDelay = 180;
1428        int numItems = hideAnimatedList.size();
1429        for (int i = numItems - 1; i >= 0; i--) {
1430            View view = hideAnimatedList.get(i);
1431            Runnable endRunnable = null;
1432            if (i == 0) {
1433                endRunnable = animationFinishAction;
1434            }
1435            mStackScroller.dismissViewAnimated(view, endRunnable, totalDelay, 260);
1436            currentDelay = Math.max(50, currentDelay - rowDelayDecrement);
1437            totalDelay += currentDelay;
1438        }
1439    }
1440
1441    protected void setZenMode(int mode) {
1442        // start old BaseStatusBar.setZenMode().
1443        if (isDeviceProvisioned()) {
1444            mZenMode = mode;
1445            updateNotifications();
1446        }
1447        // end old BaseStatusBar.setZenMode().
1448    }
1449
1450    protected void startKeyguard() {
1451        Trace.beginSection("StatusBar#startKeyguard");
1452        KeyguardViewMediator keyguardViewMediator = getComponent(KeyguardViewMediator.class);
1453        mFingerprintUnlockController = new FingerprintUnlockController(mContext,
1454                mDozeScrimController, keyguardViewMediator,
1455                mScrimController, this, UnlockMethodCache.getInstance(mContext));
1456        mStatusBarKeyguardViewManager = keyguardViewMediator.registerStatusBar(this,
1457                getBouncerContainer(), mScrimController,
1458                mFingerprintUnlockController);
1459        mKeyguardIndicationController.setStatusBarKeyguardViewManager(
1460                mStatusBarKeyguardViewManager);
1461        mKeyguardIndicationController.setUserInfoController(
1462                Dependency.get(UserInfoController.class));
1463        mFingerprintUnlockController.setStatusBarKeyguardViewManager(mStatusBarKeyguardViewManager);
1464        mRemoteInputController.addCallback(mStatusBarKeyguardViewManager);
1465
1466        mRemoteInputController.addCallback(new RemoteInputController.Callback() {
1467            @Override
1468            public void onRemoteInputSent(Entry entry) {
1469                if (FORCE_REMOTE_INPUT_HISTORY && mKeysKeptForRemoteInput.contains(entry.key)) {
1470                    removeNotification(entry.key, null);
1471                } else if (mRemoteInputEntriesToRemoveOnCollapse.contains(entry)) {
1472                    // We're currently holding onto this notification, but from the apps point of
1473                    // view it is already canceled, so we'll need to cancel it on the apps behalf
1474                    // after sending - unless the app posts an update in the mean time, so wait a
1475                    // bit.
1476                    mHandler.postDelayed(() -> {
1477                        if (mRemoteInputEntriesToRemoveOnCollapse.remove(entry)) {
1478                            removeNotification(entry.key, null);
1479                        }
1480                    }, REMOTE_INPUT_KEPT_ENTRY_AUTO_CANCEL_DELAY);
1481                }
1482            }
1483        });
1484
1485        mKeyguardViewMediatorCallback = keyguardViewMediator.getViewMediatorCallback();
1486        mLightBarController.setFingerprintUnlockController(mFingerprintUnlockController);
1487        Trace.endSection();
1488    }
1489
1490    protected View getStatusBarView() {
1491        return mStatusBarView;
1492    }
1493
1494    public StatusBarWindowView getStatusBarWindow() {
1495        return mStatusBarWindow;
1496    }
1497
1498    protected ViewGroup getBouncerContainer() {
1499        return mStatusBarWindow;
1500    }
1501
1502    public int getStatusBarHeight() {
1503        if (mNaturalBarHeight < 0) {
1504            final Resources res = mContext.getResources();
1505            mNaturalBarHeight =
1506                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
1507        }
1508        return mNaturalBarHeight;
1509    }
1510
1511    protected boolean toggleSplitScreenMode(int metricsDockAction, int metricsUndockAction) {
1512        if (mRecents == null) {
1513            return false;
1514        }
1515        int dockSide = WindowManagerProxy.getInstance().getDockSide();
1516        if (dockSide == WindowManager.DOCKED_INVALID) {
1517            return mRecents.dockTopTask(NavigationBarGestureHelper.DRAG_MODE_NONE,
1518                    ActivityManager.DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT, null, metricsDockAction);
1519        } else {
1520            Divider divider = getComponent(Divider.class);
1521            if (divider != null && divider.isMinimized() && !divider.isHomeStackResizable()) {
1522                // Undocking from the minimized state is not supported
1523                return false;
1524            } else {
1525                EventBus.getDefault().send(new UndockingTaskEvent());
1526                if (metricsUndockAction != -1) {
1527                    mMetricsLogger.action(metricsUndockAction);
1528                }
1529            }
1530        }
1531        return true;
1532    }
1533
1534    void awakenDreams() {
1535        SystemServicesProxy.getInstance(mContext).awakenDreamsAsync();
1536    }
1537
1538    public UserHandle getCurrentUserHandle() {
1539        return new UserHandle(mCurrentUserId);
1540    }
1541
1542    public void addNotification(StatusBarNotification notification, RankingMap ranking)
1543            throws InflationException {
1544        String key = notification.getKey();
1545        if (DEBUG) Log.d(TAG, "addNotification key=" + key);
1546
1547        mNotificationData.updateRanking(ranking);
1548        Entry shadeEntry = createNotificationViews(notification);
1549        boolean isHeadsUped = shouldPeek(shadeEntry);
1550        if (!isHeadsUped && notification.getNotification().fullScreenIntent != null) {
1551            if (shouldSuppressFullScreenIntent(key)) {
1552                if (DEBUG) {
1553                    Log.d(TAG, "No Fullscreen intent: suppressed by DND: " + key);
1554                }
1555            } else if (mNotificationData.getImportance(key)
1556                    < NotificationManager.IMPORTANCE_HIGH) {
1557                if (DEBUG) {
1558                    Log.d(TAG, "No Fullscreen intent: not important enough: "
1559                            + key);
1560                }
1561            } else {
1562                // Stop screensaver if the notification has a full-screen intent.
1563                // (like an incoming phone call)
1564                awakenDreams();
1565
1566                // not immersive & a full-screen alert should be shown
1567                if (DEBUG)
1568                    Log.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
1569                try {
1570                    EventLog.writeEvent(EventLogTags.SYSUI_FULLSCREEN_NOTIFICATION,
1571                            key);
1572                    notification.getNotification().fullScreenIntent.send();
1573                    shadeEntry.notifyFullScreenIntentLaunched();
1574                    mMetricsLogger.count("note_fullscreen", 1);
1575                } catch (PendingIntent.CanceledException e) {
1576                }
1577            }
1578        }
1579        abortExistingInflation(key);
1580        mPendingNotifications.put(key, shadeEntry);
1581    }
1582
1583    private void abortExistingInflation(String key) {
1584        if (mPendingNotifications.containsKey(key)) {
1585            Entry entry = mPendingNotifications.get(key);
1586            entry.abortTask();
1587            mPendingNotifications.remove(key);
1588        }
1589        Entry addedEntry = mNotificationData.get(key);
1590        if (addedEntry != null) {
1591            addedEntry.abortTask();
1592        }
1593    }
1594
1595    private void addEntry(Entry shadeEntry) {
1596        boolean isHeadsUped = shouldPeek(shadeEntry);
1597        if (isHeadsUped) {
1598            mHeadsUpManager.showNotification(shadeEntry);
1599            // Mark as seen immediately
1600            setNotificationShown(shadeEntry.notification);
1601        }
1602        addNotificationViews(shadeEntry);
1603        // Recalculate the position of the sliding windows and the titles.
1604        setAreThereNotifications();
1605    }
1606
1607    @Override
1608    public void handleInflationException(StatusBarNotification notification, Exception e) {
1609        handleNotificationError(notification, e.getMessage());
1610    }
1611
1612    @Override
1613    public void onAsyncInflationFinished(Entry entry) {
1614        mPendingNotifications.remove(entry.key);
1615        if (mNotificationData.get(entry.key) == null) {
1616            addEntry(entry);
1617        }
1618    }
1619
1620    private boolean shouldSuppressFullScreenIntent(String key) {
1621        if (isDeviceInVrMode()) {
1622            return true;
1623        }
1624
1625        if (mPowerManager.isInteractive()) {
1626            return mNotificationData.shouldSuppressScreenOn(key);
1627        } else {
1628            return mNotificationData.shouldSuppressScreenOff(key);
1629        }
1630    }
1631
1632    protected void updateNotificationRanking(RankingMap ranking) {
1633        mNotificationData.updateRanking(ranking);
1634        updateNotifications();
1635    }
1636
1637    public void removeNotification(String key, RankingMap ranking) {
1638        boolean deferRemoval = false;
1639        abortExistingInflation(key);
1640        if (mHeadsUpManager.isHeadsUp(key)) {
1641            // A cancel() in repsonse to a remote input shouldn't be delayed, as it makes the
1642            // sending look longer than it takes.
1643            // Also we should not defer the removal if reordering isn't allowed since otherwise
1644            // some notifications can't disappear before the panel is closed.
1645            boolean ignoreEarliestRemovalTime = mRemoteInputController.isSpinning(key)
1646                    && !FORCE_REMOTE_INPUT_HISTORY
1647                    || !mVisualStabilityManager.isReorderingAllowed();
1648            deferRemoval = !mHeadsUpManager.removeNotification(key,  ignoreEarliestRemovalTime);
1649        }
1650        if (key.equals(mMediaNotificationKey)) {
1651            clearCurrentMediaNotification();
1652            updateMediaMetaData(true, true);
1653        }
1654        if (FORCE_REMOTE_INPUT_HISTORY && mRemoteInputController.isSpinning(key)) {
1655            Entry entry = mNotificationData.get(key);
1656            StatusBarNotification sbn = entry.notification;
1657
1658            Notification.Builder b = Notification.Builder
1659                    .recoverBuilder(mContext, sbn.getNotification().clone());
1660            CharSequence[] oldHistory = sbn.getNotification().extras
1661                    .getCharSequenceArray(Notification.EXTRA_REMOTE_INPUT_HISTORY);
1662            CharSequence[] newHistory;
1663            if (oldHistory == null) {
1664                newHistory = new CharSequence[1];
1665            } else {
1666                newHistory = new CharSequence[oldHistory.length + 1];
1667                for (int i = 0; i < oldHistory.length; i++) {
1668                    newHistory[i + 1] = oldHistory[i];
1669                }
1670            }
1671            newHistory[0] = String.valueOf(entry.remoteInputText);
1672            b.setRemoteInputHistory(newHistory);
1673
1674            Notification newNotification = b.build();
1675
1676            // Undo any compatibility view inflation
1677            newNotification.contentView = sbn.getNotification().contentView;
1678            newNotification.bigContentView = sbn.getNotification().bigContentView;
1679            newNotification.headsUpContentView = sbn.getNotification().headsUpContentView;
1680
1681            StatusBarNotification newSbn = new StatusBarNotification(sbn.getPackageName(),
1682                    sbn.getOpPkg(),
1683                    sbn.getId(), sbn.getTag(), sbn.getUid(), sbn.getInitialPid(),
1684                    newNotification, sbn.getUser(), sbn.getOverrideGroupKey(), sbn.getPostTime());
1685            boolean updated = false;
1686            try {
1687                updateNotification(newSbn, null);
1688                updated = true;
1689            } catch (InflationException e) {
1690                deferRemoval = false;
1691            }
1692            if (updated) {
1693                mKeysKeptForRemoteInput.add(entry.key);
1694                return;
1695            }
1696        }
1697        if (deferRemoval) {
1698            mLatestRankingMap = ranking;
1699            mHeadsUpEntriesToRemoveOnSwitch.add(mHeadsUpManager.getEntry(key));
1700            return;
1701        }
1702        Entry entry = mNotificationData.get(key);
1703
1704        if (entry != null && mRemoteInputController.isRemoteInputActive(entry)
1705                && (entry.row != null && !entry.row.isDismissed())) {
1706            mLatestRankingMap = ranking;
1707            mRemoteInputEntriesToRemoveOnCollapse.add(entry);
1708            return;
1709        }
1710
1711        if (entry != null && entry.row != null) {
1712            entry.row.setRemoved();
1713            mStackScroller.cleanUpViewState(entry.row);
1714        }
1715        // Let's remove the children if this was a summary
1716        handleGroupSummaryRemoved(key, ranking);
1717        StatusBarNotification old = removeNotificationViews(key, ranking);
1718        if (SPEW) Log.d(TAG, "removeNotification key=" + key + " old=" + old);
1719
1720        if (old != null) {
1721            if (CLOSE_PANEL_WHEN_EMPTIED && !hasActiveNotifications()
1722                    && !mNotificationPanel.isTracking() && !mNotificationPanel.isQsExpanded()) {
1723                if (mState == StatusBarState.SHADE) {
1724                    animateCollapsePanels();
1725                } else if (mState == StatusBarState.SHADE_LOCKED && !isCollapsing()) {
1726                    goToKeyguard();
1727                }
1728            }
1729        }
1730        setAreThereNotifications();
1731    }
1732
1733    /**
1734     * Ensures that the group children are cancelled immediately when the group summary is cancelled
1735     * instead of waiting for the notification manager to send all cancels. Otherwise this could
1736     * lead to flickers.
1737     *
1738     * This also ensures that the animation looks nice and only consists of a single disappear
1739     * animation instead of multiple.
1740     *
1741     * @param key the key of the notification was removed
1742     * @param ranking the current ranking
1743     */
1744    private void handleGroupSummaryRemoved(String key,
1745            RankingMap ranking) {
1746        Entry entry = mNotificationData.get(key);
1747        if (entry != null && entry.row != null
1748                && entry.row.isSummaryWithChildren()) {
1749            if (entry.notification.getOverrideGroupKey() != null && !entry.row.isDismissed()) {
1750                // We don't want to remove children for autobundled notifications as they are not
1751                // always cancelled. We only remove them if they were dismissed by the user.
1752                return;
1753            }
1754            List<ExpandableNotificationRow> notificationChildren =
1755                    entry.row.getNotificationChildren();
1756            ArrayList<ExpandableNotificationRow> toRemove = new ArrayList<>();
1757            for (int i = 0; i < notificationChildren.size(); i++) {
1758                ExpandableNotificationRow row = notificationChildren.get(i);
1759                if ((row.getStatusBarNotification().getNotification().flags
1760                        & Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1761                    // the child is a forground service notification which we can't remove!
1762                    continue;
1763                }
1764                toRemove.add(row);
1765                toRemove.get(i).setKeepInParent(true);
1766                // we need to set this state earlier as otherwise we might generate some weird
1767                // animations
1768                toRemove.get(i).setRemoved();
1769            }
1770        }
1771    }
1772
1773    protected void performRemoveNotification(StatusBarNotification n) {
1774        Entry entry = mNotificationData.get(n.getKey());
1775        if (mRemoteInputController.isRemoteInputActive(entry)) {
1776            mRemoteInputController.removeRemoteInput(entry, null);
1777        }
1778        // start old BaseStatusBar.performRemoveNotification.
1779        final String pkg = n.getPackageName();
1780        final String tag = n.getTag();
1781        final int id = n.getId();
1782        final int userId = n.getUserId();
1783        try {
1784            mBarService.onNotificationClear(pkg, tag, id, userId);
1785            if (FORCE_REMOTE_INPUT_HISTORY
1786                    && mKeysKeptForRemoteInput.contains(n.getKey())) {
1787                mKeysKeptForRemoteInput.remove(n.getKey());
1788            }
1789            removeNotification(n.getKey(), null);
1790
1791        } catch (RemoteException ex) {
1792            // system process is dead if we're here.
1793        }
1794        // end old BaseStatusBar.performRemoveNotification.
1795    }
1796
1797    private void updateNotificationShade() {
1798        if (mStackScroller == null) return;
1799
1800        // Do not modify the notifications during collapse.
1801        if (isCollapsing()) {
1802            addPostCollapseAction(new Runnable() {
1803                @Override
1804                public void run() {
1805                    updateNotificationShade();
1806                }
1807            });
1808            return;
1809        }
1810
1811        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1812        ArrayList<ExpandableNotificationRow> toShow = new ArrayList<>(activeNotifications.size());
1813        final int N = activeNotifications.size();
1814        for (int i=0; i<N; i++) {
1815            Entry ent = activeNotifications.get(i);
1816            if (ent.row.isDismissed() || ent.row.isRemoved()) {
1817                // we don't want to update removed notifications because they could
1818                // temporarily become children if they were isolated before.
1819                continue;
1820            }
1821            int vis = ent.notification.getNotification().visibility;
1822            int userId = ent.notification.getUserId();
1823
1824            // Display public version of the notification if we need to redact.
1825            boolean deviceSensitive = (isLockscreenPublicMode(mCurrentUserId)
1826                    && !userAllowsPrivateNotificationsInPublic(mCurrentUserId));
1827            boolean userSensitive = deviceSensitive || (isLockscreenPublicMode(userId)
1828                    && !userAllowsPrivateNotificationsInPublic(userId));
1829            boolean sensitiveNote = vis == Notification.VISIBILITY_PRIVATE;
1830            boolean sensitivePackage = packageHasVisibilityOverride(ent.notification.getKey());
1831            boolean sensitive = (sensitiveNote && userSensitive) || sensitivePackage;
1832            boolean showingPublic = sensitive && isLockscreenPublicMode(userId);
1833            if (showingPublic) {
1834                updatePublicContentView(ent, ent.notification);
1835            }
1836            ent.row.setSensitive(sensitive, deviceSensitive);
1837            ent.row.setNeedsRedaction(needsRedaction(ent));
1838            if (mGroupManager.isChildInGroupWithSummary(ent.row.getStatusBarNotification())) {
1839                ExpandableNotificationRow summary = mGroupManager.getGroupSummary(
1840                        ent.row.getStatusBarNotification());
1841                List<ExpandableNotificationRow> orderedChildren =
1842                        mTmpChildOrderMap.get(summary);
1843                if (orderedChildren == null) {
1844                    orderedChildren = new ArrayList<>();
1845                    mTmpChildOrderMap.put(summary, orderedChildren);
1846                }
1847                orderedChildren.add(ent.row);
1848            } else {
1849                toShow.add(ent.row);
1850            }
1851
1852        }
1853
1854        ArrayList<ExpandableNotificationRow> toRemove = new ArrayList<>();
1855        for (int i=0; i< mStackScroller.getChildCount(); i++) {
1856            View child = mStackScroller.getChildAt(i);
1857            if (!toShow.contains(child) && child instanceof ExpandableNotificationRow) {
1858                toRemove.add((ExpandableNotificationRow) child);
1859            }
1860        }
1861
1862        for (ExpandableNotificationRow remove : toRemove) {
1863            if (mGroupManager.isChildInGroupWithSummary(remove.getStatusBarNotification())) {
1864                // we are only transfering this notification to its parent, don't generate an animation
1865                mStackScroller.setChildTransferInProgress(true);
1866            }
1867            if (remove.isSummaryWithChildren()) {
1868                remove.removeAllChildren();
1869            }
1870            mStackScroller.removeView(remove);
1871            mStackScroller.setChildTransferInProgress(false);
1872        }
1873
1874        removeNotificationChildren();
1875
1876        for (int i=0; i<toShow.size(); i++) {
1877            View v = toShow.get(i);
1878            if (v.getParent() == null) {
1879                mVisualStabilityManager.notifyViewAddition(v);
1880                mStackScroller.addView(v);
1881            }
1882        }
1883
1884        addNotificationChildrenAndSort();
1885
1886        // So after all this work notifications still aren't sorted correctly.
1887        // Let's do that now by advancing through toShow and mStackScroller in
1888        // lock-step, making sure mStackScroller matches what we see in toShow.
1889        int j = 0;
1890        for (int i = 0; i < mStackScroller.getChildCount(); i++) {
1891            View child = mStackScroller.getChildAt(i);
1892            if (!(child instanceof ExpandableNotificationRow)) {
1893                // We don't care about non-notification views.
1894                continue;
1895            }
1896
1897            ExpandableNotificationRow targetChild = toShow.get(j);
1898            if (child != targetChild) {
1899                // Oops, wrong notification at this position. Put the right one
1900                // here and advance both lists.
1901                if (mVisualStabilityManager.canReorderNotification(targetChild)) {
1902                    mStackScroller.changeViewPosition(targetChild, i);
1903                } else {
1904                    mVisualStabilityManager.addReorderingAllowedCallback(this);
1905                }
1906            }
1907            j++;
1908
1909        }
1910
1911        mVisualStabilityManager.onReorderingFinished();
1912        // clear the map again for the next usage
1913        mTmpChildOrderMap.clear();
1914
1915        updateRowStates();
1916        updateSpeedBumpIndex();
1917        updateClearAll();
1918        updateEmptyShadeView();
1919
1920        updateQsExpansionEnabled();
1921
1922        // Let's also update the icons
1923        mNotificationIconAreaController.updateNotificationIcons(mNotificationData);
1924    }
1925
1926    /** @return true if the entry needs redaction when on the lockscreen. */
1927    private boolean needsRedaction(Entry ent) {
1928        int userId = ent.notification.getUserId();
1929
1930        boolean currentUserWantsRedaction = !userAllowsPrivateNotificationsInPublic(mCurrentUserId);
1931        boolean notiUserWantsRedaction = !userAllowsPrivateNotificationsInPublic(userId);
1932        boolean redactedLockscreen = currentUserWantsRedaction || notiUserWantsRedaction;
1933
1934        boolean notificationRequestsRedaction =
1935                ent.notification.getNotification().visibility == Notification.VISIBILITY_PRIVATE;
1936        boolean userForcesRedaction = packageHasVisibilityOverride(ent.notification.getKey());
1937
1938        return userForcesRedaction || notificationRequestsRedaction && redactedLockscreen;
1939    }
1940
1941    /**
1942     * Disable QS if device not provisioned.
1943     * If the user switcher is simple then disable QS during setup because
1944     * the user intends to use the lock screen user switcher, QS in not needed.
1945     */
1946    private void updateQsExpansionEnabled() {
1947        mNotificationPanel.setQsExpansionEnabled(isDeviceProvisioned()
1948                && (mUserSetup || mUserSwitcherController == null
1949                        || !mUserSwitcherController.isSimpleUserSwitcher())
1950                && ((mDisabled2 & StatusBarManager.DISABLE2_QUICK_SETTINGS) == 0)
1951                && !mDozing
1952                && !ONLY_CORE_APPS);
1953    }
1954
1955    private void addNotificationChildrenAndSort() {
1956        // Let's now add all notification children which are missing
1957        boolean orderChanged = false;
1958        for (int i = 0; i < mStackScroller.getChildCount(); i++) {
1959            View view = mStackScroller.getChildAt(i);
1960            if (!(view instanceof ExpandableNotificationRow)) {
1961                // We don't care about non-notification views.
1962                continue;
1963            }
1964
1965            ExpandableNotificationRow parent = (ExpandableNotificationRow) view;
1966            List<ExpandableNotificationRow> children = parent.getNotificationChildren();
1967            List<ExpandableNotificationRow> orderedChildren = mTmpChildOrderMap.get(parent);
1968
1969            for (int childIndex = 0; orderedChildren != null && childIndex < orderedChildren.size();
1970                    childIndex++) {
1971                ExpandableNotificationRow childView = orderedChildren.get(childIndex);
1972                if (children == null || !children.contains(childView)) {
1973                    if (childView.getParent() != null) {
1974                        Log.wtf(TAG, "trying to add a notification child that already has " +
1975                                "a parent. class:" + childView.getParent().getClass() +
1976                                "\n child: " + childView);
1977                        // This shouldn't happen. We can recover by removing it though.
1978                        ((ViewGroup) childView.getParent()).removeView(childView);
1979                    }
1980                    mVisualStabilityManager.notifyViewAddition(childView);
1981                    parent.addChildNotification(childView, childIndex);
1982                    mStackScroller.notifyGroupChildAdded(childView);
1983                }
1984            }
1985
1986            // Finally after removing and adding has been beformed we can apply the order.
1987            orderChanged |= parent.applyChildOrder(orderedChildren, mVisualStabilityManager, this);
1988        }
1989        if (orderChanged) {
1990            mStackScroller.generateChildOrderChangedEvent();
1991        }
1992    }
1993
1994    private void removeNotificationChildren() {
1995        // First let's remove all children which don't belong in the parents
1996        ArrayList<ExpandableNotificationRow> toRemove = new ArrayList<>();
1997        for (int i = 0; i < mStackScroller.getChildCount(); i++) {
1998            View view = mStackScroller.getChildAt(i);
1999            if (!(view instanceof ExpandableNotificationRow)) {
2000                // We don't care about non-notification views.
2001                continue;
2002            }
2003
2004            ExpandableNotificationRow parent = (ExpandableNotificationRow) view;
2005            List<ExpandableNotificationRow> children = parent.getNotificationChildren();
2006            List<ExpandableNotificationRow> orderedChildren = mTmpChildOrderMap.get(parent);
2007
2008            if (children != null) {
2009                toRemove.clear();
2010                for (ExpandableNotificationRow childRow : children) {
2011                    if ((orderedChildren == null
2012                            || !orderedChildren.contains(childRow))
2013                            && !childRow.keepInParent()) {
2014                        toRemove.add(childRow);
2015                    }
2016                }
2017                for (ExpandableNotificationRow remove : toRemove) {
2018                    parent.removeChildNotification(remove);
2019                    if (mNotificationData.get(remove.getStatusBarNotification().getKey()) == null) {
2020                        // We only want to add an animation if the view is completely removed
2021                        // otherwise it's just a transfer
2022                        mStackScroller.notifyGroupChildRemoved(remove,
2023                                parent.getChildrenContainer());
2024                    }
2025                }
2026            }
2027        }
2028    }
2029
2030    public void addQsTile(ComponentName tile) {
2031        mQSPanel.getHost().addTile(tile);
2032    }
2033
2034    public void remQsTile(ComponentName tile) {
2035        mQSPanel.getHost().removeTile(tile);
2036    }
2037
2038    public void clickTile(ComponentName tile) {
2039        mQSPanel.clickTile(tile);
2040    }
2041
2042    private boolean packageHasVisibilityOverride(String key) {
2043        return mNotificationData.getVisibilityOverride(key) == Notification.VISIBILITY_PRIVATE;
2044    }
2045
2046    private void updateClearAll() {
2047        boolean showDismissView =
2048                mState != StatusBarState.KEYGUARD &&
2049               hasActiveClearableNotifications();
2050        mStackScroller.updateDismissView(showDismissView);
2051    }
2052
2053    /**
2054     * Return whether there are any clearable notifications
2055     */
2056    private boolean hasActiveClearableNotifications() {
2057        int childCount = mStackScroller.getChildCount();
2058        for (int i = 0; i < childCount; i++) {
2059            View child = mStackScroller.getChildAt(i);
2060            if (!(child instanceof ExpandableNotificationRow)) {
2061                continue;
2062            }
2063            if (((ExpandableNotificationRow) child).canViewBeDismissed()) {
2064                    return true;
2065            }
2066        }
2067        return false;
2068    }
2069
2070    private void updateEmptyShadeView() {
2071        boolean showEmptyShadeView =
2072                mState != StatusBarState.KEYGUARD &&
2073                        mNotificationData.getActiveNotifications().size() == 0;
2074        mNotificationPanel.showEmptyShadeView(showEmptyShadeView);
2075    }
2076
2077    private void updateSpeedBumpIndex() {
2078        int speedBumpIndex = 0;
2079        int currentIndex = 0;
2080        final int N = mStackScroller.getChildCount();
2081        for (int i = 0; i < N; i++) {
2082            View view = mStackScroller.getChildAt(i);
2083            if (view.getVisibility() == View.GONE || !(view instanceof ExpandableNotificationRow)) {
2084                continue;
2085            }
2086            ExpandableNotificationRow row = (ExpandableNotificationRow) view;
2087            currentIndex++;
2088            if (!mNotificationData.isAmbient(row.getStatusBarNotification().getKey())) {
2089                speedBumpIndex = currentIndex;
2090            }
2091        }
2092        boolean noAmbient = speedBumpIndex == N;
2093        mStackScroller.updateSpeedBumpIndex(speedBumpIndex, noAmbient);
2094    }
2095
2096    public static boolean isTopLevelChild(Entry entry) {
2097        return entry.row.getParent() instanceof NotificationStackScrollLayout;
2098    }
2099
2100    protected void updateNotifications() {
2101        mNotificationData.filterAndSort();
2102
2103        updateNotificationShade();
2104    }
2105
2106    public void requestNotificationUpdate() {
2107        updateNotifications();
2108    }
2109
2110    protected void setAreThereNotifications() {
2111
2112        if (SPEW) {
2113            final boolean clearable = hasActiveNotifications() &&
2114                    hasActiveClearableNotifications();
2115            Log.d(TAG, "setAreThereNotifications: N=" +
2116                    mNotificationData.getActiveNotifications().size() + " any=" +
2117                    hasActiveNotifications() + " clearable=" + clearable);
2118        }
2119
2120        if (mStatusBarView != null) {
2121            final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
2122            final boolean showDot = hasActiveNotifications() && !areLightsOn();
2123            if (showDot != (nlo.getAlpha() == 1.0f)) {
2124                if (showDot) {
2125                    nlo.setAlpha(0f);
2126                    nlo.setVisibility(View.VISIBLE);
2127                }
2128                nlo.animate()
2129                        .alpha(showDot ? 1 : 0)
2130                        .setDuration(showDot ? 750 : 250)
2131                        .setInterpolator(new AccelerateInterpolator(2.0f))
2132                        .setListener(showDot ? null : new AnimatorListenerAdapter() {
2133                            @Override
2134                            public void onAnimationEnd(Animator _a) {
2135                                nlo.setVisibility(View.GONE);
2136                            }
2137                        })
2138                        .start();
2139            }
2140        }
2141
2142        findAndUpdateMediaNotifications();
2143    }
2144
2145    public void findAndUpdateMediaNotifications() {
2146        boolean metaDataChanged = false;
2147
2148        synchronized (mNotificationData) {
2149            ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
2150            final int N = activeNotifications.size();
2151
2152            // Promote the media notification with a controller in 'playing' state, if any.
2153            Entry mediaNotification = null;
2154            MediaController controller = null;
2155            for (int i = 0; i < N; i++) {
2156                final Entry entry = activeNotifications.get(i);
2157                if (isMediaNotification(entry)) {
2158                    final MediaSession.Token token =
2159                            entry.notification.getNotification().extras
2160                            .getParcelable(Notification.EXTRA_MEDIA_SESSION);
2161                    if (token != null) {
2162                        MediaController aController = new MediaController(mContext, token);
2163                        if (PlaybackState.STATE_PLAYING ==
2164                                getMediaControllerPlaybackState(aController)) {
2165                            if (DEBUG_MEDIA) {
2166                                Log.v(TAG, "DEBUG_MEDIA: found mediastyle controller matching "
2167                                        + entry.notification.getKey());
2168                            }
2169                            mediaNotification = entry;
2170                            controller = aController;
2171                            break;
2172                        }
2173                    }
2174                }
2175            }
2176            if (mediaNotification == null) {
2177                // Still nothing? OK, let's just look for live media sessions and see if they match
2178                // one of our notifications. This will catch apps that aren't (yet!) using media
2179                // notifications.
2180
2181                if (mMediaSessionManager != null) {
2182                    final List<MediaController> sessions
2183                            = mMediaSessionManager.getActiveSessionsForUser(
2184                                    null,
2185                                    UserHandle.USER_ALL);
2186
2187                    for (MediaController aController : sessions) {
2188                        if (PlaybackState.STATE_PLAYING ==
2189                                getMediaControllerPlaybackState(aController)) {
2190                            // now to see if we have one like this
2191                            final String pkg = aController.getPackageName();
2192
2193                            for (int i = 0; i < N; i++) {
2194                                final Entry entry = activeNotifications.get(i);
2195                                if (entry.notification.getPackageName().equals(pkg)) {
2196                                    if (DEBUG_MEDIA) {
2197                                        Log.v(TAG, "DEBUG_MEDIA: found controller matching "
2198                                            + entry.notification.getKey());
2199                                    }
2200                                    controller = aController;
2201                                    mediaNotification = entry;
2202                                    break;
2203                                }
2204                            }
2205                        }
2206                    }
2207                }
2208            }
2209
2210            if (controller != null && !sameSessions(mMediaController, controller)) {
2211                // We have a new media session
2212                clearCurrentMediaNotification();
2213                mMediaController = controller;
2214                mMediaController.registerCallback(mMediaListener);
2215                mMediaMetadata = mMediaController.getMetadata();
2216                if (DEBUG_MEDIA) {
2217                    Log.v(TAG, "DEBUG_MEDIA: insert listener, receive metadata: "
2218                            + mMediaMetadata);
2219                }
2220
2221                if (mediaNotification != null) {
2222                    mMediaNotificationKey = mediaNotification.notification.getKey();
2223                    if (DEBUG_MEDIA) {
2224                        Log.v(TAG, "DEBUG_MEDIA: Found new media notification: key="
2225                                + mMediaNotificationKey + " controller=" + mMediaController);
2226                    }
2227                }
2228                metaDataChanged = true;
2229            }
2230        }
2231
2232        if (metaDataChanged) {
2233            updateNotifications();
2234        }
2235        updateMediaMetaData(metaDataChanged, true);
2236    }
2237
2238    private int getMediaControllerPlaybackState(MediaController controller) {
2239        if (controller != null) {
2240            final PlaybackState playbackState = controller.getPlaybackState();
2241            if (playbackState != null) {
2242                return playbackState.getState();
2243            }
2244        }
2245        return PlaybackState.STATE_NONE;
2246    }
2247
2248    private boolean isPlaybackActive(int state) {
2249        if (state != PlaybackState.STATE_STOPPED
2250                && state != PlaybackState.STATE_ERROR
2251                && state != PlaybackState.STATE_NONE) {
2252            return true;
2253        }
2254        return false;
2255    }
2256
2257    private void clearCurrentMediaNotification() {
2258        mMediaNotificationKey = null;
2259        mMediaMetadata = null;
2260        if (mMediaController != null) {
2261            if (DEBUG_MEDIA) {
2262                Log.v(TAG, "DEBUG_MEDIA: Disconnecting from old controller: "
2263                        + mMediaController.getPackageName());
2264            }
2265            mMediaController.unregisterCallback(mMediaListener);
2266        }
2267        mMediaController = null;
2268    }
2269
2270    private boolean sameSessions(MediaController a, MediaController b) {
2271        if (a == b) return true;
2272        if (a == null) return false;
2273        return a.controlsSameSession(b);
2274    }
2275
2276    /**
2277     * Hide the album artwork that is fading out and release its bitmap.
2278     */
2279    protected Runnable mHideBackdropFront = new Runnable() {
2280        @Override
2281        public void run() {
2282            if (DEBUG_MEDIA) {
2283                Log.v(TAG, "DEBUG_MEDIA: removing fade layer");
2284            }
2285            mBackdropFront.setVisibility(View.INVISIBLE);
2286            mBackdropFront.animate().cancel();
2287            mBackdropFront.setImageDrawable(null);
2288        }
2289    };
2290
2291    /**
2292     * Refresh or remove lockscreen artwork from media metadata or the lockscreen wallpaper.
2293     */
2294    public void updateMediaMetaData(boolean metaDataChanged, boolean allowEnterAnimation) {
2295        Trace.beginSection("StatusBar#updateMediaMetaData");
2296        if (!SHOW_LOCKSCREEN_MEDIA_ARTWORK) {
2297            Trace.endSection();
2298            return;
2299        }
2300
2301        if (mBackdrop == null) {
2302            Trace.endSection();
2303            return; // called too early
2304        }
2305
2306        if (mLaunchTransitionFadingAway) {
2307            mBackdrop.setVisibility(View.INVISIBLE);
2308            Trace.endSection();
2309            return;
2310        }
2311
2312        if (DEBUG_MEDIA) {
2313            Log.v(TAG, "DEBUG_MEDIA: updating album art for notification " + mMediaNotificationKey
2314                    + " metadata=" + mMediaMetadata
2315                    + " metaDataChanged=" + metaDataChanged
2316                    + " state=" + mState);
2317        }
2318
2319        Drawable artworkDrawable = null;
2320        if (mMediaMetadata != null) {
2321            Bitmap artworkBitmap = null;
2322            artworkBitmap = mMediaMetadata.getBitmap(MediaMetadata.METADATA_KEY_ART);
2323            if (artworkBitmap == null) {
2324                artworkBitmap = mMediaMetadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
2325                // might still be null
2326            }
2327            if (artworkBitmap != null) {
2328                artworkDrawable = new BitmapDrawable(mBackdropBack.getResources(), artworkBitmap);
2329            }
2330        }
2331        boolean allowWhenShade = false;
2332        if (ENABLE_LOCKSCREEN_WALLPAPER && artworkDrawable == null) {
2333            Bitmap lockWallpaper = mLockscreenWallpaper.getBitmap();
2334            if (lockWallpaper != null) {
2335                artworkDrawable = new LockscreenWallpaper.WallpaperDrawable(
2336                        mBackdropBack.getResources(), lockWallpaper);
2337                // We're in the SHADE mode on the SIM screen - yet we still need to show
2338                // the lockscreen wallpaper in that mode.
2339                allowWhenShade = mStatusBarKeyguardViewManager != null
2340                        && mStatusBarKeyguardViewManager.isShowing();
2341            }
2342        }
2343
2344        boolean hideBecauseOccluded = mStatusBarKeyguardViewManager != null
2345                && mStatusBarKeyguardViewManager.isOccluded();
2346
2347        final boolean hasArtwork = artworkDrawable != null;
2348
2349        if ((hasArtwork || DEBUG_MEDIA_FAKE_ARTWORK)
2350                && (mState != StatusBarState.SHADE || allowWhenShade)
2351                && mFingerprintUnlockController.getMode()
2352                        != FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
2353                && !hideBecauseOccluded) {
2354            // time to show some art!
2355            if (mBackdrop.getVisibility() != View.VISIBLE) {
2356                mBackdrop.setVisibility(View.VISIBLE);
2357                if (allowEnterAnimation) {
2358                    mBackdrop.setAlpha(SRC_MIN_ALPHA);
2359                    mBackdrop.animate().alpha(1f);
2360                } else {
2361                    mBackdrop.animate().cancel();
2362                    mBackdrop.setAlpha(1f);
2363                }
2364                mStatusBarWindowManager.setBackdropShowing(true);
2365                metaDataChanged = true;
2366                if (DEBUG_MEDIA) {
2367                    Log.v(TAG, "DEBUG_MEDIA: Fading in album artwork");
2368                }
2369            }
2370            if (metaDataChanged) {
2371                if (mBackdropBack.getDrawable() != null) {
2372                    Drawable drawable =
2373                            mBackdropBack.getDrawable().getConstantState()
2374                                    .newDrawable(mBackdropFront.getResources()).mutate();
2375                    mBackdropFront.setImageDrawable(drawable);
2376                    if (mScrimSrcModeEnabled) {
2377                        mBackdropFront.getDrawable().mutate().setXfermode(mSrcOverXferMode);
2378                    }
2379                    mBackdropFront.setAlpha(1f);
2380                    mBackdropFront.setVisibility(View.VISIBLE);
2381                } else {
2382                    mBackdropFront.setVisibility(View.INVISIBLE);
2383                }
2384
2385                if (DEBUG_MEDIA_FAKE_ARTWORK) {
2386                    final int c = 0xFF000000 | (int)(Math.random() * 0xFFFFFF);
2387                    Log.v(TAG, String.format("DEBUG_MEDIA: setting new color: 0x%08x", c));
2388                    mBackdropBack.setBackgroundColor(0xFFFFFFFF);
2389                    mBackdropBack.setImageDrawable(new ColorDrawable(c));
2390                } else {
2391                    mBackdropBack.setImageDrawable(artworkDrawable);
2392                }
2393                if (mScrimSrcModeEnabled) {
2394                    mBackdropBack.getDrawable().mutate().setXfermode(mSrcXferMode);
2395                }
2396
2397                if (mBackdropFront.getVisibility() == View.VISIBLE) {
2398                    if (DEBUG_MEDIA) {
2399                        Log.v(TAG, "DEBUG_MEDIA: Crossfading album artwork from "
2400                                + mBackdropFront.getDrawable()
2401                                + " to "
2402                                + mBackdropBack.getDrawable());
2403                    }
2404                    mBackdropFront.animate()
2405                            .setDuration(250)
2406                            .alpha(0f).withEndAction(mHideBackdropFront);
2407                }
2408            }
2409        } else {
2410            // need to hide the album art, either because we are unlocked or because
2411            // the metadata isn't there to support it
2412            if (mBackdrop.getVisibility() != View.GONE) {
2413                if (DEBUG_MEDIA) {
2414                    Log.v(TAG, "DEBUG_MEDIA: Fading out album artwork");
2415                }
2416                if (mFingerprintUnlockController.getMode()
2417                        == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
2418                        || hideBecauseOccluded) {
2419
2420                    // We are unlocking directly - no animation!
2421                    mBackdrop.setVisibility(View.GONE);
2422                    mBackdropBack.setImageDrawable(null);
2423                    mStatusBarWindowManager.setBackdropShowing(false);
2424                } else {
2425                    mStatusBarWindowManager.setBackdropShowing(false);
2426                    mBackdrop.animate()
2427                            .alpha(SRC_MIN_ALPHA)
2428                            .setInterpolator(Interpolators.ACCELERATE_DECELERATE)
2429                            .setDuration(300)
2430                            .setStartDelay(0)
2431                            .withEndAction(new Runnable() {
2432                                @Override
2433                                public void run() {
2434                                    mBackdrop.setVisibility(View.GONE);
2435                                    mBackdropFront.animate().cancel();
2436                                    mBackdropBack.setImageDrawable(null);
2437                                    mHandler.post(mHideBackdropFront);
2438                                }
2439                            });
2440                    if (mKeyguardFadingAway) {
2441                        mBackdrop.animate()
2442                                // Make it disappear faster, as the focus should be on the activity
2443                                // behind.
2444                                .setDuration(mKeyguardFadingAwayDuration / 2)
2445                                .setStartDelay(mKeyguardFadingAwayDelay)
2446                                .setInterpolator(Interpolators.LINEAR)
2447                                .start();
2448                    }
2449                }
2450            }
2451        }
2452        Trace.endSection();
2453    }
2454
2455    private void updateReportRejectedTouchVisibility() {
2456        if (mReportRejectedTouch == null) {
2457            return;
2458        }
2459        mReportRejectedTouch.setVisibility(mState == StatusBarState.KEYGUARD
2460                && mFalsingManager.isReportingEnabled() ? View.VISIBLE : View.INVISIBLE);
2461    }
2462
2463    /**
2464     * State is one or more of the DISABLE constants from StatusBarManager.
2465     */
2466    @Override
2467    public void disable(int state1, int state2, boolean animate) {
2468        animate &= mStatusBarWindowState != WINDOW_STATE_HIDDEN;
2469        mDisabledUnmodified1 = state1;
2470        mDisabledUnmodified2 = state2;
2471        final int old1 = mDisabled1;
2472        final int diff1 = state1 ^ old1;
2473        mDisabled1 = state1;
2474
2475        final int old2 = mDisabled2;
2476        final int diff2 = state2 ^ old2;
2477        mDisabled2 = state2;
2478
2479        if (DEBUG) {
2480            Log.d(TAG, String.format("disable1: 0x%08x -> 0x%08x (diff1: 0x%08x)",
2481                old1, state1, diff1));
2482            Log.d(TAG, String.format("disable2: 0x%08x -> 0x%08x (diff2: 0x%08x)",
2483                old2, state2, diff2));
2484        }
2485
2486        StringBuilder flagdbg = new StringBuilder();
2487        flagdbg.append("disable<");
2488        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_EXPAND))                ? 'E' : 'e');
2489        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_EXPAND))                ? '!' : ' ');
2490        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_NOTIFICATION_ICONS))    ? 'I' : 'i');
2491        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_NOTIFICATION_ICONS))    ? '!' : ' ');
2492        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS))   ? 'A' : 'a');
2493        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS))   ? '!' : ' ');
2494        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_SYSTEM_INFO))           ? 'S' : 's');
2495        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_SYSTEM_INFO))           ? '!' : ' ');
2496        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_BACK))                  ? 'B' : 'b');
2497        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_BACK))                  ? '!' : ' ');
2498        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_HOME))                  ? 'H' : 'h');
2499        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_HOME))                  ? '!' : ' ');
2500        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_RECENT))                ? 'R' : 'r');
2501        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_RECENT))                ? '!' : ' ');
2502        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_CLOCK))                 ? 'C' : 'c');
2503        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_CLOCK))                 ? '!' : ' ');
2504        flagdbg.append(0 != ((state1 & StatusBarManager.DISABLE_SEARCH))                ? 'S' : 's');
2505        flagdbg.append(0 != ((diff1  & StatusBarManager.DISABLE_SEARCH))                ? '!' : ' ');
2506        flagdbg.append(0 != ((state2 & StatusBarManager.DISABLE2_QUICK_SETTINGS))       ? 'Q' : 'q');
2507        flagdbg.append(0 != ((diff2  & StatusBarManager.DISABLE2_QUICK_SETTINGS))       ? '!' : ' ');
2508        flagdbg.append('>');
2509        Log.d(TAG, flagdbg.toString());
2510
2511        if ((diff1 & StatusBarManager.DISABLE_EXPAND) != 0) {
2512            if ((state1 & StatusBarManager.DISABLE_EXPAND) != 0) {
2513                animateCollapsePanels();
2514            }
2515        }
2516
2517        if ((diff1 & StatusBarManager.DISABLE_RECENT) != 0) {
2518            if ((state1 & StatusBarManager.DISABLE_RECENT) != 0) {
2519                // close recents if it's visible
2520                mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
2521                mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
2522            }
2523        }
2524
2525        if ((diff1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
2526            mDisableNotificationAlerts =
2527                    (state1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0;
2528            mHeadsUpObserver.onChange(true);
2529        }
2530
2531        if ((diff2 & StatusBarManager.DISABLE2_QUICK_SETTINGS) != 0) {
2532            updateQsExpansionEnabled();
2533        }
2534    }
2535
2536    /**
2537     * Reapplies the disable flags as last requested by StatusBarManager.
2538     *
2539     * This needs to be called if state used by {@link #adjustDisableFlags} changes.
2540     */
2541    public void recomputeDisableFlags(boolean animate) {
2542        mCommandQueue.recomputeDisableFlags(animate);
2543    }
2544
2545    protected H createHandler() {
2546        return new StatusBar.H();
2547    }
2548
2549    @Override
2550    public void startActivity(Intent intent, boolean dismissShade) {
2551        startActivityDismissingKeyguard(intent, false, dismissShade);
2552    }
2553
2554    @Override
2555    public void startActivity(Intent intent, boolean onlyProvisioned, boolean dismissShade) {
2556        startActivityDismissingKeyguard(intent, onlyProvisioned, dismissShade);
2557    }
2558
2559    @Override
2560    public void startActivity(Intent intent, boolean dismissShade, Callback callback) {
2561        startActivityDismissingKeyguard(intent, false, dismissShade, callback);
2562    }
2563
2564    public void setQsExpanded(boolean expanded) {
2565        mStatusBarWindowManager.setQsExpanded(expanded);
2566        mKeyguardStatusView.setImportantForAccessibility(expanded
2567                ? View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
2568                : View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
2569    }
2570
2571    public boolean isGoingToNotificationShade() {
2572        return mLeaveOpenOnKeyguardHide;
2573    }
2574
2575    public boolean isWakeUpComingFromTouch() {
2576        return mWakeUpComingFromTouch;
2577    }
2578
2579    public boolean isFalsingThresholdNeeded() {
2580        return getBarState() == StatusBarState.KEYGUARD;
2581    }
2582
2583    public boolean isDozing() {
2584        return mDozing;
2585    }
2586
2587    @Override  // NotificationData.Environment
2588    public String getCurrentMediaNotificationKey() {
2589        return mMediaNotificationKey;
2590    }
2591
2592    public boolean isScrimSrcModeEnabled() {
2593        return mScrimSrcModeEnabled;
2594    }
2595
2596    /**
2597     * To be called when there's a state change in StatusBarKeyguardViewManager.
2598     */
2599    public void onKeyguardViewManagerStatesUpdated() {
2600        logStateToEventlog();
2601    }
2602
2603    @Override  // UnlockMethodCache.OnUnlockMethodChangedListener
2604    public void onUnlockMethodStateChanged() {
2605        logStateToEventlog();
2606    }
2607
2608    @Override
2609    public void onHeadsUpPinnedModeChanged(boolean inPinnedMode) {
2610        if (inPinnedMode) {
2611            mStatusBarWindowManager.setHeadsUpShowing(true);
2612            mStatusBarWindowManager.setForceStatusBarVisible(true);
2613            if (mNotificationPanel.isFullyCollapsed()) {
2614                // We need to ensure that the touchable region is updated before the window will be
2615                // resized, in order to not catch any touches. A layout will ensure that
2616                // onComputeInternalInsets will be called and after that we can resize the layout. Let's
2617                // make sure that the window stays small for one frame until the touchableRegion is set.
2618                mNotificationPanel.requestLayout();
2619                mStatusBarWindowManager.setForceWindowCollapsed(true);
2620                mNotificationPanel.post(new Runnable() {
2621                    @Override
2622                    public void run() {
2623                        mStatusBarWindowManager.setForceWindowCollapsed(false);
2624                    }
2625                });
2626            }
2627        } else {
2628            if (!mNotificationPanel.isFullyCollapsed() || mNotificationPanel.isTracking()) {
2629                // We are currently tracking or is open and the shade doesn't need to be kept
2630                // open artificially.
2631                mStatusBarWindowManager.setHeadsUpShowing(false);
2632            } else {
2633                // we need to keep the panel open artificially, let's wait until the animation
2634                // is finished.
2635                mHeadsUpManager.setHeadsUpGoingAway(true);
2636                mStackScroller.runAfterAnimationFinished(new Runnable() {
2637                    @Override
2638                    public void run() {
2639                        if (!mHeadsUpManager.hasPinnedHeadsUp()) {
2640                            mStatusBarWindowManager.setHeadsUpShowing(false);
2641                            mHeadsUpManager.setHeadsUpGoingAway(false);
2642                        }
2643                        removeRemoteInputEntriesKeptUntilCollapsed();
2644                    }
2645                });
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public void onHeadsUpPinned(ExpandableNotificationRow headsUp) {
2652        dismissVolumeDialog();
2653    }
2654
2655    @Override
2656    public void onHeadsUpUnPinned(ExpandableNotificationRow headsUp) {
2657    }
2658
2659    @Override
2660    public void onHeadsUpStateChanged(Entry entry, boolean isHeadsUp) {
2661        if (!isHeadsUp && mHeadsUpEntriesToRemoveOnSwitch.contains(entry)) {
2662            removeNotification(entry.key, mLatestRankingMap);
2663            mHeadsUpEntriesToRemoveOnSwitch.remove(entry);
2664            if (mHeadsUpEntriesToRemoveOnSwitch.isEmpty()) {
2665                mLatestRankingMap = null;
2666            }
2667        } else {
2668            updateNotificationRanking(null);
2669            if (isHeadsUp) {
2670                mDozeServiceHost.fireNotificationHeadsUp();
2671            }
2672        }
2673
2674    }
2675
2676    protected void updateHeadsUp(String key, Entry entry, boolean shouldPeek,
2677            boolean alertAgain) {
2678        final boolean wasHeadsUp = isHeadsUp(key);
2679        if (wasHeadsUp) {
2680            if (!shouldPeek) {
2681                // We don't want this to be interrupting anymore, lets remove it
2682                mHeadsUpManager.removeNotification(key, false /* ignoreEarliestRemovalTime */);
2683            } else {
2684                mHeadsUpManager.updateNotification(entry, alertAgain);
2685            }
2686        } else if (shouldPeek && alertAgain) {
2687            // This notification was updated to be a heads-up, show it!
2688            mHeadsUpManager.showNotification(entry);
2689        }
2690    }
2691
2692    protected void setHeadsUpUser(int newUserId) {
2693        if (mHeadsUpManager != null) {
2694            mHeadsUpManager.setUser(newUserId);
2695        }
2696    }
2697
2698    public boolean isHeadsUp(String key) {
2699        return mHeadsUpManager.isHeadsUp(key);
2700    }
2701
2702    protected boolean isSnoozedPackage(StatusBarNotification sbn) {
2703        return mHeadsUpManager.isSnoozed(sbn.getPackageName());
2704    }
2705
2706    public boolean isKeyguardCurrentlySecure() {
2707        return !mUnlockMethodCache.canSkipBouncer();
2708    }
2709
2710    public void setPanelExpanded(boolean isExpanded) {
2711        mPanelExpanded = isExpanded;
2712        mStatusBarWindowManager.setPanelExpanded(isExpanded);
2713        mVisualStabilityManager.setPanelExpanded(isExpanded);
2714        if (isExpanded && getBarState() != StatusBarState.KEYGUARD) {
2715            if (DEBUG) {
2716                Log.v(TAG, "clearing notification effects from setPanelExpanded");
2717            }
2718            clearNotificationEffects();
2719        }
2720
2721        if (!isExpanded) {
2722            removeRemoteInputEntriesKeptUntilCollapsed();
2723        }
2724    }
2725
2726    private void removeRemoteInputEntriesKeptUntilCollapsed() {
2727        for (int i = 0; i < mRemoteInputEntriesToRemoveOnCollapse.size(); i++) {
2728            Entry entry = mRemoteInputEntriesToRemoveOnCollapse.valueAt(i);
2729            mRemoteInputController.removeRemoteInput(entry, null);
2730            removeNotification(entry.key, mLatestRankingMap);
2731        }
2732        mRemoteInputEntriesToRemoveOnCollapse.clear();
2733    }
2734
2735    public void onScreenTurnedOff() {
2736        mFalsingManager.onScreenOff();
2737    }
2738
2739    public NotificationStackScrollLayout getNotificationScrollLayout() {
2740        return mStackScroller;
2741    }
2742
2743    public boolean isPulsing() {
2744        return mDozeScrimController.isPulsing();
2745    }
2746
2747    @Override
2748    public void onReorderingAllowed() {
2749        updateNotifications();
2750    }
2751
2752    public boolean isLaunchTransitionFadingAway() {
2753        return mLaunchTransitionFadingAway;
2754    }
2755
2756    public boolean hideStatusBarIconsWhenExpanded() {
2757        return mNotificationPanel.hideStatusBarIconsWhenExpanded();
2758    }
2759
2760    /**
2761     * All changes to the status bar and notifications funnel through here and are batched.
2762     */
2763    protected class H extends Handler {
2764        @Override
2765        public void handleMessage(Message m) {
2766            switch (m.what) {
2767                case MSG_TOGGLE_KEYBOARD_SHORTCUTS_MENU:
2768                    toggleKeyboardShortcuts(m.arg1);
2769                    break;
2770                case MSG_DISMISS_KEYBOARD_SHORTCUTS_MENU:
2771                    dismissKeyboardShortcuts();
2772                    break;
2773                // End old BaseStatusBar.H handling.
2774                case MSG_OPEN_NOTIFICATION_PANEL:
2775                    animateExpandNotificationsPanel();
2776                    break;
2777                case MSG_OPEN_SETTINGS_PANEL:
2778                    animateExpandSettingsPanel((String) m.obj);
2779                    break;
2780                case MSG_CLOSE_PANELS:
2781                    animateCollapsePanels();
2782                    break;
2783                case MSG_LAUNCH_TRANSITION_TIMEOUT:
2784                    onLaunchTransitionTimeout();
2785                    break;
2786            }
2787        }
2788    }
2789
2790    public void maybeEscalateHeadsUp() {
2791        Collection<HeadsUpManager.HeadsUpEntry> entries = mHeadsUpManager.getAllEntries();
2792        for (HeadsUpManager.HeadsUpEntry entry : entries) {
2793            final StatusBarNotification sbn = entry.entry.notification;
2794            final Notification notification = sbn.getNotification();
2795            if (notification.fullScreenIntent != null) {
2796                if (DEBUG) {
2797                    Log.d(TAG, "converting a heads up to fullScreen");
2798                }
2799                try {
2800                    EventLog.writeEvent(EventLogTags.SYSUI_HEADS_UP_ESCALATION,
2801                            sbn.getKey());
2802                    notification.fullScreenIntent.send();
2803                    entry.entry.notifyFullScreenIntentLaunched();
2804                } catch (PendingIntent.CanceledException e) {
2805                }
2806            }
2807        }
2808        mHeadsUpManager.releaseAllImmediately();
2809    }
2810
2811    /**
2812     * Called for system navigation gestures. First action opens the panel, second opens
2813     * settings. Down action closes the entire panel.
2814     */
2815    @Override
2816    public void handleSystemNavigationKey(int key) {
2817        if (SPEW) Log.d(TAG, "handleSystemNavigationKey: " + key);
2818        if (!panelsEnabled() || !mKeyguardMonitor.isDeviceInteractive()
2819                || mKeyguardMonitor.isShowing() && !mKeyguardMonitor.isOccluded()) {
2820            return;
2821        }
2822
2823        // Panels are not available in setup
2824        if (!mUserSetup) return;
2825
2826        if (KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP == key) {
2827            mMetricsLogger.action(MetricsEvent.ACTION_SYSTEM_NAVIGATION_KEY_UP);
2828            mNotificationPanel.collapse(false /* delayed */, 1.0f /* speedUpFactor */);
2829        } else if (KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN == key) {
2830            mMetricsLogger.action(MetricsEvent.ACTION_SYSTEM_NAVIGATION_KEY_DOWN);
2831            if (mNotificationPanel.isFullyCollapsed()) {
2832                mNotificationPanel.expand(true /* animate */);
2833                mMetricsLogger.count(NotificationPanelView.COUNTER_PANEL_OPEN, 1);
2834            } else if (!mNotificationPanel.isInSettings() && !mNotificationPanel.isExpanding()){
2835                mNotificationPanel.flingSettings(0 /* velocity */, true /* expand */);
2836                mMetricsLogger.count(NotificationPanelView.COUNTER_PANEL_OPEN_QS, 1);
2837            }
2838        }
2839
2840    }
2841
2842    boolean panelsEnabled() {
2843        return (mDisabled1 & StatusBarManager.DISABLE_EXPAND) == 0 && !ONLY_CORE_APPS;
2844    }
2845
2846    void makeExpandedVisible(boolean force) {
2847        if (SPEW) Log.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
2848        if (!force && (mExpandedVisible || !panelsEnabled())) {
2849            return;
2850        }
2851
2852        mExpandedVisible = true;
2853
2854        // Expand the window to encompass the full screen in anticipation of the drag.
2855        // This is only possible to do atomically because the status bar is at the top of the screen!
2856        mStatusBarWindowManager.setPanelVisible(true);
2857
2858        visibilityChanged(true);
2859        mWaitingForKeyguardExit = false;
2860        recomputeDisableFlags(!force /* animate */);
2861        setInteracting(StatusBarManager.WINDOW_STATUS_BAR, true);
2862    }
2863
2864    public void animateCollapsePanels() {
2865        animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
2866    }
2867
2868    private final Runnable mAnimateCollapsePanels = new Runnable() {
2869        @Override
2870        public void run() {
2871            animateCollapsePanels();
2872        }
2873    };
2874
2875    public void postAnimateCollapsePanels() {
2876        mHandler.post(mAnimateCollapsePanels);
2877    }
2878
2879    public void postAnimateOpenPanels() {
2880        mHandler.sendEmptyMessage(MSG_OPEN_SETTINGS_PANEL);
2881    }
2882
2883    @Override
2884    public void animateCollapsePanels(int flags) {
2885        animateCollapsePanels(flags, false /* force */, false /* delayed */,
2886                1.0f /* speedUpFactor */);
2887    }
2888
2889    public void animateCollapsePanels(int flags, boolean force) {
2890        animateCollapsePanels(flags, force, false /* delayed */, 1.0f /* speedUpFactor */);
2891    }
2892
2893    public void animateCollapsePanels(int flags, boolean force, boolean delayed) {
2894        animateCollapsePanels(flags, force, delayed, 1.0f /* speedUpFactor */);
2895    }
2896
2897    public void animateCollapsePanels(int flags, boolean force, boolean delayed,
2898            float speedUpFactor) {
2899        if (!force && mState != StatusBarState.SHADE) {
2900            runPostCollapseRunnables();
2901            return;
2902        }
2903        if (SPEW) {
2904            Log.d(TAG, "animateCollapse():"
2905                    + " mExpandedVisible=" + mExpandedVisible
2906                    + " flags=" + flags);
2907        }
2908
2909        if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
2910            if (!mHandler.hasMessages(MSG_HIDE_RECENT_APPS)) {
2911                mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
2912                mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
2913            }
2914        }
2915
2916        if (mStatusBarWindow != null && mNotificationPanel.canPanelBeCollapsed()) {
2917            // release focus immediately to kick off focus change transition
2918            mStatusBarWindowManager.setStatusBarFocusable(false);
2919
2920            mStatusBarWindow.cancelExpandHelper();
2921            mStatusBarView.collapsePanel(true /* animate */, delayed, speedUpFactor);
2922        }
2923    }
2924
2925    private void runPostCollapseRunnables() {
2926        ArrayList<Runnable> clonedList = new ArrayList<>(mPostCollapseRunnables);
2927        mPostCollapseRunnables.clear();
2928        int size = clonedList.size();
2929        for (int i = 0; i < size; i++) {
2930            clonedList.get(i).run();
2931        }
2932        mStatusBarKeyguardViewManager.readyForKeyguardDone();
2933    }
2934
2935    @Override
2936    public void animateExpandNotificationsPanel() {
2937        if (SPEW) Log.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
2938        if (!panelsEnabled()) {
2939            return ;
2940        }
2941
2942        mNotificationPanel.expand(true /* animate */);
2943
2944        if (false) postStartTracing();
2945    }
2946
2947    @Override
2948    public void animateExpandSettingsPanel(String subPanel) {
2949        if (SPEW) Log.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
2950        if (!panelsEnabled()) {
2951            return;
2952        }
2953
2954        // Settings are not available in setup
2955        if (!mUserSetup) return;
2956
2957
2958        if (subPanel != null) {
2959            mQSPanel.openDetails(subPanel);
2960        }
2961        mNotificationPanel.expandWithQs();
2962
2963        if (false) postStartTracing();
2964    }
2965
2966    public void animateCollapseQuickSettings() {
2967        if (mState == StatusBarState.SHADE) {
2968            mStatusBarView.collapsePanel(true, false /* delayed */, 1.0f /* speedUpFactor */);
2969        }
2970    }
2971
2972    void makeExpandedInvisible() {
2973        if (SPEW) Log.d(TAG, "makeExpandedInvisible: mExpandedVisible=" + mExpandedVisible
2974                + " mExpandedVisible=" + mExpandedVisible);
2975
2976        if (!mExpandedVisible || mStatusBarWindow == null) {
2977            return;
2978        }
2979
2980        // Ensure the panel is fully collapsed (just in case; bug 6765842, 7260868)
2981        mStatusBarView.collapsePanel(/*animate=*/ false, false /* delayed*/,
2982                1.0f /* speedUpFactor */);
2983
2984        mNotificationPanel.closeQs();
2985
2986        mExpandedVisible = false;
2987        visibilityChanged(false);
2988
2989        // Shrink the window to the size of the status bar only
2990        mStatusBarWindowManager.setPanelVisible(false);
2991        mStatusBarWindowManager.setForceStatusBarVisible(false);
2992
2993        // Close any guts that might be visible
2994        closeAndSaveGuts(true /* removeLeavebehind */, true /* force */, true /* removeControls */,
2995                -1 /* x */, -1 /* y */, true /* resetMenu */);
2996
2997        runPostCollapseRunnables();
2998        setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
2999        showBouncerIfKeyguard();
3000        recomputeDisableFlags(mNotificationPanel.hideStatusBarIconsWhenExpanded() /* animate */);
3001
3002        // Trimming will happen later if Keyguard is showing - doing it here might cause a jank in
3003        // the bouncer appear animation.
3004        if (!mStatusBarKeyguardViewManager.isShowing()) {
3005            WindowManagerGlobal.getInstance().trimMemory(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
3006        }
3007    }
3008
3009    public boolean interceptTouchEvent(MotionEvent event) {
3010        if (DEBUG_GESTURES) {
3011            if (event.getActionMasked() != MotionEvent.ACTION_MOVE) {
3012                EventLog.writeEvent(EventLogTags.SYSUI_STATUSBAR_TOUCH,
3013                        event.getActionMasked(), (int) event.getX(), (int) event.getY(),
3014                        mDisabled1, mDisabled2);
3015            }
3016
3017        }
3018
3019        if (SPEW) {
3020            Log.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled1="
3021                + mDisabled1 + " mDisabled2=" + mDisabled2 + " mTracking=" + mTracking);
3022        } else if (CHATTY) {
3023            if (event.getAction() != MotionEvent.ACTION_MOVE) {
3024                Log.d(TAG, String.format(
3025                            "panel: %s at (%f, %f) mDisabled1=0x%08x mDisabled2=0x%08x",
3026                            MotionEvent.actionToString(event.getAction()),
3027                            event.getRawX(), event.getRawY(), mDisabled1, mDisabled2));
3028            }
3029        }
3030
3031        if (DEBUG_GESTURES) {
3032            mGestureRec.add(event);
3033        }
3034
3035        if (mStatusBarWindowState == WINDOW_STATE_SHOWING) {
3036            final boolean upOrCancel =
3037                    event.getAction() == MotionEvent.ACTION_UP ||
3038                    event.getAction() == MotionEvent.ACTION_CANCEL;
3039            if (upOrCancel && !mExpandedVisible) {
3040                setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
3041            } else {
3042                setInteracting(StatusBarManager.WINDOW_STATUS_BAR, true);
3043            }
3044        }
3045        return false;
3046    }
3047
3048    public GestureRecorder getGestureRecorder() {
3049        return mGestureRec;
3050    }
3051
3052    public FingerprintUnlockController getFingerprintUnlockController() {
3053        return mFingerprintUnlockController;
3054    }
3055
3056    @Override // CommandQueue
3057    public void setWindowState(int window, int state) {
3058        boolean showing = state == WINDOW_STATE_SHOWING;
3059        if (mStatusBarWindow != null
3060                && window == StatusBarManager.WINDOW_STATUS_BAR
3061                && mStatusBarWindowState != state) {
3062            mStatusBarWindowState = state;
3063            if (DEBUG_WINDOW_STATE) Log.d(TAG, "Status bar " + windowStateToString(state));
3064            if (!showing && mState == StatusBarState.SHADE) {
3065                mStatusBarView.collapsePanel(false /* animate */, false /* delayed */,
3066                        1.0f /* speedUpFactor */);
3067            }
3068        }
3069    }
3070
3071    @Override // CommandQueue
3072    public void setSystemUiVisibility(int vis, int fullscreenStackVis, int dockedStackVis,
3073            int mask, Rect fullscreenStackBounds, Rect dockedStackBounds) {
3074        final int oldVal = mSystemUiVisibility;
3075        final int newVal = (oldVal&~mask) | (vis&mask);
3076        final int diff = newVal ^ oldVal;
3077        if (DEBUG) Log.d(TAG, String.format(
3078                "setSystemUiVisibility vis=%s mask=%s oldVal=%s newVal=%s diff=%s",
3079                Integer.toHexString(vis), Integer.toHexString(mask),
3080                Integer.toHexString(oldVal), Integer.toHexString(newVal),
3081                Integer.toHexString(diff)));
3082        boolean sbModeChanged = false;
3083        if (diff != 0) {
3084            mSystemUiVisibility = newVal;
3085
3086            // update low profile
3087            if ((diff & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
3088                setAreThereNotifications();
3089            }
3090
3091            // ready to unhide
3092            if ((vis & View.STATUS_BAR_UNHIDE) != 0) {
3093                mSystemUiVisibility &= ~View.STATUS_BAR_UNHIDE;
3094                mNoAnimationOnNextBarModeChange = true;
3095            }
3096
3097            // update status bar mode
3098            final int sbMode = computeStatusBarMode(oldVal, newVal);
3099
3100            sbModeChanged = sbMode != -1;
3101            if (sbModeChanged && sbMode != mStatusBarMode) {
3102                if (sbMode != mStatusBarMode) {
3103                    mStatusBarMode = sbMode;
3104                    checkBarModes();
3105                }
3106                touchAutoHide();
3107            }
3108
3109            if ((vis & View.NAVIGATION_BAR_UNHIDE) != 0) {
3110                mSystemUiVisibility &= ~View.NAVIGATION_BAR_UNHIDE;
3111            }
3112
3113            // send updated sysui visibility to window manager
3114            notifyUiVisibilityChanged(mSystemUiVisibility);
3115        }
3116
3117        mLightBarController.onSystemUiVisibilityChanged(fullscreenStackVis, dockedStackVis,
3118                mask, fullscreenStackBounds, dockedStackBounds, sbModeChanged, mStatusBarMode);
3119    }
3120
3121    void touchAutoHide() {
3122        // update transient bar autohide
3123        if (mStatusBarMode == MODE_SEMI_TRANSPARENT || (mNavigationBar != null
3124                && mNavigationBar.isSemiTransparent())) {
3125            scheduleAutohide();
3126        } else {
3127            cancelAutohide();
3128        }
3129    }
3130
3131    protected int computeStatusBarMode(int oldVal, int newVal) {
3132        return computeBarMode(oldVal, newVal, View.STATUS_BAR_TRANSIENT,
3133                View.STATUS_BAR_TRANSLUCENT, View.STATUS_BAR_TRANSPARENT);
3134    }
3135
3136    protected BarTransitions getStatusBarTransitions() {
3137        return mStatusBarView.getBarTransitions();
3138    }
3139
3140    protected int computeBarMode(int oldVis, int newVis,
3141            int transientFlag, int translucentFlag, int transparentFlag) {
3142        final int oldMode = barMode(oldVis, transientFlag, translucentFlag, transparentFlag);
3143        final int newMode = barMode(newVis, transientFlag, translucentFlag, transparentFlag);
3144        if (oldMode == newMode) {
3145            return -1; // no mode change
3146        }
3147        return newMode;
3148    }
3149
3150    private int barMode(int vis, int transientFlag, int translucentFlag, int transparentFlag) {
3151        int lightsOutTransparent = View.SYSTEM_UI_FLAG_LOW_PROFILE | transparentFlag;
3152        return (vis & transientFlag) != 0 ? MODE_SEMI_TRANSPARENT
3153                : (vis & translucentFlag) != 0 ? MODE_TRANSLUCENT
3154                : (vis & lightsOutTransparent) == lightsOutTransparent ? MODE_LIGHTS_OUT_TRANSPARENT
3155                : (vis & transparentFlag) != 0 ? MODE_TRANSPARENT
3156                : (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0 ? MODE_LIGHTS_OUT
3157                : MODE_OPAQUE;
3158    }
3159
3160    void checkBarModes() {
3161        if (mDemoMode) return;
3162        if (mStatusBarView != null) checkBarMode(mStatusBarMode, mStatusBarWindowState,
3163                getStatusBarTransitions());
3164        if (mNavigationBar != null) mNavigationBar.checkNavBarModes();
3165        mNoAnimationOnNextBarModeChange = false;
3166    }
3167
3168    // Called by NavigationBarFragment
3169    void setQsScrimEnabled(boolean scrimEnabled) {
3170        mNotificationPanel.setQsScrimEnabled(scrimEnabled);
3171    }
3172
3173    void checkBarMode(int mode, int windowState, BarTransitions transitions) {
3174        final boolean powerSave = mBatteryController.isPowerSave();
3175        final boolean anim = !mNoAnimationOnNextBarModeChange && mDeviceInteractive
3176                && windowState != WINDOW_STATE_HIDDEN && !powerSave;
3177        if (powerSave && getBarState() == StatusBarState.SHADE) {
3178            mode = MODE_WARNING;
3179        }
3180        transitions.transitionTo(mode, anim);
3181    }
3182
3183    private void finishBarAnimations() {
3184        if (mStatusBarView != null) {
3185            mStatusBarView.getBarTransitions().finishAnimations();
3186        }
3187        if (mNavigationBar != null) {
3188            mNavigationBar.finishBarAnimations();
3189        }
3190    }
3191
3192    private final Runnable mCheckBarModes = new Runnable() {
3193        @Override
3194        public void run() {
3195            checkBarModes();
3196        }
3197    };
3198
3199    public void setInteracting(int barWindow, boolean interacting) {
3200        final boolean changing = ((mInteractingWindows & barWindow) != 0) != interacting;
3201        mInteractingWindows = interacting
3202                ? (mInteractingWindows | barWindow)
3203                : (mInteractingWindows & ~barWindow);
3204        if (mInteractingWindows != 0) {
3205            suspendAutohide();
3206        } else {
3207            resumeSuspendedAutohide();
3208        }
3209        // manually dismiss the volume panel when interacting with the nav bar
3210        if (changing && interacting && barWindow == StatusBarManager.WINDOW_NAVIGATION_BAR) {
3211            dismissVolumeDialog();
3212        }
3213        checkBarModes();
3214    }
3215
3216    private void dismissVolumeDialog() {
3217        if (mVolumeComponent != null) {
3218            mVolumeComponent.dismissNow();
3219        }
3220    }
3221
3222    private void resumeSuspendedAutohide() {
3223        if (mAutohideSuspended) {
3224            scheduleAutohide();
3225            mHandler.postDelayed(mCheckBarModes, 500); // longer than home -> launcher
3226        }
3227    }
3228
3229    private void suspendAutohide() {
3230        mHandler.removeCallbacks(mAutohide);
3231        mHandler.removeCallbacks(mCheckBarModes);
3232        mAutohideSuspended = (mSystemUiVisibility & STATUS_OR_NAV_TRANSIENT) != 0;
3233    }
3234
3235    private void cancelAutohide() {
3236        mAutohideSuspended = false;
3237        mHandler.removeCallbacks(mAutohide);
3238    }
3239
3240    private void scheduleAutohide() {
3241        cancelAutohide();
3242        mHandler.postDelayed(mAutohide, AUTOHIDE_TIMEOUT_MS);
3243    }
3244
3245    void checkUserAutohide(View v, MotionEvent event) {
3246        if ((mSystemUiVisibility & STATUS_OR_NAV_TRANSIENT) != 0  // a transient bar is revealed
3247                && event.getAction() == MotionEvent.ACTION_OUTSIDE // touch outside the source bar
3248                && event.getX() == 0 && event.getY() == 0  // a touch outside both bars
3249                && !mRemoteInputController.isRemoteInputActive()) { // not due to typing in IME
3250            userAutohide();
3251        }
3252    }
3253
3254    private void checkRemoteInputOutside(MotionEvent event) {
3255        if (event.getAction() == MotionEvent.ACTION_OUTSIDE // touch outside the source bar
3256                && event.getX() == 0 && event.getY() == 0  // a touch outside both bars
3257                && mRemoteInputController.isRemoteInputActive()) {
3258            mRemoteInputController.closeRemoteInputs();
3259        }
3260    }
3261
3262    private void userAutohide() {
3263        cancelAutohide();
3264        mHandler.postDelayed(mAutohide, 350); // longer than app gesture -> flag clear
3265    }
3266
3267    private boolean areLightsOn() {
3268        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
3269    }
3270
3271    public void setLightsOn(boolean on) {
3272        Log.v(TAG, "setLightsOn(" + on + ")");
3273        if (on) {
3274            setSystemUiVisibility(0, 0, 0, View.SYSTEM_UI_FLAG_LOW_PROFILE,
3275                    mLastFullscreenStackBounds, mLastDockedStackBounds);
3276        } else {
3277            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, 0, 0,
3278                    View.SYSTEM_UI_FLAG_LOW_PROFILE, mLastFullscreenStackBounds,
3279                    mLastDockedStackBounds);
3280        }
3281    }
3282
3283    private void notifyUiVisibilityChanged(int vis) {
3284        try {
3285            if (mLastDispatchedSystemUiVisibility != vis) {
3286                mWindowManagerService.statusBarVisibilityChanged(vis);
3287                mLastDispatchedSystemUiVisibility = vis;
3288            }
3289        } catch (RemoteException ex) {
3290        }
3291    }
3292
3293    @Override
3294    public void topAppWindowChanged(boolean showMenu) {
3295        if (SPEW) {
3296            Log.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
3297        }
3298
3299        // See above re: lights-out policy for legacy apps.
3300        if (showMenu) setLightsOn(true);
3301    }
3302
3303    public static String viewInfo(View v) {
3304        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
3305                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
3306    }
3307
3308    @Override
3309    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3310        synchronized (mQueueLock) {
3311            pw.println("Current Status Bar state:");
3312            pw.println("  mExpandedVisible=" + mExpandedVisible
3313                    + ", mTrackingPosition=" + mTrackingPosition);
3314            pw.println("  mTracking=" + mTracking);
3315            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
3316            pw.println("  mStackScroller: " + viewInfo(mStackScroller));
3317            pw.println("  mStackScroller: " + viewInfo(mStackScroller)
3318                    + " scroll " + mStackScroller.getScrollX()
3319                    + "," + mStackScroller.getScrollY());
3320        }
3321        pw.print("  mPendingNotifications=");
3322        if (mPendingNotifications.size() == 0) {
3323            pw.println("null");
3324        } else {
3325            for (Entry entry : mPendingNotifications.values()) {
3326                pw.println(entry.notification);
3327            }
3328        }
3329
3330        pw.print("  mInteractingWindows="); pw.println(mInteractingWindows);
3331        pw.print("  mStatusBarWindowState=");
3332        pw.println(windowStateToString(mStatusBarWindowState));
3333        pw.print("  mStatusBarMode=");
3334        pw.println(BarTransitions.modeToString(mStatusBarMode));
3335        pw.print("  mDozing="); pw.println(mDozing);
3336        pw.print("  mZenMode=");
3337        pw.println(Settings.Global.zenModeToString(mZenMode));
3338        pw.print("  mUseHeadsUp=");
3339        pw.println(mUseHeadsUp);
3340        dumpBarTransitions(pw, "mStatusBarView", mStatusBarView.getBarTransitions());
3341
3342        pw.print("  mMediaSessionManager=");
3343        pw.println(mMediaSessionManager);
3344        pw.print("  mMediaNotificationKey=");
3345        pw.println(mMediaNotificationKey);
3346        pw.print("  mMediaController=");
3347        pw.print(mMediaController);
3348        if (mMediaController != null) {
3349            pw.print(" state=" + mMediaController.getPlaybackState());
3350        }
3351        pw.println();
3352        pw.print("  mMediaMetadata=");
3353        pw.print(mMediaMetadata);
3354        if (mMediaMetadata != null) {
3355            pw.print(" title=" + mMediaMetadata.getText(MediaMetadata.METADATA_KEY_TITLE));
3356        }
3357        pw.println();
3358
3359        pw.println("  Panels: ");
3360        if (mNotificationPanel != null) {
3361            pw.println("    mNotificationPanel=" +
3362                mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""));
3363            pw.print  ("      ");
3364            mNotificationPanel.dump(fd, pw, args);
3365        }
3366
3367        DozeLog.dump(pw);
3368
3369        if (DUMPTRUCK) {
3370            synchronized (mNotificationData) {
3371                mNotificationData.dump(pw, "  ");
3372            }
3373
3374            if (false) {
3375                pw.println("see the logcat for a dump of the views we have created.");
3376                // must happen on ui thread
3377                mHandler.post(new Runnable() {
3378                        @Override
3379                        public void run() {
3380                            mStatusBarView.getLocationOnScreen(mAbsPos);
3381                            Log.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
3382                                    + ") " + mStatusBarView.getWidth() + "x"
3383                                    + getStatusBarHeight());
3384                            mStatusBarView.debug();
3385                        }
3386                    });
3387            }
3388        }
3389
3390        if (DEBUG_GESTURES) {
3391            pw.print("  status bar gestures: ");
3392            mGestureRec.dump(fd, pw, args);
3393        }
3394
3395        if (mHeadsUpManager != null) {
3396            mHeadsUpManager.dump(fd, pw, args);
3397        } else {
3398            pw.println("  mHeadsUpManager: null");
3399        }
3400        if (mGroupManager != null) {
3401            mGroupManager.dump(fd, pw, args);
3402        } else {
3403            pw.println("  mGroupManager: null");
3404        }
3405
3406        mLightBarController.dump(fd, pw, args);
3407
3408        if (KeyguardUpdateMonitor.getInstance(mContext) != null) {
3409            KeyguardUpdateMonitor.getInstance(mContext).dump(fd, pw, args);
3410        }
3411
3412        FalsingManager.getInstance(mContext).dump(pw);
3413        FalsingLog.dump(pw);
3414
3415        pw.println("SharedPreferences:");
3416        for (Map.Entry<String, ?> entry : Prefs.getAll(mContext).entrySet()) {
3417            pw.print("  "); pw.print(entry.getKey()); pw.print("="); pw.println(entry.getValue());
3418        }
3419    }
3420
3421    static void dumpBarTransitions(PrintWriter pw, String var, BarTransitions transitions) {
3422        pw.print("  "); pw.print(var); pw.print(".BarTransitions.mMode=");
3423        pw.println(BarTransitions.modeToString(transitions.getMode()));
3424    }
3425
3426    public void createAndAddWindows() {
3427        addStatusBarWindow();
3428    }
3429
3430    private void addStatusBarWindow() {
3431        makeStatusBarView();
3432        mStatusBarWindowManager = Dependency.get(StatusBarWindowManager.class);
3433        mRemoteInputController = new RemoteInputController(mHeadsUpManager);
3434        mStatusBarWindowManager.add(mStatusBarWindow, getStatusBarHeight());
3435    }
3436
3437    // called by makeStatusbar and also by PhoneStatusBarView
3438    void updateDisplaySize() {
3439        mDisplay.getMetrics(mDisplayMetrics);
3440        mDisplay.getSize(mCurrentDisplaySize);
3441        if (DEBUG_GESTURES) {
3442            mGestureRec.tag("display",
3443                    String.format("%dx%d", mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels));
3444        }
3445    }
3446
3447    float getDisplayDensity() {
3448        return mDisplayMetrics.density;
3449    }
3450
3451    public void startActivityDismissingKeyguard(final Intent intent, boolean onlyProvisioned,
3452            boolean dismissShade) {
3453        startActivityDismissingKeyguard(intent, onlyProvisioned, dismissShade, null /* callback */);
3454    }
3455
3456    public void startActivityDismissingKeyguard(final Intent intent, boolean onlyProvisioned,
3457            final boolean dismissShade, final Callback callback) {
3458        if (onlyProvisioned && !isDeviceProvisioned()) return;
3459
3460        final boolean afterKeyguardGone = PreviewInflater.wouldLaunchResolverActivity(
3461                mContext, intent, mCurrentUserId);
3462        Runnable runnable = new Runnable() {
3463            @Override
3464            public void run() {
3465                mAssistManager.hideAssist();
3466                intent.setFlags(
3467                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
3468                int result = ActivityManager.START_CANCELED;
3469                ActivityOptions options = new ActivityOptions(getActivityOptions());
3470                if (intent == KeyguardBottomAreaView.INSECURE_CAMERA_INTENT) {
3471                    // Normally an activity will set it's requested rotation
3472                    // animation on its window. However when launching an activity
3473                    // causes the orientation to change this is too late. In these cases
3474                    // the default animation is used. This doesn't look good for
3475                    // the camera (as it rotates the camera contents out of sync
3476                    // with physical reality). So, we ask the WindowManager to
3477                    // force the crossfade animation if an orientation change
3478                    // happens to occur during the launch.
3479                    options.setRotationAnimationHint(
3480                            WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS);
3481                }
3482                try {
3483                    result = ActivityManager.getService().startActivityAsUser(
3484                            null, mContext.getBasePackageName(),
3485                            intent,
3486                            intent.resolveTypeIfNeeded(mContext.getContentResolver()),
3487                            null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null,
3488                            options.toBundle(), UserHandle.CURRENT.getIdentifier());
3489                } catch (RemoteException e) {
3490                    Log.w(TAG, "Unable to start activity", e);
3491                }
3492                if (callback != null) {
3493                    callback.onActivityStarted(result);
3494                }
3495            }
3496        };
3497        Runnable cancelRunnable = new Runnable() {
3498            @Override
3499            public void run() {
3500                if (callback != null) {
3501                    callback.onActivityStarted(ActivityManager.START_CANCELED);
3502                }
3503            }
3504        };
3505        executeRunnableDismissingKeyguard(runnable, cancelRunnable, dismissShade,
3506                afterKeyguardGone, true /* deferred */);
3507    }
3508
3509    public void readyForKeyguardDone() {
3510        mStatusBarKeyguardViewManager.readyForKeyguardDone();
3511    }
3512
3513    public void executeRunnableDismissingKeyguard(final Runnable runnable,
3514            final Runnable cancelAction,
3515            final boolean dismissShade,
3516            final boolean afterKeyguardGone,
3517            final boolean deferred) {
3518        dismissKeyguardThenExecute(() -> {
3519            if (runnable != null) {
3520                if (mStatusBarKeyguardViewManager.isShowing()
3521                        && mStatusBarKeyguardViewManager.isOccluded()) {
3522                    mStatusBarKeyguardViewManager.addAfterKeyguardGoneRunnable(runnable);
3523                } else {
3524                    AsyncTask.execute(runnable);
3525                }
3526            }
3527            if (dismissShade) {
3528                if (mExpandedVisible) {
3529                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */,
3530                            true /* delayed*/);
3531                } else {
3532
3533                    // Do it after DismissAction has been processed to conserve the needed ordering.
3534                    mHandler.post(this::runPostCollapseRunnables);
3535                }
3536            }
3537            return deferred;
3538        }, cancelAction, afterKeyguardGone);
3539    }
3540
3541    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
3542        @Override
3543        public void onReceive(Context context, Intent intent) {
3544            if (DEBUG) Log.v(TAG, "onReceive: " + intent);
3545            String action = intent.getAction();
3546            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
3547                KeyboardShortcuts.dismiss();
3548                if (mRemoteInputController != null) {
3549                    mRemoteInputController.closeRemoteInputs();
3550                }
3551                if (isCurrentProfile(getSendingUserId())) {
3552                    int flags = CommandQueue.FLAG_EXCLUDE_NONE;
3553                    String reason = intent.getStringExtra("reason");
3554                    if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
3555                        flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
3556                    }
3557                    animateCollapsePanels(flags);
3558                }
3559            }
3560            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
3561                notifyHeadsUpScreenOff();
3562                finishBarAnimations();
3563                resetUserExpandedStates();
3564            }
3565            else if (DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG.equals(action)) {
3566                mQSPanel.showDeviceMonitoringDialog();
3567            }
3568        }
3569    };
3570
3571    private BroadcastReceiver mDemoReceiver = new BroadcastReceiver() {
3572        @Override
3573        public void onReceive(Context context, Intent intent) {
3574            if (DEBUG) Log.v(TAG, "onReceive: " + intent);
3575            String action = intent.getAction();
3576            if (ACTION_DEMO.equals(action)) {
3577                Bundle bundle = intent.getExtras();
3578                if (bundle != null) {
3579                    String command = bundle.getString("command", "").trim().toLowerCase();
3580                    if (command.length() > 0) {
3581                        try {
3582                            dispatchDemoCommand(command, bundle);
3583                        } catch (Throwable t) {
3584                            Log.w(TAG, "Error running demo command, intent=" + intent, t);
3585                        }
3586                    }
3587                }
3588            } else if (ACTION_FAKE_ARTWORK.equals(action)) {
3589                if (DEBUG_MEDIA_FAKE_ARTWORK) {
3590                    updateMediaMetaData(true, true);
3591                }
3592            }
3593        }
3594    };
3595
3596    public void resetUserExpandedStates() {
3597        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
3598        final int notificationCount = activeNotifications.size();
3599        for (int i = 0; i < notificationCount; i++) {
3600            NotificationData.Entry entry = activeNotifications.get(i);
3601            if (entry.row != null) {
3602                entry.row.resetUserExpansion();
3603            }
3604        }
3605    }
3606
3607    protected void dismissKeyguardThenExecute(OnDismissAction action, boolean afterKeyguardGone) {
3608        dismissKeyguardThenExecute(action, null /* cancelRunnable */, afterKeyguardGone);
3609    }
3610
3611    private void dismissKeyguardThenExecute(OnDismissAction action, Runnable cancelAction,
3612            boolean afterKeyguardGone) {
3613        if (mStatusBarKeyguardViewManager.isShowing()) {
3614            mStatusBarKeyguardViewManager.dismissWithAction(action, cancelAction,
3615                    afterKeyguardGone);
3616        } else {
3617            action.onDismiss();
3618        }
3619    }
3620
3621    // SystemUIService notifies SystemBars of configuration changes, which then calls down here
3622    @Override
3623    protected void onConfigurationChanged(Configuration newConfig) {
3624        updateResources();
3625        updateDisplaySize(); // populates mDisplayMetrics
3626
3627        if (DEBUG) {
3628            Log.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
3629        }
3630
3631        updateRowStates();
3632        mScreenPinningRequest.onConfigurationChanged();
3633    }
3634
3635    public void userSwitched(int newUserId) {
3636        // Begin old BaseStatusBar.userSwitched
3637        setHeadsUpUser(newUserId);
3638        // End old BaseStatusBar.userSwitched
3639        if (MULTIUSER_DEBUG) mNotificationPanelDebugText.setText("USER " + newUserId);
3640        animateCollapsePanels();
3641        updatePublicMode();
3642        mNotificationData.filterAndSort();
3643        if (mReinflateNotificationsOnUserSwitched) {
3644            updateNotificationsOnDensityOrFontScaleChanged();
3645            mReinflateNotificationsOnUserSwitched = false;
3646        }
3647        updateNotificationShade();
3648        clearCurrentMediaNotification();
3649        setLockscreenUser(newUserId);
3650    }
3651
3652    protected void setLockscreenUser(int newUserId) {
3653        mLockscreenWallpaper.setCurrentUser(newUserId);
3654        mScrimController.setCurrentUser(newUserId);
3655        updateMediaMetaData(true, false);
3656    }
3657
3658    /**
3659     * Reload some of our resources when the configuration changes.
3660     *
3661     * We don't reload everything when the configuration changes -- we probably
3662     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
3663     * meantime, just update the things that we know change.
3664     */
3665    void updateResources() {
3666        // Update the quick setting tiles
3667        if (mQSPanel != null) {
3668            mQSPanel.updateResources();
3669        }
3670
3671        loadDimens();
3672
3673        if (mNotificationPanel != null) {
3674            mNotificationPanel.updateResources();
3675        }
3676        if (mBrightnessMirrorController != null) {
3677            mBrightnessMirrorController.updateResources();
3678        }
3679    }
3680
3681    protected void loadDimens() {
3682        final Resources res = mContext.getResources();
3683
3684        int oldBarHeight = mNaturalBarHeight;
3685        mNaturalBarHeight = res.getDimensionPixelSize(
3686                com.android.internal.R.dimen.status_bar_height);
3687        if (mStatusBarWindowManager != null && mNaturalBarHeight != oldBarHeight) {
3688            mStatusBarWindowManager.setBarHeight(mNaturalBarHeight);
3689        }
3690        mMaxAllowedKeyguardNotifications = res.getInteger(
3691                R.integer.keyguard_max_notification_count);
3692
3693        if (DEBUG) Log.v(TAG, "defineSlots");
3694    }
3695
3696    // Visibility reporting
3697
3698    protected void handleVisibleToUserChanged(boolean visibleToUser) {
3699        if (visibleToUser) {
3700            handleVisibleToUserChangedImpl(visibleToUser);
3701            startNotificationLogging();
3702        } else {
3703            stopNotificationLogging();
3704            handleVisibleToUserChangedImpl(visibleToUser);
3705        }
3706    }
3707
3708    /**
3709     * The LEDs are turned off when the notification panel is shown, even just a little bit.
3710     * See also StatusBar.setPanelExpanded for another place where we attempt to do this.
3711     */
3712    // Old BaseStatusBar.handleVisibileToUserChanged
3713    private void handleVisibleToUserChangedImpl(boolean visibleToUser) {
3714        try {
3715            if (visibleToUser) {
3716                boolean pinnedHeadsUp = mHeadsUpManager.hasPinnedHeadsUp();
3717                boolean clearNotificationEffects =
3718                        !isPanelFullyCollapsed() &&
3719                        (mState == StatusBarState.SHADE || mState == StatusBarState.SHADE_LOCKED);
3720                int notificationLoad = mNotificationData.getActiveNotifications().size();
3721                if (pinnedHeadsUp && isPanelFullyCollapsed())  {
3722                    notificationLoad = 1;
3723                } else {
3724                    mMetricsLogger.histogram("note_load", notificationLoad);
3725                }
3726                mBarService.onPanelRevealed(clearNotificationEffects, notificationLoad);
3727            } else {
3728                mBarService.onPanelHidden();
3729            }
3730        } catch (RemoteException ex) {
3731            // Won't fail unless the world has ended.
3732        }
3733    }
3734
3735    private void stopNotificationLogging() {
3736        // Report all notifications as invisible and turn down the
3737        // reporter.
3738        if (!mCurrentlyVisibleNotifications.isEmpty()) {
3739            logNotificationVisibilityChanges(Collections.<NotificationVisibility>emptyList(),
3740                    mCurrentlyVisibleNotifications);
3741            recycleAllVisibilityObjects(mCurrentlyVisibleNotifications);
3742        }
3743        mHandler.removeCallbacks(mVisibilityReporter);
3744        mStackScroller.setChildLocationsChangedListener(null);
3745    }
3746
3747    private void startNotificationLogging() {
3748        mStackScroller.setChildLocationsChangedListener(mNotificationLocationsChangedListener);
3749        // Some transitions like mVisibleToUser=false -> mVisibleToUser=true don't
3750        // cause the scroller to emit child location events. Hence generate
3751        // one ourselves to guarantee that we're reporting visible
3752        // notifications.
3753        // (Note that in cases where the scroller does emit events, this
3754        // additional event doesn't break anything.)
3755        mNotificationLocationsChangedListener.onChildLocationsChanged(mStackScroller);
3756    }
3757
3758    private void logNotificationVisibilityChanges(
3759            Collection<NotificationVisibility> newlyVisible,
3760            Collection<NotificationVisibility> noLongerVisible) {
3761        if (newlyVisible.isEmpty() && noLongerVisible.isEmpty()) {
3762            return;
3763        }
3764        NotificationVisibility[] newlyVisibleAr =
3765                newlyVisible.toArray(new NotificationVisibility[newlyVisible.size()]);
3766        NotificationVisibility[] noLongerVisibleAr =
3767                noLongerVisible.toArray(new NotificationVisibility[noLongerVisible.size()]);
3768        try {
3769            mBarService.onNotificationVisibilityChanged(newlyVisibleAr, noLongerVisibleAr);
3770        } catch (RemoteException e) {
3771            // Ignore.
3772        }
3773
3774        final int N = newlyVisible.size();
3775        if (N > 0) {
3776            String[] newlyVisibleKeyAr = new String[N];
3777            for (int i = 0; i < N; i++) {
3778                newlyVisibleKeyAr[i] = newlyVisibleAr[i].key;
3779            }
3780
3781            setNotificationsShown(newlyVisibleKeyAr);
3782        }
3783    }
3784
3785    public void onKeyguardOccludedChanged(boolean keyguardOccluded) {
3786        mNavigationBar.onKeyguardOccludedChanged(keyguardOccluded);
3787    }
3788
3789    // State logging
3790
3791    private void logStateToEventlog() {
3792        boolean isShowing = mStatusBarKeyguardViewManager.isShowing();
3793        boolean isOccluded = mStatusBarKeyguardViewManager.isOccluded();
3794        boolean isBouncerShowing = mStatusBarKeyguardViewManager.isBouncerShowing();
3795        boolean isSecure = mUnlockMethodCache.isMethodSecure();
3796        boolean canSkipBouncer = mUnlockMethodCache.canSkipBouncer();
3797        int stateFingerprint = getLoggingFingerprint(mState,
3798                isShowing,
3799                isOccluded,
3800                isBouncerShowing,
3801                isSecure,
3802                canSkipBouncer);
3803        if (stateFingerprint != mLastLoggedStateFingerprint) {
3804            if (mStatusBarStateLog == null) {
3805                mStatusBarStateLog = new LogMaker(MetricsEvent.VIEW_UNKNOWN);
3806            }
3807            mMetricsLogger.write(mStatusBarStateLog
3808                    .setCategory(isBouncerShowing ? MetricsEvent.BOUNCER : MetricsEvent.LOCKSCREEN)
3809                    .setType(isShowing ? MetricsEvent.TYPE_OPEN : MetricsEvent.TYPE_CLOSE)
3810                    .setSubtype(isSecure ? 1 : 0));
3811            EventLogTags.writeSysuiStatusBarState(mState,
3812                    isShowing ? 1 : 0,
3813                    isOccluded ? 1 : 0,
3814                    isBouncerShowing ? 1 : 0,
3815                    isSecure ? 1 : 0,
3816                    canSkipBouncer ? 1 : 0);
3817            mLastLoggedStateFingerprint = stateFingerprint;
3818        }
3819    }
3820
3821    /**
3822     * Returns a fingerprint of fields logged to eventlog
3823     */
3824    private static int getLoggingFingerprint(int statusBarState, boolean keyguardShowing,
3825            boolean keyguardOccluded, boolean bouncerShowing, boolean secure,
3826            boolean currentlyInsecure) {
3827        // Reserve 8 bits for statusBarState. We'll never go higher than
3828        // that, right? Riiiight.
3829        return (statusBarState & 0xFF)
3830                | ((keyguardShowing   ? 1 : 0) <<  8)
3831                | ((keyguardOccluded  ? 1 : 0) <<  9)
3832                | ((bouncerShowing    ? 1 : 0) << 10)
3833                | ((secure            ? 1 : 0) << 11)
3834                | ((currentlyInsecure ? 1 : 0) << 12);
3835    }
3836
3837    //
3838    // tracing
3839    //
3840
3841    void postStartTracing() {
3842        mHandler.postDelayed(mStartTracing, 3000);
3843    }
3844
3845    void vibrate() {
3846        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
3847                Context.VIBRATOR_SERVICE);
3848        vib.vibrate(250, VIBRATION_ATTRIBUTES);
3849    }
3850
3851    Runnable mStartTracing = new Runnable() {
3852        @Override
3853        public void run() {
3854            vibrate();
3855            SystemClock.sleep(250);
3856            Log.d(TAG, "startTracing");
3857            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
3858            mHandler.postDelayed(mStopTracing, 10000);
3859        }
3860    };
3861
3862    Runnable mStopTracing = new Runnable() {
3863        @Override
3864        public void run() {
3865            android.os.Debug.stopMethodTracing();
3866            Log.d(TAG, "stopTracing");
3867            vibrate();
3868        }
3869    };
3870
3871    @Override
3872    public void postQSRunnableDismissingKeyguard(final Runnable runnable) {
3873        mHandler.post(() -> {
3874            mLeaveOpenOnKeyguardHide = true;
3875            executeRunnableDismissingKeyguard(() -> mHandler.post(runnable), null, false, false,
3876                    false);
3877        });
3878    }
3879
3880    @Override
3881    public void postStartActivityDismissingKeyguard(final PendingIntent intent) {
3882        mHandler.post(() -> startPendingIntentDismissingKeyguard(intent));
3883    }
3884
3885    @Override
3886    public void postStartActivityDismissingKeyguard(final Intent intent, int delay) {
3887        mHandler.postDelayed(() ->
3888                handleStartActivityDismissingKeyguard(intent, true /*onlyProvisioned*/), delay);
3889    }
3890
3891    private void handleStartActivityDismissingKeyguard(Intent intent, boolean onlyProvisioned) {
3892        startActivityDismissingKeyguard(intent, onlyProvisioned, true /* dismissShade */);
3893    }
3894
3895    private static class FastColorDrawable extends Drawable {
3896        private final int mColor;
3897
3898        public FastColorDrawable(int color) {
3899            mColor = 0xff000000 | color;
3900        }
3901
3902        @Override
3903        public void draw(Canvas canvas) {
3904            canvas.drawColor(mColor, PorterDuff.Mode.SRC);
3905        }
3906
3907        @Override
3908        public void setAlpha(int alpha) {
3909        }
3910
3911        @Override
3912        public void setColorFilter(ColorFilter colorFilter) {
3913        }
3914
3915        @Override
3916        public int getOpacity() {
3917            return PixelFormat.OPAQUE;
3918        }
3919
3920        @Override
3921        public void setBounds(int left, int top, int right, int bottom) {
3922        }
3923
3924        @Override
3925        public void setBounds(Rect bounds) {
3926        }
3927    }
3928
3929    public void destroy() {
3930        // Begin old BaseStatusBar.destroy().
3931        mContext.unregisterReceiver(mBaseBroadcastReceiver);
3932        try {
3933            mNotificationListener.unregisterAsSystemService();
3934        } catch (RemoteException e) {
3935            // Ignore.
3936        }
3937        mDeviceProvisionedController.removeCallback(mDeviceProvisionedListener);
3938        // End old BaseStatusBar.destroy().
3939        if (mStatusBarWindow != null) {
3940            mWindowManager.removeViewImmediate(mStatusBarWindow);
3941            mStatusBarWindow = null;
3942        }
3943        if (mNavigationBarView != null) {
3944            mWindowManager.removeViewImmediate(mNavigationBarView);
3945            mNavigationBarView = null;
3946        }
3947        mContext.unregisterReceiver(mBroadcastReceiver);
3948        mContext.unregisterReceiver(mDemoReceiver);
3949        mAssistManager.destroy();
3950
3951        if (mQSPanel != null && mQSPanel.getHost() != null) {
3952            mQSPanel.getHost().destroy();
3953        }
3954        Dependency.get(ActivityStarterDelegate.class).setActivityStarterImpl(null);
3955        mDeviceProvisionedController.removeCallback(mUserSetupObserver);
3956        Dependency.get(ConfigurationController.class).removeCallback(mConfigurationListener);
3957    }
3958
3959    private boolean mDemoModeAllowed;
3960    private boolean mDemoMode;
3961
3962    @Override
3963    public void dispatchDemoCommand(String command, Bundle args) {
3964        if (!mDemoModeAllowed) {
3965            mDemoModeAllowed = Settings.Global.getInt(mContext.getContentResolver(),
3966                    DEMO_MODE_ALLOWED, 0) != 0;
3967        }
3968        if (!mDemoModeAllowed) return;
3969        if (command.equals(COMMAND_ENTER)) {
3970            mDemoMode = true;
3971        } else if (command.equals(COMMAND_EXIT)) {
3972            mDemoMode = false;
3973            checkBarModes();
3974        } else if (!mDemoMode) {
3975            // automatically enter demo mode on first demo command
3976            dispatchDemoCommand(COMMAND_ENTER, new Bundle());
3977        }
3978        boolean modeChange = command.equals(COMMAND_ENTER) || command.equals(COMMAND_EXIT);
3979        if ((modeChange || command.equals(COMMAND_VOLUME)) && mVolumeComponent != null) {
3980            mVolumeComponent.dispatchDemoCommand(command, args);
3981        }
3982        if (modeChange || command.equals(COMMAND_CLOCK)) {
3983            dispatchDemoCommandToView(command, args, R.id.clock);
3984        }
3985        if (modeChange || command.equals(COMMAND_BATTERY)) {
3986            mBatteryController.dispatchDemoCommand(command, args);
3987        }
3988        if (modeChange || command.equals(COMMAND_STATUS)) {
3989            ((StatusBarIconControllerImpl) mIconController).dispatchDemoCommand(command, args);
3990        }
3991        if (mNetworkController != null && (modeChange || command.equals(COMMAND_NETWORK))) {
3992            mNetworkController.dispatchDemoCommand(command, args);
3993        }
3994        if (modeChange || command.equals(COMMAND_NOTIFICATIONS)) {
3995            View notifications = mStatusBarView == null ? null
3996                    : mStatusBarView.findViewById(R.id.notification_icon_area);
3997            if (notifications != null) {
3998                String visible = args.getString("visible");
3999                int vis = mDemoMode && "false".equals(visible) ? View.INVISIBLE : View.VISIBLE;
4000                notifications.setVisibility(vis);
4001            }
4002        }
4003        if (command.equals(COMMAND_BARS)) {
4004            String mode = args.getString("mode");
4005            int barMode = "opaque".equals(mode) ? MODE_OPAQUE :
4006                    "translucent".equals(mode) ? MODE_TRANSLUCENT :
4007                    "semi-transparent".equals(mode) ? MODE_SEMI_TRANSPARENT :
4008                    "transparent".equals(mode) ? MODE_TRANSPARENT :
4009                    "warning".equals(mode) ? MODE_WARNING :
4010                    -1;
4011            if (barMode != -1) {
4012                boolean animate = true;
4013                if (mStatusBarView != null) {
4014                    mStatusBarView.getBarTransitions().transitionTo(barMode, animate);
4015                }
4016                if (mNavigationBar != null) {
4017                    mNavigationBar.getBarTransitions().transitionTo(barMode, animate);
4018                }
4019            }
4020        }
4021    }
4022
4023    private void dispatchDemoCommandToView(String command, Bundle args, int id) {
4024        if (mStatusBarView == null) return;
4025        View v = mStatusBarView.findViewById(id);
4026        if (v instanceof DemoMode) {
4027            ((DemoMode)v).dispatchDemoCommand(command, args);
4028        }
4029    }
4030
4031    /**
4032     * @return The {@link StatusBarState} the status bar is in.
4033     */
4034    public int getBarState() {
4035        return mState;
4036    }
4037
4038    public boolean isPanelFullyCollapsed() {
4039        return mNotificationPanel.isFullyCollapsed();
4040    }
4041
4042    public void showKeyguard() {
4043        if (mLaunchTransitionFadingAway) {
4044            mNotificationPanel.animate().cancel();
4045            onLaunchTransitionFadingEnded();
4046        }
4047        mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
4048        if (mUserSwitcherController != null && mUserSwitcherController.useFullscreenUserSwitcher()) {
4049            setBarState(StatusBarState.FULLSCREEN_USER_SWITCHER);
4050        } else {
4051            setBarState(StatusBarState.KEYGUARD);
4052        }
4053        updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
4054        if (mState == StatusBarState.KEYGUARD) {
4055            instantExpandNotificationsPanel();
4056        } else if (mState == StatusBarState.FULLSCREEN_USER_SWITCHER) {
4057            instantCollapseNotificationPanel();
4058        }
4059        mLeaveOpenOnKeyguardHide = false;
4060        if (mDraggedDownRow != null) {
4061            mDraggedDownRow.setUserLocked(false);
4062            mDraggedDownRow.notifyHeightChanged(false  /* needsAnimation */);
4063            mDraggedDownRow = null;
4064        }
4065        mPendingRemoteInputView = null;
4066        mAssistManager.onLockscreenShown();
4067    }
4068
4069    private void onLaunchTransitionFadingEnded() {
4070        mNotificationPanel.setAlpha(1.0f);
4071        mNotificationPanel.onAffordanceLaunchEnded();
4072        releaseGestureWakeLock();
4073        runLaunchTransitionEndRunnable();
4074        mLaunchTransitionFadingAway = false;
4075        mScrimController.forceHideScrims(false /* hide */);
4076        updateMediaMetaData(true /* metaDataChanged */, true);
4077    }
4078
4079    public boolean isCollapsing() {
4080        return mNotificationPanel.isCollapsing();
4081    }
4082
4083    public void addPostCollapseAction(Runnable r) {
4084        mPostCollapseRunnables.add(r);
4085    }
4086
4087    public boolean isInLaunchTransition() {
4088        return mNotificationPanel.isLaunchTransitionRunning()
4089                || mNotificationPanel.isLaunchTransitionFinished();
4090    }
4091
4092    /**
4093     * Fades the content of the keyguard away after the launch transition is done.
4094     *
4095     * @param beforeFading the runnable to be run when the circle is fully expanded and the fading
4096     *                     starts
4097     * @param endRunnable the runnable to be run when the transition is done
4098     */
4099    public void fadeKeyguardAfterLaunchTransition(final Runnable beforeFading,
4100            Runnable endRunnable) {
4101        mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
4102        mLaunchTransitionEndRunnable = endRunnable;
4103        Runnable hideRunnable = new Runnable() {
4104            @Override
4105            public void run() {
4106                mLaunchTransitionFadingAway = true;
4107                if (beforeFading != null) {
4108                    beforeFading.run();
4109                }
4110                mScrimController.forceHideScrims(true /* hide */);
4111                updateMediaMetaData(false, true);
4112                mNotificationPanel.setAlpha(1);
4113                mStackScroller.setParentNotFullyVisible(true);
4114                mNotificationPanel.animate()
4115                        .alpha(0)
4116                        .setStartDelay(FADE_KEYGUARD_START_DELAY)
4117                        .setDuration(FADE_KEYGUARD_DURATION)
4118                        .withLayer()
4119                        .withEndAction(new Runnable() {
4120                            @Override
4121                            public void run() {
4122                                onLaunchTransitionFadingEnded();
4123                            }
4124                        });
4125                mCommandQueue.appTransitionStarting(SystemClock.uptimeMillis(),
4126                        LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4127            }
4128        };
4129        if (mNotificationPanel.isLaunchTransitionRunning()) {
4130            mNotificationPanel.setLaunchTransitionEndRunnable(hideRunnable);
4131        } else {
4132            hideRunnable.run();
4133        }
4134    }
4135
4136    /**
4137     * Fades the content of the Keyguard while we are dozing and makes it invisible when finished
4138     * fading.
4139     */
4140    public void fadeKeyguardWhilePulsing() {
4141        mNotificationPanel.notifyStartFading();
4142        mNotificationPanel.animate()
4143                .alpha(0f)
4144                .setStartDelay(0)
4145                .setDuration(FADE_KEYGUARD_DURATION_PULSING)
4146                .setInterpolator(ScrimController.KEYGUARD_FADE_OUT_INTERPOLATOR)
4147                .start();
4148    }
4149
4150    /**
4151     * Plays the animation when an activity that was occluding Keyguard goes away.
4152     */
4153    public void animateKeyguardUnoccluding() {
4154        mScrimController.animateKeyguardUnoccluding(500);
4155        mNotificationPanel.setExpandedFraction(0f);
4156        animateExpandNotificationsPanel();
4157    }
4158
4159    /**
4160     * Starts the timeout when we try to start the affordances on Keyguard. We usually rely that
4161     * Keyguard goes away via fadeKeyguardAfterLaunchTransition, however, that might not happen
4162     * because the launched app crashed or something else went wrong.
4163     */
4164    public void startLaunchTransitionTimeout() {
4165        mHandler.sendEmptyMessageDelayed(MSG_LAUNCH_TRANSITION_TIMEOUT,
4166                LAUNCH_TRANSITION_TIMEOUT_MS);
4167    }
4168
4169    private void onLaunchTransitionTimeout() {
4170        Log.w(TAG, "Launch transition: Timeout!");
4171        mNotificationPanel.onAffordanceLaunchEnded();
4172        releaseGestureWakeLock();
4173        mNotificationPanel.resetViews();
4174    }
4175
4176    private void runLaunchTransitionEndRunnable() {
4177        if (mLaunchTransitionEndRunnable != null) {
4178            Runnable r = mLaunchTransitionEndRunnable;
4179
4180            // mLaunchTransitionEndRunnable might call showKeyguard, which would execute it again,
4181            // which would lead to infinite recursion. Protect against it.
4182            mLaunchTransitionEndRunnable = null;
4183            r.run();
4184        }
4185    }
4186
4187    /**
4188     * @return true if we would like to stay in the shade, false if it should go away entirely
4189     */
4190    public boolean hideKeyguard() {
4191        Trace.beginSection("StatusBar#hideKeyguard");
4192        boolean staying = mLeaveOpenOnKeyguardHide;
4193        setBarState(StatusBarState.SHADE);
4194        View viewToClick = null;
4195        if (mLeaveOpenOnKeyguardHide) {
4196            mLeaveOpenOnKeyguardHide = false;
4197            long delay = calculateGoingToFullShadeDelay();
4198            mNotificationPanel.animateToFullShade(delay);
4199            if (mDraggedDownRow != null) {
4200                mDraggedDownRow.setUserLocked(false);
4201                mDraggedDownRow = null;
4202            }
4203            viewToClick = mPendingRemoteInputView;
4204            mPendingRemoteInputView = null;
4205
4206            // Disable layout transitions in navbar for this transition because the load is just
4207            // too heavy for the CPU and GPU on any device.
4208            if (mNavigationBar != null) {
4209                mNavigationBar.disableAnimationsDuringHide(delay);
4210            }
4211        } else if (!mNotificationPanel.isCollapsing()) {
4212            instantCollapseNotificationPanel();
4213        }
4214        updateKeyguardState(staying, false /* fromShadeLocked */);
4215
4216        if (viewToClick != null && viewToClick.isAttachedToWindow()) {
4217            viewToClick.callOnClick();
4218        }
4219
4220        // Keyguard state has changed, but QS is not listening anymore. Make sure to update the tile
4221        // visibilities so next time we open the panel we know the correct height already.
4222        if (mQSPanel != null) {
4223            mQSPanel.refreshAllTiles();
4224        }
4225        mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
4226        releaseGestureWakeLock();
4227        mNotificationPanel.onAffordanceLaunchEnded();
4228        mNotificationPanel.animate().cancel();
4229        mNotificationPanel.setAlpha(1f);
4230        Trace.endSection();
4231        return staying;
4232    }
4233
4234    private void releaseGestureWakeLock() {
4235        if (mGestureWakeLock.isHeld()) {
4236            mGestureWakeLock.release();
4237        }
4238    }
4239
4240    public long calculateGoingToFullShadeDelay() {
4241        return mKeyguardFadingAwayDelay + mKeyguardFadingAwayDuration;
4242    }
4243
4244    /**
4245     * Notifies the status bar that Keyguard is going away very soon.
4246     */
4247    public void keyguardGoingAway() {
4248
4249        // Treat Keyguard exit animation as an app transition to achieve nice transition for status
4250        // bar.
4251        mKeyguardGoingAway = true;
4252        mKeyguardMonitor.notifyKeyguardGoingAway(true);
4253        mCommandQueue.appTransitionPending(true);
4254    }
4255
4256    /**
4257     * Notifies the status bar the Keyguard is fading away with the specified timings.
4258     *
4259     * @param startTime the start time of the animations in uptime millis
4260     * @param delay the precalculated animation delay in miliseconds
4261     * @param fadeoutDuration the duration of the exit animation, in milliseconds
4262     */
4263    public void setKeyguardFadingAway(long startTime, long delay, long fadeoutDuration) {
4264        mKeyguardFadingAway = true;
4265        mKeyguardFadingAwayDelay = delay;
4266        mKeyguardFadingAwayDuration = fadeoutDuration;
4267        mWaitingForKeyguardExit = false;
4268        mCommandQueue.appTransitionStarting(startTime + fadeoutDuration
4269                        - LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION,
4270                LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4271        recomputeDisableFlags(fadeoutDuration > 0 /* animate */);
4272        mCommandQueue.appTransitionStarting(
4273                    startTime - LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION,
4274                    LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4275        mKeyguardMonitor.notifyKeyguardFadingAway(delay, fadeoutDuration);
4276    }
4277
4278    public boolean isKeyguardFadingAway() {
4279        return mKeyguardFadingAway;
4280    }
4281
4282    /**
4283     * Notifies that the Keyguard fading away animation is done.
4284     */
4285    public void finishKeyguardFadingAway() {
4286        mKeyguardFadingAway = false;
4287        mKeyguardGoingAway = false;
4288        mKeyguardMonitor.notifyKeyguardDoneFading();
4289    }
4290
4291    public void stopWaitingForKeyguardExit() {
4292        mWaitingForKeyguardExit = false;
4293    }
4294
4295    private void updatePublicMode() {
4296        final boolean showingKeyguard = mStatusBarKeyguardViewManager.isShowing();
4297        final boolean devicePublic = showingKeyguard
4298                && mStatusBarKeyguardViewManager.isSecure(mCurrentUserId);
4299
4300        // Look for public mode users. Users are considered public in either case of:
4301        //   - device keyguard is shown in secure mode;
4302        //   - profile is locked with a work challenge.
4303        for (int i = mCurrentProfiles.size() - 1; i >= 0; i--) {
4304            final int userId = mCurrentProfiles.valueAt(i).id;
4305            boolean isProfilePublic = devicePublic;
4306            if (!devicePublic && userId != mCurrentUserId) {
4307                if (mStatusBarKeyguardViewManager.isSecure(userId)) {
4308                    isProfilePublic = mKeyguardManager.isDeviceLocked(userId);
4309                }
4310            }
4311            setLockscreenPublicMode(isProfilePublic, userId);
4312        }
4313    }
4314
4315    protected void updateKeyguardState(boolean goingToFullShade, boolean fromShadeLocked) {
4316        Trace.beginSection("StatusBar#updateKeyguardState");
4317        if (mState == StatusBarState.KEYGUARD) {
4318            mKeyguardIndicationController.setVisible(true);
4319            mNotificationPanel.resetViews();
4320            if (mKeyguardUserSwitcher != null) {
4321                mKeyguardUserSwitcher.setKeyguard(true, fromShadeLocked);
4322            }
4323            mStatusBarView.removePendingHideExpandedRunnables();
4324        } else {
4325            mKeyguardIndicationController.setVisible(false);
4326            if (mKeyguardUserSwitcher != null) {
4327                mKeyguardUserSwitcher.setKeyguard(false,
4328                        goingToFullShade ||
4329                        mState == StatusBarState.SHADE_LOCKED ||
4330                        fromShadeLocked);
4331            }
4332        }
4333        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4334            mScrimController.setKeyguardShowing(true);
4335        } else {
4336            mScrimController.setKeyguardShowing(false);
4337        }
4338        mNotificationPanel.setBarState(mState, mKeyguardFadingAway, goingToFullShade);
4339        updateDozingState();
4340        updatePublicMode();
4341        updateStackScrollerState(goingToFullShade, fromShadeLocked);
4342        updateNotifications();
4343        checkBarModes();
4344        updateMediaMetaData(false, mState != StatusBarState.KEYGUARD);
4345        mKeyguardMonitor.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
4346                mUnlockMethodCache.isMethodSecure(),
4347                mStatusBarKeyguardViewManager.isOccluded());
4348        Trace.endSection();
4349    }
4350
4351    private void updateDozingState() {
4352        Trace.beginSection("StatusBar#updateDozingState");
4353        boolean animate = !mDozing && mDozeServiceHost.shouldAnimateWakeup();
4354        mNotificationPanel.setDozing(mDozing, animate);
4355        mStackScroller.setDark(mDozing, animate, mWakeUpTouchLocation);
4356        mScrimController.setDozing(mDozing);
4357        mKeyguardIndicationController.setDozing(mDozing);
4358        mNotificationPanel.setDark(mDozing, animate);
4359        updateQsExpansionEnabled();
4360        mDozeScrimController.setDozing(mDozing, animate);
4361        updateRowStates();
4362        Trace.endSection();
4363    }
4364
4365    public void updateStackScrollerState(boolean goingToFullShade, boolean fromShadeLocked) {
4366        if (mStackScroller == null) return;
4367        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
4368        boolean publicMode = isAnyProfilePublicMode();
4369        mStackScroller.setHideSensitive(publicMode, goingToFullShade);
4370        mStackScroller.setDimmed(onKeyguard, fromShadeLocked /* animate */);
4371        mStackScroller.setExpandingEnabled(!onKeyguard);
4372        ActivatableNotificationView activatedChild = mStackScroller.getActivatedChild();
4373        mStackScroller.setActivatedChild(null);
4374        if (activatedChild != null) {
4375            activatedChild.makeInactive(false /* animate */);
4376        }
4377    }
4378
4379    public void userActivity() {
4380        if (mState == StatusBarState.KEYGUARD) {
4381            mKeyguardViewMediatorCallback.userActivity();
4382        }
4383    }
4384
4385    public boolean interceptMediaKey(KeyEvent event) {
4386        return mState == StatusBarState.KEYGUARD
4387                && mStatusBarKeyguardViewManager.interceptMediaKey(event);
4388    }
4389
4390    protected boolean shouldUnlockOnMenuPressed() {
4391        return mDeviceInteractive && mState != StatusBarState.SHADE
4392            && mStatusBarKeyguardViewManager.shouldDismissOnMenuPressed();
4393    }
4394
4395    public boolean onMenuPressed() {
4396        if (shouldUnlockOnMenuPressed()) {
4397            animateCollapsePanels(
4398                    CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
4399            return true;
4400        }
4401        return false;
4402    }
4403
4404    public void endAffordanceLaunch() {
4405        releaseGestureWakeLock();
4406        mNotificationPanel.onAffordanceLaunchEnded();
4407    }
4408
4409    public boolean onBackPressed() {
4410        if (mStatusBarKeyguardViewManager.onBackPressed()) {
4411            return true;
4412        }
4413        if (mNotificationPanel.isQsExpanded()) {
4414            if (mNotificationPanel.isQsDetailShowing()) {
4415                mNotificationPanel.closeQsDetail();
4416            } else {
4417                mNotificationPanel.animateCloseQs();
4418            }
4419            return true;
4420        }
4421        if (mState != StatusBarState.KEYGUARD && mState != StatusBarState.SHADE_LOCKED) {
4422            animateCollapsePanels();
4423            return true;
4424        }
4425        if (mKeyguardUserSwitcher.hideIfNotSimple(true)) {
4426            return true;
4427        }
4428        return false;
4429    }
4430
4431    public boolean onSpacePressed() {
4432        if (mDeviceInteractive && mState != StatusBarState.SHADE) {
4433            animateCollapsePanels(
4434                    CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
4435            return true;
4436        }
4437        return false;
4438    }
4439
4440    private void showBouncerIfKeyguard() {
4441        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4442            showBouncer();
4443        }
4444    }
4445
4446    protected void showBouncer() {
4447        mWaitingForKeyguardExit = mStatusBarKeyguardViewManager.isShowing();
4448        mStatusBarKeyguardViewManager.dismiss();
4449    }
4450
4451    private void instantExpandNotificationsPanel() {
4452
4453        // Make our window larger and the panel expanded.
4454        makeExpandedVisible(true);
4455        mNotificationPanel.expand(false /* animate */);
4456    }
4457
4458    private void instantCollapseNotificationPanel() {
4459        mNotificationPanel.instantCollapse();
4460    }
4461
4462    @Override
4463    public void onActivated(ActivatableNotificationView view) {
4464        mLockscreenGestureLogger.write(
4465                MetricsEvent.ACTION_LS_NOTE,
4466                0 /* lengthDp - N/A */, 0 /* velocityDp - N/A */);
4467        mKeyguardIndicationController.showTransientIndication(R.string.notification_tap_again);
4468        ActivatableNotificationView previousView = mStackScroller.getActivatedChild();
4469        if (previousView != null) {
4470            previousView.makeInactive(true /* animate */);
4471        }
4472        mStackScroller.setActivatedChild(view);
4473    }
4474
4475    /**
4476     * @param state The {@link StatusBarState} to set.
4477     */
4478    public void setBarState(int state) {
4479        // If we're visible and switched to SHADE_LOCKED (the user dragged
4480        // down on the lockscreen), clear notification LED, vibration,
4481        // ringing.
4482        // Other transitions are covered in handleVisibleToUserChanged().
4483        if (state != mState && mVisible && (state == StatusBarState.SHADE_LOCKED
4484                || (state == StatusBarState.SHADE && isGoingToNotificationShade()))) {
4485            clearNotificationEffects();
4486        }
4487        if (state == StatusBarState.KEYGUARD) {
4488            removeRemoteInputEntriesKeptUntilCollapsed();
4489            maybeEscalateHeadsUp();
4490        }
4491        mState = state;
4492        mGroupManager.setStatusBarState(state);
4493        mHeadsUpManager.setStatusBarState(state);
4494        mFalsingManager.setStatusBarState(state);
4495        mStatusBarWindowManager.setStatusBarState(state);
4496        mStackScroller.setStatusBarState(state);
4497        updateReportRejectedTouchVisibility();
4498        updateDozing();
4499        mNotificationShelf.setStatusBarState(state);
4500    }
4501
4502    @Override
4503    public void onActivationReset(ActivatableNotificationView view) {
4504        if (view == mStackScroller.getActivatedChild()) {
4505            mKeyguardIndicationController.hideTransientIndication();
4506            mStackScroller.setActivatedChild(null);
4507        }
4508    }
4509
4510    public void onTrackingStarted() {
4511        runPostCollapseRunnables();
4512    }
4513
4514    public void onClosingFinished() {
4515        runPostCollapseRunnables();
4516        if (!isPanelFullyCollapsed()) {
4517            // if we set it not to be focusable when collapsing, we have to undo it when we aborted
4518            // the closing
4519            mStatusBarWindowManager.setStatusBarFocusable(true);
4520        }
4521    }
4522
4523    public void onUnlockHintStarted() {
4524        mFalsingManager.onUnlockHintStarted();
4525        mKeyguardIndicationController.showTransientIndication(R.string.keyguard_unlock);
4526    }
4527
4528    public void onHintFinished() {
4529        // Delay the reset a bit so the user can read the text.
4530        mKeyguardIndicationController.hideTransientIndicationDelayed(HINT_RESET_DELAY_MS);
4531    }
4532
4533    public void onCameraHintStarted() {
4534        mFalsingManager.onCameraHintStarted();
4535        mKeyguardIndicationController.showTransientIndication(R.string.camera_hint);
4536    }
4537
4538    public void onVoiceAssistHintStarted() {
4539        mFalsingManager.onLeftAffordanceHintStarted();
4540        mKeyguardIndicationController.showTransientIndication(R.string.voice_hint);
4541    }
4542
4543    public void onPhoneHintStarted() {
4544        mFalsingManager.onLeftAffordanceHintStarted();
4545        mKeyguardIndicationController.showTransientIndication(R.string.phone_hint);
4546    }
4547
4548    public void onTrackingStopped(boolean expand) {
4549        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4550            if (!expand && !mUnlockMethodCache.canSkipBouncer()) {
4551                showBouncerIfKeyguard();
4552            }
4553        }
4554    }
4555
4556    protected int getMaxKeyguardNotifications(boolean recompute) {
4557        if (recompute) {
4558            mMaxKeyguardNotifications = Math.max(1,
4559                    mNotificationPanel.computeMaxKeyguardNotifications(
4560                            mMaxAllowedKeyguardNotifications));
4561            return mMaxKeyguardNotifications;
4562        }
4563        return mMaxKeyguardNotifications;
4564    }
4565
4566    public int getMaxKeyguardNotifications() {
4567        return getMaxKeyguardNotifications(false /* recompute */);
4568    }
4569
4570    // TODO: Figure out way to remove this.
4571    public NavigationBarView getNavigationBarView() {
4572        return (NavigationBarView) mNavigationBar.getView();
4573    }
4574
4575    // ---------------------- DragDownHelper.OnDragDownListener ------------------------------------
4576
4577
4578    /* Only ever called as a consequence of a lockscreen expansion gesture. */
4579    @Override
4580    public boolean onDraggedDown(View startingChild, int dragLengthY) {
4581        if (hasActiveNotifications() && (!isDozing() || isPulsing())) {
4582            mLockscreenGestureLogger.write(
4583                    MetricsEvent.ACTION_LS_SHADE,
4584                    (int) (dragLengthY / mDisplayMetrics.density),
4585                    0 /* velocityDp - N/A */);
4586
4587            // We have notifications, go to locked shade.
4588            goToLockedShade(startingChild);
4589            if (startingChild instanceof ExpandableNotificationRow) {
4590                ExpandableNotificationRow row = (ExpandableNotificationRow) startingChild;
4591                row.onExpandedByGesture(true /* drag down is always an open */);
4592            }
4593            return true;
4594        } else {
4595            // abort gesture.
4596            return false;
4597        }
4598    }
4599
4600    @Override
4601    public void onDragDownReset() {
4602        mStackScroller.setDimmed(true /* dimmed */, true /* animated */);
4603        mStackScroller.resetScrollPosition();
4604        mStackScroller.resetCheckSnoozeLeavebehind();
4605    }
4606
4607    @Override
4608    public void onCrossedThreshold(boolean above) {
4609        mStackScroller.setDimmed(!above /* dimmed */, true /* animate */);
4610    }
4611
4612    @Override
4613    public void onTouchSlopExceeded() {
4614        mStackScroller.removeLongPressCallback();
4615        mStackScroller.checkSnoozeLeavebehind();
4616    }
4617
4618    @Override
4619    public void setEmptyDragAmount(float amount) {
4620        mNotificationPanel.setEmptyDragAmount(amount);
4621    }
4622
4623    /**
4624     * If secure with redaction: Show bouncer, go to unlocked shade.
4625     *
4626     * <p>If secure without redaction or no security: Go to {@link StatusBarState#SHADE_LOCKED}.</p>
4627     *
4628     * @param expandView The view to expand after going to the shade.
4629     */
4630    public void goToLockedShade(View expandView) {
4631        int userId = mCurrentUserId;
4632        ExpandableNotificationRow row = null;
4633        if (expandView instanceof ExpandableNotificationRow) {
4634            row = (ExpandableNotificationRow) expandView;
4635            row.setUserExpanded(true /* userExpanded */, true /* allowChildExpansion */);
4636            // Indicate that the group expansion is changing at this time -- this way the group
4637            // and children backgrounds / divider animations will look correct.
4638            row.setGroupExpansionChanging(true);
4639            if (row.getStatusBarNotification() != null) {
4640                userId = row.getStatusBarNotification().getUserId();
4641            }
4642        }
4643        boolean fullShadeNeedsBouncer = !userAllowsPrivateNotificationsInPublic(mCurrentUserId)
4644                || !mShowLockscreenNotifications || mFalsingManager.shouldEnforceBouncer();
4645        if (isLockscreenPublicMode(userId) && fullShadeNeedsBouncer) {
4646            mLeaveOpenOnKeyguardHide = true;
4647            showBouncerIfKeyguard();
4648            mDraggedDownRow = row;
4649            mPendingRemoteInputView = null;
4650        } else {
4651            mNotificationPanel.animateToFullShade(0 /* delay */);
4652            setBarState(StatusBarState.SHADE_LOCKED);
4653            updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
4654        }
4655    }
4656
4657    public void onLockedNotificationImportanceChange(OnDismissAction dismissAction) {
4658        mLeaveOpenOnKeyguardHide = true;
4659        dismissKeyguardThenExecute(dismissAction, true /* afterKeyguardGone */);
4660    }
4661
4662    protected void onLockedRemoteInput(ExpandableNotificationRow row, View clicked) {
4663        mLeaveOpenOnKeyguardHide = true;
4664        showBouncer();
4665        mPendingRemoteInputView = clicked;
4666    }
4667
4668    protected void onMakeExpandedVisibleForRemoteInput(ExpandableNotificationRow row,
4669            View clickedView) {
4670        if (isKeyguardShowing()) {
4671            onLockedRemoteInput(row, clickedView);
4672        } else {
4673            row.setUserExpanded(true);
4674            row.getPrivateLayout().setOnExpandedVisibleListener(clickedView::performClick);
4675        }
4676    }
4677
4678    protected boolean startWorkChallengeIfNecessary(int userId, IntentSender intendSender,
4679            String notificationKey) {
4680        // Clear pending remote view, as we do not want to trigger pending remote input view when
4681        // it's called by other code
4682        mPendingWorkRemoteInputView = null;
4683        // Begin old BaseStatusBar.startWorkChallengeIfNecessary.
4684        final Intent newIntent = mKeyguardManager.createConfirmDeviceCredentialIntent(null,
4685                null, userId);
4686        if (newIntent == null) {
4687            return false;
4688        }
4689        final Intent callBackIntent = new Intent(NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION);
4690        callBackIntent.putExtra(Intent.EXTRA_INTENT, intendSender);
4691        callBackIntent.putExtra(Intent.EXTRA_INDEX, notificationKey);
4692        callBackIntent.setPackage(mContext.getPackageName());
4693
4694        PendingIntent callBackPendingIntent = PendingIntent.getBroadcast(
4695                mContext,
4696                0,
4697                callBackIntent,
4698                PendingIntent.FLAG_CANCEL_CURRENT |
4699                        PendingIntent.FLAG_ONE_SHOT |
4700                        PendingIntent.FLAG_IMMUTABLE);
4701        newIntent.putExtra(
4702                Intent.EXTRA_INTENT,
4703                callBackPendingIntent.getIntentSender());
4704        try {
4705            ActivityManager.getService().startConfirmDeviceCredentialIntent(newIntent,
4706                    null /*options*/);
4707        } catch (RemoteException ex) {
4708            // ignore
4709        }
4710        return true;
4711        // End old BaseStatusBar.startWorkChallengeIfNecessary.
4712    }
4713
4714    protected void onLockedWorkRemoteInput(int userId, ExpandableNotificationRow row,
4715            View clicked) {
4716        // Collapse notification and show work challenge
4717        animateCollapsePanels();
4718        startWorkChallengeIfNecessary(userId, null, null);
4719        // Add pending remote input view after starting work challenge, as starting work challenge
4720        // will clear all previous pending review view
4721        mPendingWorkRemoteInputView = clicked;
4722    }
4723
4724    private boolean isAnyProfilePublicMode() {
4725        for (int i = mCurrentProfiles.size() - 1; i >= 0; i--) {
4726            if (isLockscreenPublicMode(mCurrentProfiles.valueAt(i).id)) {
4727                return true;
4728            }
4729        }
4730        return false;
4731    }
4732
4733    protected void onWorkChallengeChanged() {
4734        updatePublicMode();
4735        updateNotifications();
4736        if (mPendingWorkRemoteInputView != null && !isAnyProfilePublicMode()) {
4737            // Expand notification panel and the notification row, then click on remote input view
4738            final Runnable clickPendingViewRunnable = new Runnable() {
4739                @Override
4740                public void run() {
4741                    final View pendingWorkRemoteInputView = mPendingWorkRemoteInputView;
4742                    if (pendingWorkRemoteInputView == null) {
4743                        return;
4744                    }
4745
4746                    // Climb up the hierarchy until we get to the container for this row.
4747                    ViewParent p = pendingWorkRemoteInputView.getParent();
4748                    while (!(p instanceof ExpandableNotificationRow)) {
4749                        if (p == null) {
4750                            return;
4751                        }
4752                        p = p.getParent();
4753                    }
4754
4755                    final ExpandableNotificationRow row = (ExpandableNotificationRow) p;
4756                    ViewParent viewParent = row.getParent();
4757                    if (viewParent instanceof NotificationStackScrollLayout) {
4758                        final NotificationStackScrollLayout scrollLayout =
4759                                (NotificationStackScrollLayout) viewParent;
4760                        row.makeActionsVisibile();
4761                        row.post(new Runnable() {
4762                            @Override
4763                            public void run() {
4764                                final Runnable finishScrollingCallback = new Runnable() {
4765                                    @Override
4766                                    public void run() {
4767                                        mPendingWorkRemoteInputView.callOnClick();
4768                                        mPendingWorkRemoteInputView = null;
4769                                        scrollLayout.setFinishScrollingCallback(null);
4770                                    }
4771                                };
4772                                if (scrollLayout.scrollTo(row)) {
4773                                    // It scrolls! So call it when it's finished.
4774                                    scrollLayout.setFinishScrollingCallback(
4775                                            finishScrollingCallback);
4776                                } else {
4777                                    // It does not scroll, so call it now!
4778                                    finishScrollingCallback.run();
4779                                }
4780                            }
4781                        });
4782                    }
4783                }
4784            };
4785            mNotificationPanel.getViewTreeObserver().addOnGlobalLayoutListener(
4786                    new ViewTreeObserver.OnGlobalLayoutListener() {
4787                        @Override
4788                        public void onGlobalLayout() {
4789                            if (mNotificationPanel.mStatusBar.getStatusBarWindow()
4790                                    .getHeight() != mNotificationPanel.mStatusBar
4791                                            .getStatusBarHeight()) {
4792                                mNotificationPanel.getViewTreeObserver()
4793                                        .removeOnGlobalLayoutListener(this);
4794                                mNotificationPanel.post(clickPendingViewRunnable);
4795                            }
4796                        }
4797                    });
4798            instantExpandNotificationsPanel();
4799        }
4800    }
4801
4802    @Override
4803    public void onExpandClicked(Entry clickedEntry, boolean nowExpanded) {
4804        mHeadsUpManager.setExpanded(clickedEntry, nowExpanded);
4805        if (mState == StatusBarState.KEYGUARD && nowExpanded) {
4806            goToLockedShade(clickedEntry.row);
4807        }
4808    }
4809
4810    /**
4811     * Goes back to the keyguard after hanging around in {@link StatusBarState#SHADE_LOCKED}.
4812     */
4813    public void goToKeyguard() {
4814        if (mState == StatusBarState.SHADE_LOCKED) {
4815            mStackScroller.onGoToKeyguard();
4816            setBarState(StatusBarState.KEYGUARD);
4817            updateKeyguardState(false /* goingToFullShade */, true /* fromShadeLocked*/);
4818        }
4819    }
4820
4821    public long getKeyguardFadingAwayDelay() {
4822        return mKeyguardFadingAwayDelay;
4823    }
4824
4825    public long getKeyguardFadingAwayDuration() {
4826        return mKeyguardFadingAwayDuration;
4827    }
4828
4829    public void setBouncerShowing(boolean bouncerShowing) {
4830        mBouncerShowing = bouncerShowing;
4831        mStatusBarView.setBouncerShowing(bouncerShowing);
4832        recomputeDisableFlags(true /* animate */);
4833    }
4834
4835    public void onStartedGoingToSleep() {
4836        mStartedGoingToSleep = true;
4837    }
4838
4839    public void onFinishedGoingToSleep() {
4840        mNotificationPanel.onAffordanceLaunchEnded();
4841        releaseGestureWakeLock();
4842        mLaunchCameraOnScreenTurningOn = false;
4843        mStartedGoingToSleep = false;
4844        mDeviceInteractive = false;
4845        mWakeUpComingFromTouch = false;
4846        mWakeUpTouchLocation = null;
4847        mStackScroller.setAnimationsEnabled(false);
4848        mVisualStabilityManager.setScreenOn(false);
4849        updateVisibleToUser();
4850
4851        // We need to disable touch events because these might
4852        // collapse the panel after we expanded it, and thus we would end up with a blank
4853        // Keyguard.
4854        mNotificationPanel.setTouchDisabled(true);
4855        mStatusBarWindow.cancelCurrentTouch();
4856        if (mLaunchCameraOnFinishedGoingToSleep) {
4857            mLaunchCameraOnFinishedGoingToSleep = false;
4858
4859            // This gets executed before we will show Keyguard, so post it in order that the state
4860            // is correct.
4861            mHandler.post(new Runnable() {
4862                @Override
4863                public void run() {
4864                    onCameraLaunchGestureDetected(mLastCameraLaunchSource);
4865                }
4866            });
4867        }
4868    }
4869
4870    public void onStartedWakingUp() {
4871        mDeviceInteractive = true;
4872        mStackScroller.setAnimationsEnabled(true);
4873        mVisualStabilityManager.setScreenOn(true);
4874        mNotificationPanel.setTouchDisabled(false);
4875        updateVisibleToUser();
4876    }
4877
4878    public void onScreenTurningOn() {
4879        mScreenTurningOn = true;
4880        mFalsingManager.onScreenTurningOn();
4881        mNotificationPanel.onScreenTurningOn();
4882        if (mLaunchCameraOnScreenTurningOn) {
4883            mNotificationPanel.launchCamera(false, mLastCameraLaunchSource);
4884            mLaunchCameraOnScreenTurningOn = false;
4885        }
4886    }
4887
4888    private void vibrateForCameraGesture() {
4889        // Make sure to pass -1 for repeat so VibratorService doesn't stop us when going to sleep.
4890        mVibrator.vibrate(mCameraLaunchGestureVibePattern, -1 /* repeat */);
4891    }
4892
4893    public void onScreenTurnedOn() {
4894        mScreenTurningOn = false;
4895        mDozeScrimController.onScreenTurnedOn();
4896    }
4897
4898    @Override
4899    public void showScreenPinningRequest(int taskId) {
4900        if (mKeyguardMonitor.isShowing()) {
4901            // Don't allow apps to trigger this from keyguard.
4902            return;
4903        }
4904        // Show screen pinning request, since this comes from an app, show 'no thanks', button.
4905        showScreenPinningRequest(taskId, true);
4906    }
4907
4908    public void showScreenPinningRequest(int taskId, boolean allowCancel) {
4909        mScreenPinningRequest.showPrompt(taskId, allowCancel);
4910    }
4911
4912    public boolean hasActiveNotifications() {
4913        return !mNotificationData.getActiveNotifications().isEmpty();
4914    }
4915
4916    public void wakeUpIfDozing(long time, View where) {
4917        if (mDozing) {
4918            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
4919            pm.wakeUp(time, "com.android.systemui:NODOZE");
4920            mWakeUpComingFromTouch = true;
4921            where.getLocationInWindow(mTmpInt2);
4922            mWakeUpTouchLocation = new PointF(mTmpInt2[0] + where.getWidth() / 2,
4923                    mTmpInt2[1] + where.getHeight() / 2);
4924            mNotificationPanel.setTouchDisabled(false);
4925            mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
4926            mFalsingManager.onScreenOnFromTouch();
4927        }
4928    }
4929
4930    @Override
4931    public void appTransitionCancelled() {
4932        EventBus.getDefault().send(new AppTransitionFinishedEvent());
4933    }
4934
4935    @Override
4936    public void appTransitionFinished() {
4937        EventBus.getDefault().send(new AppTransitionFinishedEvent());
4938    }
4939
4940    @Override
4941    public void onCameraLaunchGestureDetected(int source) {
4942        mLastCameraLaunchSource = source;
4943        if (mStartedGoingToSleep) {
4944            mLaunchCameraOnFinishedGoingToSleep = true;
4945            return;
4946        }
4947        if (!mNotificationPanel.canCameraGestureBeLaunched(
4948                mStatusBarKeyguardViewManager.isShowing() && mExpandedVisible)) {
4949            return;
4950        }
4951        if (!mDeviceInteractive) {
4952            PowerManager pm = mContext.getSystemService(PowerManager.class);
4953            pm.wakeUp(SystemClock.uptimeMillis(), "com.android.systemui:CAMERA_GESTURE");
4954            mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
4955        }
4956        vibrateForCameraGesture();
4957        if (!mStatusBarKeyguardViewManager.isShowing()) {
4958            startActivity(KeyguardBottomAreaView.INSECURE_CAMERA_INTENT,
4959                    true /* dismissShade */);
4960        } else {
4961            if (!mDeviceInteractive) {
4962                // Avoid flickering of the scrim when we instant launch the camera and the bouncer
4963                // comes on.
4964                mScrimController.dontAnimateBouncerChangesUntilNextFrame();
4965                mGestureWakeLock.acquire(LAUNCH_TRANSITION_TIMEOUT_MS + 1000L);
4966            }
4967            if (mScreenTurningOn || mStatusBarKeyguardViewManager.isScreenTurnedOn()) {
4968                mNotificationPanel.launchCamera(mDeviceInteractive /* animate */, source);
4969            } else {
4970                // We need to defer the camera launch until the screen comes on, since otherwise
4971                // we will dismiss us too early since we are waiting on an activity to be drawn and
4972                // incorrectly get notified because of the screen on event (which resumes and pauses
4973                // some activities)
4974                mLaunchCameraOnScreenTurningOn = true;
4975            }
4976        }
4977    }
4978
4979    public void notifyFpAuthModeChanged() {
4980        updateDozing();
4981    }
4982
4983    private void updateDozing() {
4984        Trace.beginSection("StatusBar#updateDozing");
4985        // When in wake-and-unlock while pulsing, keep dozing state until fully unlocked.
4986        mDozing = mDozingRequested && mState == StatusBarState.KEYGUARD
4987                || mFingerprintUnlockController.getMode()
4988                        == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING;
4989        mStatusBarWindowManager.setDozing(mDozing);
4990        updateDozingState();
4991        Trace.endSection();
4992    }
4993
4994    public boolean isKeyguardShowing() {
4995        return mStatusBarKeyguardViewManager.isShowing();
4996    }
4997
4998    private final class DozeServiceHost implements DozeHost {
4999        private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
5000        private boolean mAnimateWakeup;
5001
5002        @Override
5003        public String toString() {
5004            return "PSB.DozeServiceHost[mCallbacks=" + mCallbacks.size() + "]";
5005        }
5006
5007        public void firePowerSaveChanged(boolean active) {
5008            for (Callback callback : mCallbacks) {
5009                callback.onPowerSaveChanged(active);
5010            }
5011        }
5012
5013        public void fireNotificationHeadsUp() {
5014            for (Callback callback : mCallbacks) {
5015                callback.onNotificationHeadsUp();
5016            }
5017        }
5018
5019        @Override
5020        public void addCallback(@NonNull Callback callback) {
5021            mCallbacks.add(callback);
5022        }
5023
5024        @Override
5025        public void removeCallback(@NonNull Callback callback) {
5026            mCallbacks.remove(callback);
5027        }
5028
5029        @Override
5030        public void startDozing() {
5031            if (!mDozingRequested) {
5032                mDozingRequested = true;
5033                DozeLog.traceDozing(mContext, mDozing);
5034                updateDozing();
5035            }
5036        }
5037
5038        @Override
5039        public void pulseWhileDozing(@NonNull PulseCallback callback, int reason) {
5040            mDozeScrimController.pulse(new PulseCallback() {
5041
5042                @Override
5043                public void onPulseStarted() {
5044                    callback.onPulseStarted();
5045                    Collection<HeadsUpManager.HeadsUpEntry> pulsingEntries =
5046                            mHeadsUpManager.getAllEntries();
5047                    if (!pulsingEntries.isEmpty()) {
5048                        // Only pulse the stack scroller if there's actually something to show.
5049                        // Otherwise just show the always-on screen.
5050                        setPulsing(pulsingEntries);
5051                    }
5052                }
5053
5054                @Override
5055                public void onPulseFinished() {
5056                    callback.onPulseFinished();
5057                    setPulsing(null);
5058                }
5059
5060                private void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> pulsing) {
5061                    mStackScroller.setPulsing(pulsing);
5062                    mNotificationPanel.setPulsing(pulsing != null);
5063                    mVisualStabilityManager.setPulsing(pulsing != null);
5064                }
5065            }, reason);
5066        }
5067
5068        @Override
5069        public void stopDozing() {
5070            if (mDozingRequested) {
5071                mDozingRequested = false;
5072                DozeLog.traceDozing(mContext, mDozing);
5073                updateDozing();
5074            }
5075        }
5076
5077        @Override
5078        public void dozeTimeTick() {
5079            mKeyguardStatusView.refreshTime();
5080        }
5081
5082        @Override
5083        public boolean isPowerSaveActive() {
5084            return mBatteryController.isPowerSave();
5085        }
5086
5087        @Override
5088        public boolean isPulsingBlocked() {
5089            return mFingerprintUnlockController.getMode()
5090                    == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK;
5091        }
5092
5093        @Override
5094        public void startPendingIntentDismissingKeyguard(PendingIntent intent) {
5095            StatusBar.this.startPendingIntentDismissingKeyguard(intent);
5096        }
5097
5098        @Override
5099        public void abortPulsing() {
5100            mDozeScrimController.abortPulsing();
5101        }
5102
5103        @Override
5104        public void extendPulse() {
5105            mDozeScrimController.extendPulse();
5106        }
5107
5108        @Override
5109        public void setAnimateWakeup(boolean animateWakeup) {
5110            mAnimateWakeup = animateWakeup;
5111        }
5112
5113        private boolean shouldAnimateWakeup() {
5114            return mAnimateWakeup;
5115        }
5116    }
5117
5118    // Begin Extra BaseStatusBar methods.
5119
5120    protected CommandQueue mCommandQueue;
5121    protected IStatusBarService mBarService;
5122
5123    // all notifications
5124    protected NotificationData mNotificationData;
5125    protected NotificationStackScrollLayout mStackScroller;
5126
5127    protected NotificationGroupManager mGroupManager = new NotificationGroupManager();
5128
5129    protected RemoteInputController mRemoteInputController;
5130
5131    // for heads up notifications
5132    protected HeadsUpManager mHeadsUpManager;
5133
5134    // handling reordering
5135    protected VisualStabilityManager mVisualStabilityManager = new VisualStabilityManager();
5136
5137    protected int mCurrentUserId = 0;
5138    final protected SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
5139
5140    protected int mLayoutDirection = -1; // invalid
5141    protected AccessibilityManager mAccessibilityManager;
5142
5143    protected boolean mDeviceInteractive;
5144
5145    protected boolean mVisible;
5146    protected ArraySet<Entry> mHeadsUpEntriesToRemoveOnSwitch = new ArraySet<>();
5147    protected ArraySet<Entry> mRemoteInputEntriesToRemoveOnCollapse = new ArraySet<>();
5148
5149    /**
5150     * Notifications with keys in this set are not actually around anymore. We kept them around
5151     * when they were canceled in response to a remote input interaction. This allows us to show
5152     * what you replied and allows you to continue typing into it.
5153     */
5154    protected ArraySet<String> mKeysKeptForRemoteInput = new ArraySet<>();
5155
5156    // mScreenOnFromKeyguard && mVisible.
5157    private boolean mVisibleToUser;
5158
5159    private Locale mLocale;
5160
5161    protected boolean mUseHeadsUp = false;
5162    protected boolean mHeadsUpTicker = false;
5163    protected boolean mDisableNotificationAlerts = false;
5164
5165    protected DevicePolicyManager mDevicePolicyManager;
5166    protected PowerManager mPowerManager;
5167    protected StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
5168
5169    // public mode, private notifications, etc
5170    private final SparseBooleanArray mLockscreenPublicMode = new SparseBooleanArray();
5171    private final SparseBooleanArray mUsersAllowingPrivateNotifications = new SparseBooleanArray();
5172    private final SparseBooleanArray mUsersAllowingNotifications = new SparseBooleanArray();
5173
5174    private UserManager mUserManager;
5175
5176    protected KeyguardManager mKeyguardManager;
5177    private LockPatternUtils mLockPatternUtils;
5178    private DeviceProvisionedController mDeviceProvisionedController;
5179
5180    // UI-specific methods
5181
5182    protected WindowManager mWindowManager;
5183    protected IWindowManager mWindowManagerService;
5184
5185    protected Display mDisplay;
5186
5187    protected RecentsComponent mRecents;
5188
5189    protected int mZenMode;
5190
5191    // which notification is currently being longpress-examined by the user
5192    private NotificationGuts mNotificationGutsExposed;
5193    private MenuItem mGutsMenuItem;
5194
5195    private KeyboardShortcuts mKeyboardShortcuts;
5196
5197    protected NotificationShelf mNotificationShelf;
5198    protected DismissView mDismissView;
5199    protected EmptyShadeView mEmptyShadeView;
5200
5201    private NotificationClicker mNotificationClicker = new NotificationClicker();
5202
5203    protected AssistManager mAssistManager;
5204
5205    protected boolean mVrMode;
5206
5207    private Set<String> mNonBlockablePkgs;
5208
5209    @Override  // NotificationData.Environment
5210    public boolean isDeviceProvisioned() {
5211        return mDeviceProvisionedController.isDeviceProvisioned();
5212    }
5213
5214    private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
5215        @Override
5216        public void onVrStateChanged(boolean enabled) {
5217            mVrMode = enabled;
5218        }
5219    };
5220
5221    public boolean isDeviceInVrMode() {
5222        return mVrMode;
5223    }
5224
5225    private final DeviceProvisionedListener mDeviceProvisionedListener =
5226            new DeviceProvisionedListener() {
5227        @Override
5228        public void onDeviceProvisionedChanged() {
5229            updateNotifications();
5230        }
5231    };
5232
5233    protected final ContentObserver mSettingsObserver = new ContentObserver(mHandler) {
5234        @Override
5235        public void onChange(boolean selfChange) {
5236            final int mode = Settings.Global.getInt(mContext.getContentResolver(),
5237                    Settings.Global.ZEN_MODE, Settings.Global.ZEN_MODE_OFF);
5238            setZenMode(mode);
5239
5240            updateLockscreenNotificationSetting();
5241        }
5242    };
5243
5244    private final ContentObserver mLockscreenSettingsObserver = new ContentObserver(mHandler) {
5245        @Override
5246        public void onChange(boolean selfChange) {
5247            // We don't know which user changed LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS or
5248            // LOCK_SCREEN_SHOW_NOTIFICATIONS, so we just dump our cache ...
5249            mUsersAllowingPrivateNotifications.clear();
5250            mUsersAllowingNotifications.clear();
5251            // ... and refresh all the notifications
5252            updateLockscreenNotificationSetting();
5253            updateNotifications();
5254        }
5255    };
5256
5257    private RemoteViews.OnClickHandler mOnClickHandler = new RemoteViews.OnClickHandler() {
5258
5259        @Override
5260        public boolean onClickHandler(
5261                final View view, final PendingIntent pendingIntent, final Intent fillInIntent) {
5262            wakeUpIfDozing(SystemClock.uptimeMillis(), view);
5263
5264
5265            if (handleRemoteInput(view, pendingIntent, fillInIntent)) {
5266                return true;
5267            }
5268
5269            if (DEBUG) {
5270                Log.v(TAG, "Notification click handler invoked for intent: " + pendingIntent);
5271            }
5272            logActionClick(view);
5273            // The intent we are sending is for the application, which
5274            // won't have permission to immediately start an activity after
5275            // the user switches to home.  We know it is safe to do at this
5276            // point, so make sure new activity switches are now allowed.
5277            try {
5278                ActivityManager.getService().resumeAppSwitches();
5279            } catch (RemoteException e) {
5280            }
5281            final boolean isActivity = pendingIntent.isActivity();
5282            if (isActivity) {
5283                final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
5284                final boolean afterKeyguardGone = PreviewInflater.wouldLaunchResolverActivity(
5285                        mContext, pendingIntent.getIntent(), mCurrentUserId);
5286                dismissKeyguardThenExecute(new OnDismissAction() {
5287                    @Override
5288                    public boolean onDismiss() {
5289                        try {
5290                            ActivityManager.getService().resumeAppSwitches();
5291                        } catch (RemoteException e) {
5292                        }
5293
5294                        boolean handled = superOnClickHandler(view, pendingIntent, fillInIntent);
5295
5296                        // close the shade if it was open
5297                        if (handled) {
5298                            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
5299                                    true /* force */);
5300                            visibilityChanged(false);
5301                            mAssistManager.hideAssist();
5302                        }
5303
5304                        // Wait for activity start.
5305                        return handled;
5306                    }
5307                }, afterKeyguardGone);
5308                return true;
5309            } else {
5310                return superOnClickHandler(view, pendingIntent, fillInIntent);
5311            }
5312        }
5313
5314        private void logActionClick(View view) {
5315            ViewParent parent = view.getParent();
5316            String key = getNotificationKeyForParent(parent);
5317            if (key == null) {
5318                Log.w(TAG, "Couldn't determine notification for click.");
5319                return;
5320            }
5321            int index = -1;
5322            // If this is a default template, determine the index of the button.
5323            if (view.getId() == com.android.internal.R.id.action0 &&
5324                    parent != null && parent instanceof ViewGroup) {
5325                ViewGroup actionGroup = (ViewGroup) parent;
5326                index = actionGroup.indexOfChild(view);
5327            }
5328            try {
5329                mBarService.onNotificationActionClick(key, index);
5330            } catch (RemoteException e) {
5331                // Ignore
5332            }
5333        }
5334
5335        private String getNotificationKeyForParent(ViewParent parent) {
5336            while (parent != null) {
5337                if (parent instanceof ExpandableNotificationRow) {
5338                    return ((ExpandableNotificationRow) parent).getStatusBarNotification().getKey();
5339                }
5340                parent = parent.getParent();
5341            }
5342            return null;
5343        }
5344
5345        private boolean superOnClickHandler(View view, PendingIntent pendingIntent,
5346                Intent fillInIntent) {
5347            return super.onClickHandler(view, pendingIntent, fillInIntent,
5348                    StackId.FULLSCREEN_WORKSPACE_STACK_ID);
5349        }
5350
5351        private boolean handleRemoteInput(View view, PendingIntent pendingIntent, Intent fillInIntent) {
5352            Object tag = view.getTag(com.android.internal.R.id.remote_input_tag);
5353            RemoteInput[] inputs = null;
5354            if (tag instanceof RemoteInput[]) {
5355                inputs = (RemoteInput[]) tag;
5356            }
5357
5358            if (inputs == null) {
5359                return false;
5360            }
5361
5362            RemoteInput input = null;
5363
5364            for (RemoteInput i : inputs) {
5365                if (i.getAllowFreeFormInput()) {
5366                    input = i;
5367                }
5368            }
5369
5370            if (input == null) {
5371                return false;
5372            }
5373
5374            ViewParent p = view.getParent();
5375            RemoteInputView riv = null;
5376            while (p != null) {
5377                if (p instanceof View) {
5378                    View pv = (View) p;
5379                    if (pv.isRootNamespace()) {
5380                        riv = findRemoteInputView(pv);
5381                        break;
5382                    }
5383                }
5384                p = p.getParent();
5385            }
5386            ExpandableNotificationRow row = null;
5387            while (p != null) {
5388                if (p instanceof ExpandableNotificationRow) {
5389                    row = (ExpandableNotificationRow) p;
5390                    break;
5391                }
5392                p = p.getParent();
5393            }
5394
5395            if (row == null) {
5396                return false;
5397            }
5398
5399            row.setUserExpanded(true);
5400
5401            if (!mAllowLockscreenRemoteInput) {
5402                final int userId = pendingIntent.getCreatorUserHandle().getIdentifier();
5403                if (isLockscreenPublicMode(userId)) {
5404                    onLockedRemoteInput(row, view);
5405                    return true;
5406                }
5407                if (mUserManager.getUserInfo(userId).isManagedProfile()
5408                        && mKeyguardManager.isDeviceLocked(userId)) {
5409                    onLockedWorkRemoteInput(userId, row, view);
5410                    return true;
5411                }
5412            }
5413
5414            if (riv == null) {
5415                riv = findRemoteInputView(row.getPrivateLayout().getExpandedChild());
5416                if (riv == null) {
5417                    return false;
5418                }
5419                if (!row.getPrivateLayout().getExpandedChild().isShown()) {
5420                    onMakeExpandedVisibleForRemoteInput(row, view);
5421                    return true;
5422                }
5423            }
5424
5425            int width = view.getWidth();
5426            if (view instanceof TextView) {
5427                // Center the reveal on the text which might be off-center from the TextView
5428                TextView tv = (TextView) view;
5429                if (tv.getLayout() != null) {
5430                    int innerWidth = (int) tv.getLayout().getLineWidth(0);
5431                    innerWidth += tv.getCompoundPaddingLeft() + tv.getCompoundPaddingRight();
5432                    width = Math.min(width, innerWidth);
5433                }
5434            }
5435            int cx = view.getLeft() + width / 2;
5436            int cy = view.getTop() + view.getHeight() / 2;
5437            int w = riv.getWidth();
5438            int h = riv.getHeight();
5439            int r = Math.max(
5440                    Math.max(cx + cy, cx + (h - cy)),
5441                    Math.max((w - cx) + cy, (w - cx) + (h - cy)));
5442
5443            riv.setRevealParameters(cx, cy, r);
5444            riv.setPendingIntent(pendingIntent);
5445            riv.setRemoteInput(inputs, input);
5446            riv.focusAnimated();
5447
5448            return true;
5449        }
5450
5451        private RemoteInputView findRemoteInputView(View v) {
5452            if (v == null) {
5453                return null;
5454            }
5455            return (RemoteInputView) v.findViewWithTag(RemoteInputView.VIEW_TAG);
5456        }
5457    };
5458
5459    private final BroadcastReceiver mBaseBroadcastReceiver = new BroadcastReceiver() {
5460        @Override
5461        public void onReceive(Context context, Intent intent) {
5462            String action = intent.getAction();
5463            if (Intent.ACTION_USER_SWITCHED.equals(action)) {
5464                mCurrentUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
5465                updateCurrentProfilesCache();
5466                if (true) Log.v(TAG, "userId " + mCurrentUserId + " is in the house");
5467
5468                updateLockscreenNotificationSetting();
5469
5470                userSwitched(mCurrentUserId);
5471            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
5472                updateCurrentProfilesCache();
5473            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
5474                List<ActivityManager.RecentTaskInfo> recentTask = null;
5475                try {
5476                    recentTask = ActivityManager.getService().getRecentTasks(1,
5477                            ActivityManager.RECENT_WITH_EXCLUDED
5478                            | ActivityManager.RECENT_INCLUDE_PROFILES,
5479                            mCurrentUserId).getList();
5480                } catch (RemoteException e) {
5481                    // Abandon hope activity manager not running.
5482                }
5483                if (recentTask != null && recentTask.size() > 0) {
5484                    UserInfo user = mUserManager.getUserInfo(recentTask.get(0).userId);
5485                    if (user != null && user.isManagedProfile()) {
5486                        Toast toast = Toast.makeText(mContext,
5487                                R.string.managed_profile_foreground_toast,
5488                                Toast.LENGTH_SHORT);
5489                        TextView text = (TextView) toast.getView().findViewById(
5490                                android.R.id.message);
5491                        text.setCompoundDrawablesRelativeWithIntrinsicBounds(
5492                                R.drawable.stat_sys_managed_profile_status, 0, 0, 0);
5493                        int paddingPx = mContext.getResources().getDimensionPixelSize(
5494                                R.dimen.managed_profile_toast_padding);
5495                        text.setCompoundDrawablePadding(paddingPx);
5496                        toast.show();
5497                    }
5498                }
5499            } else if (BANNER_ACTION_CANCEL.equals(action) || BANNER_ACTION_SETUP.equals(action)) {
5500                NotificationManager noMan = (NotificationManager)
5501                        mContext.getSystemService(Context.NOTIFICATION_SERVICE);
5502                noMan.cancel(SystemMessage.NOTE_HIDDEN_NOTIFICATIONS);
5503
5504                Settings.Secure.putInt(mContext.getContentResolver(),
5505                        Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
5506                if (BANNER_ACTION_SETUP.equals(action)) {
5507                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
5508                            true /* force */);
5509                    mContext.startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_REDACTION)
5510                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
5511
5512                    );
5513                }
5514            } else if (NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION.equals(action)) {
5515                final IntentSender intentSender = intent.getParcelableExtra(Intent.EXTRA_INTENT);
5516                final String notificationKey = intent.getStringExtra(Intent.EXTRA_INDEX);
5517                if (intentSender != null) {
5518                    try {
5519                        mContext.startIntentSender(intentSender, null, 0, 0, 0);
5520                    } catch (IntentSender.SendIntentException e) {
5521                        /* ignore */
5522                    }
5523                }
5524                if (notificationKey != null) {
5525                    try {
5526                        mBarService.onNotificationClick(notificationKey);
5527                    } catch (RemoteException e) {
5528                        /* ignore */
5529                    }
5530                }
5531            }
5532        }
5533    };
5534
5535    private final BroadcastReceiver mAllUsersReceiver = new BroadcastReceiver() {
5536        @Override
5537        public void onReceive(Context context, Intent intent) {
5538            final String action = intent.getAction();
5539            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5540
5541            if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(action) &&
5542                    isCurrentProfile(getSendingUserId())) {
5543                mUsersAllowingPrivateNotifications.clear();
5544                updateLockscreenNotificationSetting();
5545                updateNotifications();
5546            } else if (Intent.ACTION_DEVICE_LOCKED_CHANGED.equals(action)) {
5547                if (userId != mCurrentUserId && isCurrentProfile(userId)) {
5548                    onWorkChallengeChanged();
5549                }
5550            }
5551        }
5552    };
5553
5554    private final NotificationListenerService mNotificationListener =
5555            new NotificationListenerService() {
5556        @Override
5557        public void onListenerConnected() {
5558            if (DEBUG) Log.d(TAG, "onListenerConnected");
5559            final StatusBarNotification[] notifications = getActiveNotifications();
5560            if (notifications == null) {
5561                Log.w(TAG, "onListenerConnected unable to get active notifications.");
5562                return;
5563            }
5564            final RankingMap currentRanking = getCurrentRanking();
5565            mHandler.post(new Runnable() {
5566                @Override
5567                public void run() {
5568                    for (StatusBarNotification sbn : notifications) {
5569                        try {
5570                            addNotification(sbn, currentRanking);
5571                        } catch (InflationException e) {
5572                            handleInflationException(sbn, e);
5573                        }
5574                    }
5575                }
5576            });
5577        }
5578
5579        @Override
5580        public void onNotificationPosted(final StatusBarNotification sbn,
5581                final RankingMap rankingMap) {
5582            if (DEBUG) Log.d(TAG, "onNotificationPosted: " + sbn);
5583            if (sbn != null) {
5584                mHandler.post(new Runnable() {
5585                    @Override
5586                    public void run() {
5587                        processForRemoteInput(sbn.getNotification());
5588                        String key = sbn.getKey();
5589                        mKeysKeptForRemoteInput.remove(key);
5590                        boolean isUpdate = mNotificationData.get(key) != null;
5591                        // In case we don't allow child notifications, we ignore children of
5592                        // notifications that have a summary, since we're not going to show them
5593                        // anyway. This is true also when the summary is canceled,
5594                        // because children are automatically canceled by NoMan in that case.
5595                        if (!ENABLE_CHILD_NOTIFICATIONS
5596                            && mGroupManager.isChildInGroupWithSummary(sbn)) {
5597                            if (DEBUG) {
5598                                Log.d(TAG, "Ignoring group child due to existing summary: " + sbn);
5599                            }
5600
5601                            // Remove existing notification to avoid stale data.
5602                            if (isUpdate) {
5603                                removeNotification(key, rankingMap);
5604                            } else {
5605                                mNotificationData.updateRanking(rankingMap);
5606                            }
5607                            return;
5608                        }
5609                        try {
5610                            if (isUpdate) {
5611                                updateNotification(sbn, rankingMap);
5612                            } else {
5613                                addNotification(sbn, rankingMap);
5614                            }
5615                        } catch (InflationException e) {
5616                            handleInflationException(sbn, e);
5617                        }
5618                    }
5619                });
5620            }
5621        }
5622
5623        @Override
5624        public void onNotificationRemoved(StatusBarNotification sbn,
5625                final RankingMap rankingMap) {
5626            if (DEBUG) Log.d(TAG, "onNotificationRemoved: " + sbn);
5627            if (sbn != null) {
5628                final String key = sbn.getKey();
5629                mHandler.post(new Runnable() {
5630                    @Override
5631                    public void run() {
5632                        removeNotification(key, rankingMap);
5633                    }
5634                });
5635            }
5636        }
5637
5638        @Override
5639        public void onNotificationRankingUpdate(final RankingMap rankingMap) {
5640            if (DEBUG) Log.d(TAG, "onRankingUpdate");
5641            if (rankingMap != null) {
5642            mHandler.post(new Runnable() {
5643                @Override
5644                public void run() {
5645                    updateNotificationRanking(rankingMap);
5646                }
5647            });
5648        }                            }
5649
5650    };
5651
5652    private void updateCurrentProfilesCache() {
5653        synchronized (mCurrentProfiles) {
5654            mCurrentProfiles.clear();
5655            if (mUserManager != null) {
5656                for (UserInfo user : mUserManager.getProfiles(mCurrentUserId)) {
5657                    mCurrentProfiles.put(user.id, user);
5658                }
5659            }
5660        }
5661    }
5662
5663    protected void notifyUserAboutHiddenNotifications() {
5664        if (0 != Settings.Secure.getInt(mContext.getContentResolver(),
5665                Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 1)) {
5666            Log.d(TAG, "user hasn't seen notification about hidden notifications");
5667            if (!mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
5668                Log.d(TAG, "insecure lockscreen, skipping notification");
5669                Settings.Secure.putInt(mContext.getContentResolver(),
5670                        Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
5671                return;
5672            }
5673            Log.d(TAG, "disabling lockecreen notifications and alerting the user");
5674            // disable lockscreen notifications until user acts on the banner.
5675            Settings.Secure.putInt(mContext.getContentResolver(),
5676                    Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0);
5677            Settings.Secure.putInt(mContext.getContentResolver(),
5678                    Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0);
5679
5680            final String packageName = mContext.getPackageName();
5681            PendingIntent cancelIntent = PendingIntent.getBroadcast(mContext, 0,
5682                    new Intent(BANNER_ACTION_CANCEL).setPackage(packageName),
5683                    PendingIntent.FLAG_CANCEL_CURRENT);
5684            PendingIntent setupIntent = PendingIntent.getBroadcast(mContext, 0,
5685                    new Intent(BANNER_ACTION_SETUP).setPackage(packageName),
5686                    PendingIntent.FLAG_CANCEL_CURRENT);
5687
5688            final int colorRes = com.android.internal.R.color.system_notification_accent_color;
5689            Notification.Builder note =
5690                    new Notification.Builder(mContext, NotificationChannels.GENERAL)
5691                            .setSmallIcon(R.drawable.ic_android)
5692                            .setContentTitle(mContext.getString(
5693                                    R.string.hidden_notifications_title))
5694                            .setContentText(mContext.getString(R.string.hidden_notifications_text))
5695                            .setOngoing(true)
5696                            .setColor(mContext.getColor(colorRes))
5697                            .setContentIntent(setupIntent)
5698                            .addAction(R.drawable.ic_close,
5699                                    mContext.getString(R.string.hidden_notifications_cancel),
5700                                    cancelIntent)
5701                            .addAction(R.drawable.ic_settings,
5702                                    mContext.getString(R.string.hidden_notifications_setup),
5703                                    setupIntent);
5704            overrideNotificationAppName(mContext, note);
5705
5706            NotificationManager noMan =
5707                    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
5708            noMan.notify(SystemMessage.NOTE_HIDDEN_NOTIFICATIONS, note.build());
5709        }
5710    }
5711
5712    @Override  // NotificationData.Environment
5713    public boolean isNotificationForCurrentProfiles(StatusBarNotification n) {
5714        final int thisUserId = mCurrentUserId;
5715        final int notificationUserId = n.getUserId();
5716        if (DEBUG && MULTIUSER_DEBUG) {
5717            Log.v(TAG, String.format("%s: current userid: %d, notification userid: %d",
5718                    n, thisUserId, notificationUserId));
5719        }
5720        return isCurrentProfile(notificationUserId);
5721    }
5722
5723    protected void setNotificationShown(StatusBarNotification n) {
5724        setNotificationsShown(new String[]{n.getKey()});
5725    }
5726
5727    protected void setNotificationsShown(String[] keys) {
5728        try {
5729            mNotificationListener.setNotificationsShown(keys);
5730        } catch (RuntimeException e) {
5731            Log.d(TAG, "failed setNotificationsShown: ", e);
5732        }
5733    }
5734
5735    protected boolean isCurrentProfile(int userId) {
5736        synchronized (mCurrentProfiles) {
5737            return userId == UserHandle.USER_ALL || mCurrentProfiles.get(userId) != null;
5738        }
5739    }
5740
5741    @Override
5742    public NotificationGroupManager getGroupManager() {
5743        return mGroupManager;
5744    }
5745
5746    public boolean isMediaNotification(NotificationData.Entry entry) {
5747        // TODO: confirm that there's a valid media key
5748        return entry.getExpandedContentView() != null &&
5749               entry.getExpandedContentView()
5750                       .findViewById(com.android.internal.R.id.media_actions) != null;
5751    }
5752
5753    // The button in the guts that links to the system notification settings for that app
5754    private void startAppNotificationSettingsActivity(String packageName, final int appUid,
5755            final NotificationChannel channel) {
5756        final Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
5757        intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);
5758        intent.putExtra(Settings.EXTRA_APP_UID, appUid);
5759        if (channel != null) {
5760            intent.putExtra(EXTRA_FRAGMENT_ARG_KEY, channel.getId());
5761        }
5762        startNotificationGutsIntent(intent, appUid);
5763    }
5764
5765    private void startNotificationGutsIntent(final Intent intent, final int appUid) {
5766        dismissKeyguardThenExecute(new OnDismissAction() {
5767            @Override
5768            public boolean onDismiss() {
5769                AsyncTask.execute(new Runnable() {
5770                    @Override
5771                    public void run() {
5772                        TaskStackBuilder.create(mContext)
5773                                .addNextIntentWithParentStack(intent)
5774                                .startActivities(getActivityOptions(),
5775                                        new UserHandle(UserHandle.getUserId(appUid)));
5776                    }
5777                });
5778                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */);
5779                return true;
5780            }
5781        }, false /* afterKeyguardGone */);
5782    }
5783
5784    public void setNotificationSnoozed(StatusBarNotification sbn, SnoozeOption snoozeOption) {
5785        if (snoozeOption.criterion != null) {
5786            mNotificationListener.snoozeNotification(sbn.getKey(), snoozeOption.criterion.getId());
5787        } else {
5788            mNotificationListener.snoozeNotification(sbn.getKey(),
5789                    snoozeOption.snoozeForMinutes * 60 * 1000);
5790        }
5791    }
5792
5793    private void bindGuts(final ExpandableNotificationRow row, MenuItem item) {
5794        row.inflateGuts();
5795        row.setGutsView(item);
5796        final StatusBarNotification sbn = row.getStatusBarNotification();
5797        row.setTag(sbn.getPackageName());
5798        final NotificationGuts guts = row.getGuts();
5799        guts.setClosedListener((NotificationGuts g) -> {
5800            if (!g.willBeRemoved() && !row.isRemoved()) {
5801                mStackScroller.onHeightChanged(row, !isPanelFullyCollapsed() /* needsAnimation */);
5802            }
5803            if (mNotificationGutsExposed == g) {
5804                mNotificationGutsExposed = null;
5805                mGutsMenuItem = null;
5806            }
5807        });
5808
5809        View gutsView = item.getGutsView();
5810        if (gutsView instanceof NotificationSnooze) {
5811            NotificationSnooze snoozeGuts = (NotificationSnooze) gutsView;
5812            snoozeGuts.setSnoozeListener(mStackScroller.getSwipeActionHelper());
5813            snoozeGuts.setStatusBarNotification(sbn);
5814            snoozeGuts.setSnoozeOptions(row.getEntry().snoozeCriteria);
5815            guts.setHeightChangedListener((NotificationGuts g) -> {
5816                mStackScroller.onHeightChanged(row, row.isShown() /* needsAnimation */);
5817            });
5818        }
5819
5820        if (gutsView instanceof NotificationInfo) {
5821            final UserHandle userHandle = sbn.getUser();
5822            PackageManager pmUser = getPackageManagerForUser(mContext,
5823                    userHandle.getIdentifier());
5824            final INotificationManager iNotificationManager = INotificationManager.Stub.asInterface(
5825                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
5826            final String pkg = sbn.getPackageName();
5827            NotificationInfo info = (NotificationInfo) gutsView;
5828            // Settings link is only valid for notifications that specify a user, unless this is the
5829            // system user.
5830            NotificationInfo.OnSettingsClickListener onSettingsClick = null;
5831            if (!userHandle.equals(UserHandle.ALL) || mCurrentUserId == UserHandle.USER_SYSTEM) {
5832                onSettingsClick = (View v, NotificationChannel channel, int appUid) -> {
5833                    mMetricsLogger.action(MetricsEvent.ACTION_NOTE_INFO);
5834                    guts.resetFalsingCheck();
5835                    startAppNotificationSettingsActivity(pkg, appUid, channel);
5836                };
5837            }
5838            final NotificationInfo.OnAppSettingsClickListener onAppSettingsClick = (View v,
5839                    Intent intent) -> {
5840                mMetricsLogger.action(MetricsEvent.ACTION_APP_NOTE_SETTINGS);
5841                guts.resetFalsingCheck();
5842                startNotificationGutsIntent(intent, sbn.getUid());
5843            };
5844            final View.OnClickListener onDoneClick = (View v) -> {
5845                saveAndCloseNotificationMenu(info, row, guts, v);
5846            };
5847            final NotificationInfo.CheckSaveListener checkSaveListener =
5848                    (Runnable saveImportance) -> {
5849                // If the user has security enabled, show challenge if the setting is changed.
5850                if (isLockscreenPublicMode(userHandle.getIdentifier())
5851                        && (mState == StatusBarState.KEYGUARD
5852                                || mState == StatusBarState.SHADE_LOCKED)) {
5853                    onLockedNotificationImportanceChange(() -> {
5854                        saveImportance.run();
5855                        return true;
5856                    });
5857                } else {
5858                    saveImportance.run();
5859                }
5860            };
5861
5862            ArraySet<NotificationChannel> channels = new ArraySet<NotificationChannel>();
5863            channels.add(row.getEntry().channel);
5864            if (row.isSummaryWithChildren()) {
5865                // If this is a summary, then add in the children notification channels for the
5866                // same user and pkg.
5867                final List<ExpandableNotificationRow> childrenRows = row.getNotificationChildren();
5868                final int numChildren = childrenRows.size();
5869                for (int i = 0; i < numChildren; i++) {
5870                    final ExpandableNotificationRow childRow = childrenRows.get(i);
5871                    final NotificationChannel childChannel = childRow.getEntry().channel;
5872                    final StatusBarNotification childSbn = childRow.getStatusBarNotification();
5873                    if (childSbn.getUser().equals(userHandle) &&
5874                            childSbn.getPackageName().equals(pkg)) {
5875                        channels.add(childChannel);
5876                    }
5877                }
5878            }
5879            try {
5880                info.bindNotification(pmUser, iNotificationManager, pkg, new ArrayList(channels),
5881                        row.getEntry().channel.getImportance(), sbn, onSettingsClick,
5882                        onAppSettingsClick, onDoneClick, checkSaveListener,
5883                        mNonBlockablePkgs);
5884            } catch (RemoteException e) {
5885                Log.e(TAG, e.toString());
5886            }
5887        }
5888    }
5889
5890    private void saveAndCloseNotificationMenu(NotificationInfo info,
5891            ExpandableNotificationRow row, NotificationGuts guts, View done) {
5892        guts.resetFalsingCheck();
5893        int[] rowLocation = new int[2];
5894        int[] doneLocation = new int[2];
5895        row.getLocationOnScreen(rowLocation);
5896        done.getLocationOnScreen(doneLocation);
5897
5898        final int centerX = done.getWidth() / 2;
5899        final int centerY = done.getHeight() / 2;
5900        final int x = doneLocation[0] - rowLocation[0] + centerX;
5901        final int y = doneLocation[1] - rowLocation[1] + centerY;
5902        closeAndSaveGuts(false /* removeLeavebehind */, false /* force */,
5903                true /* removeControls */, x, y, true /* resetMenu */);
5904    }
5905
5906    protected SwipeHelper.LongPressListener getNotificationLongClicker() {
5907        return new SwipeHelper.LongPressListener() {
5908            @Override
5909            public boolean onLongPress(View v, final int x, final int y,
5910                    MenuItem item) {
5911                if (!(v instanceof ExpandableNotificationRow)) {
5912                    return false;
5913                }
5914                if (v.getWindowToken() == null) {
5915                    Log.e(TAG, "Trying to show notification guts, but not attached to window");
5916                    return false;
5917                }
5918
5919                final ExpandableNotificationRow row = (ExpandableNotificationRow) v;
5920                if (row.isDark()) {
5921                    return false;
5922                }
5923                if (row.areGutsExposed()) {
5924                    closeAndSaveGuts(false /* removeLeavebehind */, false /* force */,
5925                            true /* removeControls */, -1 /* x */, -1 /* y */,
5926                            true /* resetMenu */);
5927                    return false;
5928                }
5929                bindGuts(row, item);
5930                NotificationGuts guts = row.getGuts();
5931
5932                // Assume we are a status_bar_notification_row
5933                if (guts == null) {
5934                    // This view has no guts. Examples are the more card or the dismiss all view
5935                    return false;
5936                }
5937
5938                mMetricsLogger.action(MetricsEvent.ACTION_NOTE_CONTROLS);
5939
5940                // ensure that it's laid but not visible until actually laid out
5941                guts.setVisibility(View.INVISIBLE);
5942                // Post to ensure the the guts are properly laid out.
5943                guts.post(new Runnable() {
5944                    @Override
5945                    public void run() {
5946                        if (row.getWindowToken() == null) {
5947                            Log.e(TAG, "Trying to show notification guts, but not attached to "
5948                                    + "window");
5949                            return;
5950                        }
5951                        closeAndSaveGuts(true /* removeLeavebehind */, true /* force */,
5952                                true /* removeControls */, -1 /* x */, -1 /* y */,
5953                                false /* resetMenu */);
5954                        guts.setVisibility(View.VISIBLE);
5955                        final double horz = Math.max(guts.getWidth() - x, x);
5956                        final double vert = Math.max(guts.getHeight() - y, y);
5957                        final float r = (float) Math.hypot(horz, vert);
5958                        final Animator a
5959                                = ViewAnimationUtils.createCircularReveal(guts, x, y, 0, r);
5960                        a.setDuration(StackStateAnimator.ANIMATION_DURATION_STANDARD);
5961                        a.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
5962                        a.addListener(new AnimatorListenerAdapter() {
5963                            @Override
5964                            public void onAnimationEnd(Animator animation) {
5965                                super.onAnimationEnd(animation);
5966                                // Move the notification view back over the menu
5967                                row.resetTranslation();
5968                            }
5969                        });
5970                        a.start();
5971                        final boolean needsFalsingProtection =
5972                                (mState == StatusBarState.KEYGUARD &&
5973                                !mAccessibilityManager.isTouchExplorationEnabled());
5974                        guts.setExposed(true /* exposed */, needsFalsingProtection);
5975                        row.closeRemoteInput();
5976                        mStackScroller.onHeightChanged(row, true /* needsAnimation */);
5977                        mNotificationGutsExposed = guts;
5978                        mGutsMenuItem = item;
5979                    }
5980                });
5981                return true;
5982            }
5983        };
5984    }
5985
5986    /**
5987     * Returns the exposed NotificationGuts or null if none are exposed.
5988     */
5989    public NotificationGuts getExposedGuts() {
5990        return mNotificationGutsExposed;
5991    }
5992
5993    /**
5994     * Closes guts or notification menus that might be visible and saves any changes.
5995     *
5996     * @param removeLeavebehinds true if leavebehinds (e.g. snooze) should be closed.
5997     * @param force true if guts should be closed regardless of state (used for snooze only).
5998     * @param removeControls true if controls (e.g. info) should be closed.
5999     * @param x if closed based on touch location, this is the x touch location.
6000     * @param y if closed based on touch location, this is the y touch location.
6001     * @param resetMenu if any notification menus that might be revealed should be closed.
6002     */
6003    public void closeAndSaveGuts(boolean removeLeavebehinds, boolean force, boolean removeControls,
6004            int x, int y, boolean resetMenu) {
6005        if (mNotificationGutsExposed != null) {
6006            mNotificationGutsExposed.closeControls(removeLeavebehinds, removeControls, x, y, force);
6007        }
6008        if (resetMenu) {
6009            mStackScroller.resetExposedMenuView(false /* animate */, true /* force */);
6010        }
6011    }
6012
6013    @Override
6014    public void toggleSplitScreen() {
6015        toggleSplitScreenMode(-1 /* metricsDockAction */, -1 /* metricsUndockAction */);
6016    }
6017
6018    @Override
6019    public void preloadRecentApps() {
6020        int msg = MSG_PRELOAD_RECENT_APPS;
6021        mHandler.removeMessages(msg);
6022        mHandler.sendEmptyMessage(msg);
6023    }
6024
6025    @Override
6026    public void cancelPreloadRecentApps() {
6027        int msg = MSG_CANCEL_PRELOAD_RECENT_APPS;
6028        mHandler.removeMessages(msg);
6029        mHandler.sendEmptyMessage(msg);
6030    }
6031
6032    @Override
6033    public void dismissKeyboardShortcutsMenu() {
6034        int msg = MSG_DISMISS_KEYBOARD_SHORTCUTS_MENU;
6035        mHandler.removeMessages(msg);
6036        mHandler.sendEmptyMessage(msg);
6037    }
6038
6039    @Override
6040    public void toggleKeyboardShortcutsMenu(int deviceId) {
6041        int msg = MSG_TOGGLE_KEYBOARD_SHORTCUTS_MENU;
6042        mHandler.removeMessages(msg);
6043        mHandler.obtainMessage(msg, deviceId, 0).sendToTarget();
6044    }
6045
6046    protected void sendCloseSystemWindows(String reason) {
6047        try {
6048            ActivityManager.getService().closeSystemDialogs(reason);
6049        } catch (RemoteException e) {
6050        }
6051    }
6052
6053    protected void toggleKeyboardShortcuts(int deviceId) {
6054        KeyboardShortcuts.toggle(mContext, deviceId);
6055    }
6056
6057    protected void dismissKeyboardShortcuts() {
6058        KeyboardShortcuts.dismiss();
6059    }
6060
6061    /**
6062     * Save the current "public" (locked and secure) state of the lockscreen.
6063     */
6064    public void setLockscreenPublicMode(boolean publicMode, int userId) {
6065        mLockscreenPublicMode.put(userId, publicMode);
6066    }
6067
6068    public boolean isLockscreenPublicMode(int userId) {
6069        return mLockscreenPublicMode.get(userId, false);
6070    }
6071
6072    /**
6073     * Has the given user chosen to allow notifications to be shown even when the lockscreen is in
6074     * "public" (secure & locked) mode?
6075     */
6076    public boolean userAllowsNotificationsInPublic(int userHandle) {
6077        if (userHandle == UserHandle.USER_ALL) {
6078            return true;
6079        }
6080
6081        if (mUsersAllowingNotifications.indexOfKey(userHandle) < 0) {
6082            final boolean allowed = 0 != Settings.Secure.getIntForUser(
6083                    mContext.getContentResolver(),
6084                    Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0, userHandle);
6085            mUsersAllowingNotifications.append(userHandle, allowed);
6086            return allowed;
6087        }
6088
6089        return mUsersAllowingNotifications.get(userHandle);
6090    }
6091
6092    /**
6093     * Has the given user chosen to allow their private (full) notifications to be shown even
6094     * when the lockscreen is in "public" (secure & locked) mode?
6095     */
6096    public boolean userAllowsPrivateNotificationsInPublic(int userHandle) {
6097        if (userHandle == UserHandle.USER_ALL) {
6098            return true;
6099        }
6100
6101        if (mUsersAllowingPrivateNotifications.indexOfKey(userHandle) < 0) {
6102            final boolean allowedByUser = 0 != Settings.Secure.getIntForUser(
6103                    mContext.getContentResolver(),
6104                    Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0, userHandle);
6105            final boolean allowedByDpm = adminAllowsUnredactedNotifications(userHandle);
6106            final boolean allowed = allowedByUser && allowedByDpm;
6107            mUsersAllowingPrivateNotifications.append(userHandle, allowed);
6108            return allowed;
6109        }
6110
6111        return mUsersAllowingPrivateNotifications.get(userHandle);
6112    }
6113
6114    private boolean adminAllowsUnredactedNotifications(int userHandle) {
6115        if (userHandle == UserHandle.USER_ALL) {
6116            return true;
6117        }
6118        final int dpmFlags = mDevicePolicyManager.getKeyguardDisabledFeatures(null /* admin */,
6119                    userHandle);
6120        return (dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS) == 0;
6121    }
6122
6123    /**
6124     * Returns true if we're on a secure lockscreen and the user wants to hide notification data.
6125     * If so, notifications should be hidden.
6126     */
6127    @Override  // NotificationData.Environment
6128    public boolean shouldHideNotifications(int userId) {
6129        return isLockscreenPublicMode(userId) && !userAllowsNotificationsInPublic(userId)
6130                || (userId != mCurrentUserId && shouldHideNotifications(mCurrentUserId));
6131    }
6132
6133    /**
6134     * Returns true if we're on a secure lockscreen and the user wants to hide notifications via
6135     * package-specific override.
6136     */
6137    @Override // NotificationDate.Environment
6138    public boolean shouldHideNotifications(String key) {
6139        return isLockscreenPublicMode(mCurrentUserId)
6140                && mNotificationData.getVisibilityOverride(key) == Notification.VISIBILITY_SECRET;
6141    }
6142
6143    /**
6144     * Returns true if we're on a secure lockscreen.
6145     */
6146    @Override  // NotificationData.Environment
6147    public boolean isSecurelyLocked(int userId) {
6148        return isLockscreenPublicMode(userId);
6149    }
6150
6151    public void onNotificationClear(StatusBarNotification notification) {
6152        try {
6153            mBarService.onNotificationClear(
6154                    notification.getPackageName(),
6155                    notification.getTag(),
6156                    notification.getId(),
6157                    notification.getUserId());
6158        } catch (android.os.RemoteException ex) {
6159            // oh well
6160        }
6161    }
6162
6163    /**
6164     * Called when the notification panel layouts
6165     */
6166    public void onPanelLaidOut() {
6167        if (mState == StatusBarState.KEYGUARD) {
6168            // Since the number of notifications is determined based on the height of the view, we
6169            // need to update them.
6170            int maxBefore = getMaxKeyguardNotifications(false /* recompute */);
6171            int maxNotifications = getMaxKeyguardNotifications(true /* recompute */);
6172            if (maxBefore != maxNotifications) {
6173                updateRowStates();
6174            }
6175        }
6176    }
6177
6178    protected void inflateViews(Entry entry, ViewGroup parent) {
6179        PackageManager pmUser = getPackageManagerForUser(mContext,
6180                entry.notification.getUser().getIdentifier());
6181
6182        final StatusBarNotification sbn = entry.notification;
6183        if (entry.row != null) {
6184            entry.reset();
6185            updateNotification(entry, pmUser, sbn, entry.row);
6186        } else {
6187            new RowInflaterTask().inflate(mContext, parent, entry,
6188                    row -> {
6189                        bindRow(entry, pmUser, sbn, row);
6190                        updateNotification(entry, pmUser, sbn, row);
6191                    });
6192        }
6193
6194    }
6195
6196    private void bindRow(Entry entry, PackageManager pmUser,
6197            StatusBarNotification sbn, ExpandableNotificationRow row) {
6198        row.setExpansionLogger(this, entry.notification.getKey());
6199        row.setGroupManager(mGroupManager);
6200        row.setHeadsUpManager(mHeadsUpManager);
6201        row.setRemoteInputController(mRemoteInputController);
6202        row.setOnExpandClickListener(this);
6203        row.setRemoteViewClickHandler(mOnClickHandler);
6204        row.setInflationCallback(this);
6205
6206        // Get the app name.
6207        // Note that Notification.Builder#bindHeaderAppName has similar logic
6208        // but since this field is used in the guts, it must be accurate.
6209        // Therefore we will only show the application label, or, failing that, the
6210        // package name. No substitutions.
6211        final String pkg = sbn.getPackageName();
6212        String appname = pkg;
6213        try {
6214            final ApplicationInfo info = pmUser.getApplicationInfo(pkg,
6215                    PackageManager.MATCH_UNINSTALLED_PACKAGES
6216                            | PackageManager.MATCH_DISABLED_COMPONENTS);
6217            if (info != null) {
6218                appname = String.valueOf(pmUser.getApplicationLabel(info));
6219            }
6220        } catch (NameNotFoundException e) {
6221            // Do nothing
6222        }
6223        row.setAppName(appname);
6224        row.setOnDismissRunnable(() ->
6225                performRemoveNotification(row.getStatusBarNotification()));
6226        row.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
6227        if (ENABLE_REMOTE_INPUT) {
6228            row.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
6229        }
6230    }
6231
6232    private void updateNotification(Entry entry, PackageManager pmUser,
6233            StatusBarNotification sbn, ExpandableNotificationRow row) {
6234        row.setNeedsRedaction(needsRedaction(entry));
6235        boolean isLowPriority = mNotificationData.isAmbient(sbn.getKey());
6236        row.setIsLowPriority(isLowPriority);
6237        // bind the click event to the content area
6238        mNotificationClicker.register(row, sbn);
6239
6240        // Extract target SDK version.
6241        try {
6242            ApplicationInfo info = pmUser.getApplicationInfo(sbn.getPackageName(), 0);
6243            entry.targetSdk = info.targetSdkVersion;
6244        } catch (NameNotFoundException ex) {
6245            Log.e(TAG, "Failed looking up ApplicationInfo for " + sbn.getPackageName(), ex);
6246        }
6247        row.setLegacy(entry.targetSdk >= Build.VERSION_CODES.GINGERBREAD
6248                && entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
6249        entry.setIconTag(R.id.icon_is_pre_L, entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
6250        entry.autoRedacted = entry.notification.getNotification().publicVersion == null;
6251
6252        entry.row = row;
6253        entry.row.setOnActivatedListener(this);
6254
6255        boolean useIncreasedCollapsedHeight = mMessagingUtil.isImportantMessaging(sbn,
6256                mNotificationData.getImportance(sbn.getKey()));
6257        boolean useIncreasedHeadsUp = useIncreasedCollapsedHeight && mPanelExpanded;
6258        row.setUseIncreasedCollapsedHeight(useIncreasedCollapsedHeight);
6259        row.setUseIncreasedHeadsUpHeight(useIncreasedHeadsUp);
6260        row.updateNotification(entry);
6261    }
6262
6263    /**
6264     * Adds RemoteInput actions from the WearableExtender; to be removed once more apps support this
6265     * via first-class API.
6266     *
6267     * TODO: Remove once enough apps specify remote inputs on their own.
6268     */
6269    private void processForRemoteInput(Notification n) {
6270        if (!ENABLE_REMOTE_INPUT) return;
6271
6272        if (n.extras != null && n.extras.containsKey("android.wearable.EXTENSIONS") &&
6273                (n.actions == null || n.actions.length == 0)) {
6274            Notification.Action viableAction = null;
6275            Notification.WearableExtender we = new Notification.WearableExtender(n);
6276
6277            List<Notification.Action> actions = we.getActions();
6278            final int numActions = actions.size();
6279
6280            for (int i = 0; i < numActions; i++) {
6281                Notification.Action action = actions.get(i);
6282                if (action == null) {
6283                    continue;
6284                }
6285                RemoteInput[] remoteInputs = action.getRemoteInputs();
6286                if (remoteInputs == null) {
6287                    continue;
6288                }
6289                for (RemoteInput ri : remoteInputs) {
6290                    if (ri.getAllowFreeFormInput()) {
6291                        viableAction = action;
6292                        break;
6293                    }
6294                }
6295                if (viableAction != null) {
6296                    break;
6297                }
6298            }
6299
6300            if (viableAction != null) {
6301                Notification.Builder rebuilder = Notification.Builder.recoverBuilder(mContext, n);
6302                rebuilder.setActions(viableAction);
6303                rebuilder.build(); // will rewrite n
6304            }
6305        }
6306    }
6307
6308    public void startPendingIntentDismissingKeyguard(final PendingIntent intent) {
6309        if (!isDeviceProvisioned()) return;
6310
6311        final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
6312        final boolean afterKeyguardGone = intent.isActivity()
6313                && PreviewInflater.wouldLaunchResolverActivity(mContext, intent.getIntent(),
6314                mCurrentUserId);
6315        dismissKeyguardThenExecute(new OnDismissAction() {
6316            @Override
6317            public boolean onDismiss() {
6318                new Thread() {
6319                    @Override
6320                    public void run() {
6321                        try {
6322                            // The intent we are sending is for the application, which
6323                            // won't have permission to immediately start an activity after
6324                            // the user switches to home.  We know it is safe to do at this
6325                            // point, so make sure new activity switches are now allowed.
6326                            ActivityManager.getService().resumeAppSwitches();
6327                        } catch (RemoteException e) {
6328                        }
6329                        try {
6330                            intent.send(null, 0, null, null, null, null, getActivityOptions());
6331                        } catch (PendingIntent.CanceledException e) {
6332                            // the stack trace isn't very helpful here.
6333                            // Just log the exception message.
6334                            Log.w(TAG, "Sending intent failed: " + e);
6335
6336                            // TODO: Dismiss Keyguard.
6337                        }
6338                        if (intent.isActivity()) {
6339                            mAssistManager.hideAssist();
6340                        }
6341                    }
6342                }.start();
6343
6344                // close the shade if it was open
6345                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
6346                        true /* force */, true /* delayed */);
6347                visibilityChanged(false);
6348
6349                return true;
6350            }
6351        }, afterKeyguardGone);
6352    }
6353
6354
6355    private final class NotificationClicker implements View.OnClickListener {
6356
6357        @Override
6358        public void onClick(final View v) {
6359            if (!(v instanceof ExpandableNotificationRow)) {
6360                Log.e(TAG, "NotificationClicker called on a view that is not a notification row.");
6361                return;
6362            }
6363
6364            wakeUpIfDozing(SystemClock.uptimeMillis(), v);
6365
6366            final ExpandableNotificationRow row = (ExpandableNotificationRow) v;
6367            final StatusBarNotification sbn = row.getStatusBarNotification();
6368            if (sbn == null) {
6369                Log.e(TAG, "NotificationClicker called on an unclickable notification,");
6370                return;
6371            }
6372
6373            // Check if the notification is displaying the menu, if so slide notification back
6374            if (row.getProvider() != null && row.getProvider().isMenuVisible()) {
6375                row.animateTranslateNotification(0);
6376                return;
6377            }
6378
6379            Notification notification = sbn.getNotification();
6380            final PendingIntent intent = notification.contentIntent != null
6381                    ? notification.contentIntent
6382                    : notification.fullScreenIntent;
6383            final String notificationKey = sbn.getKey();
6384
6385            // Mark notification for one frame.
6386            row.setJustClicked(true);
6387            DejankUtils.postAfterTraversal(new Runnable() {
6388                @Override
6389                public void run() {
6390                    row.setJustClicked(false);
6391                }
6392            });
6393
6394            final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
6395            final boolean afterKeyguardGone = intent.isActivity()
6396                    && PreviewInflater.wouldLaunchResolverActivity(mContext, intent.getIntent(),
6397                            mCurrentUserId);
6398            dismissKeyguardThenExecute(new OnDismissAction() {
6399                @Override
6400                public boolean onDismiss() {
6401                    if (mHeadsUpManager != null && mHeadsUpManager.isHeadsUp(notificationKey)) {
6402                        // Release the HUN notification to the shade.
6403
6404                        if (isPanelFullyCollapsed()) {
6405                            HeadsUpManager.setIsClickedNotification(row, true);
6406                        }
6407                        //
6408                        // In most cases, when FLAG_AUTO_CANCEL is set, the notification will
6409                        // become canceled shortly by NoMan, but we can't assume that.
6410                        mHeadsUpManager.releaseImmediately(notificationKey);
6411                    }
6412                    StatusBarNotification parentToCancel = null;
6413                    if (shouldAutoCancel(sbn) && mGroupManager.isOnlyChildInGroup(sbn)) {
6414                        StatusBarNotification summarySbn = mGroupManager.getLogicalGroupSummary(sbn)
6415                                        .getStatusBarNotification();
6416                        if (shouldAutoCancel(summarySbn)) {
6417                            parentToCancel = summarySbn;
6418                        }
6419                    }
6420                    final StatusBarNotification parentToCancelFinal = parentToCancel;
6421                    new Thread() {
6422                        @Override
6423                        public void run() {
6424                            try {
6425                                // The intent we are sending is for the application, which
6426                                // won't have permission to immediately start an activity after
6427                                // the user switches to home.  We know it is safe to do at this
6428                                // point, so make sure new activity switches are now allowed.
6429                                ActivityManager.getService().resumeAppSwitches();
6430                            } catch (RemoteException e) {
6431                            }
6432                            if (intent != null) {
6433                                // If we are launching a work activity and require to launch
6434                                // separate work challenge, we defer the activity action and cancel
6435                                // notification until work challenge is unlocked.
6436                                if (intent.isActivity()) {
6437                                    final int userId = intent.getCreatorUserHandle()
6438                                            .getIdentifier();
6439                                    if (mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)
6440                                            && mKeyguardManager.isDeviceLocked(userId)) {
6441                                        // TODO(b/28935539): should allow certain activities to
6442                                        // bypass work challenge
6443                                        if (startWorkChallengeIfNecessary(userId,
6444                                                intent.getIntentSender(), notificationKey)) {
6445                                            // Show work challenge, do not run PendingIntent and
6446                                            // remove notification
6447                                            return;
6448                                        }
6449                                    }
6450                                }
6451                                try {
6452                                    intent.send(null, 0, null, null, null, null,
6453                                            getActivityOptions());
6454                                } catch (PendingIntent.CanceledException e) {
6455                                    // the stack trace isn't very helpful here.
6456                                    // Just log the exception message.
6457                                    Log.w(TAG, "Sending contentIntent failed: " + e);
6458
6459                                    // TODO: Dismiss Keyguard.
6460                                }
6461                                if (intent.isActivity()) {
6462                                    mAssistManager.hideAssist();
6463                                }
6464                            }
6465
6466                            try {
6467                                mBarService.onNotificationClick(notificationKey);
6468                            } catch (RemoteException ex) {
6469                                // system process is dead if we're here.
6470                            }
6471                            if (parentToCancelFinal != null) {
6472                                // We have to post it to the UI thread for synchronization
6473                                mHandler.post(new Runnable() {
6474                                    @Override
6475                                    public void run() {
6476                                        Runnable removeRunnable = new Runnable() {
6477                                            @Override
6478                                            public void run() {
6479                                                performRemoveNotification(parentToCancelFinal);
6480                                            }
6481                                        };
6482                                        if (isCollapsing()) {
6483                                            // To avoid lags we're only performing the remove
6484                                            // after the shade was collapsed
6485                                            addPostCollapseAction(removeRunnable);
6486                                        } else {
6487                                            removeRunnable.run();
6488                                        }
6489                                    }
6490                                });
6491                            }
6492                        }
6493                    }.start();
6494
6495                    // close the shade if it was open
6496                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
6497                            true /* force */, true /* delayed */);
6498                    visibilityChanged(false);
6499
6500                    return true;
6501                }
6502            }, afterKeyguardGone);
6503        }
6504
6505        private boolean shouldAutoCancel(StatusBarNotification sbn) {
6506            int flags = sbn.getNotification().flags;
6507            if ((flags & Notification.FLAG_AUTO_CANCEL) != Notification.FLAG_AUTO_CANCEL) {
6508                return false;
6509            }
6510            if ((flags & Notification.FLAG_FOREGROUND_SERVICE) != 0) {
6511                return false;
6512            }
6513            return true;
6514        }
6515
6516        public void register(ExpandableNotificationRow row, StatusBarNotification sbn) {
6517            Notification notification = sbn.getNotification();
6518            if (notification.contentIntent != null || notification.fullScreenIntent != null) {
6519                row.setOnClickListener(this);
6520            } else {
6521                row.setOnClickListener(null);
6522            }
6523        }
6524    }
6525
6526    protected Bundle getActivityOptions() {
6527        // Anything launched from the notification shade should always go into the
6528        // fullscreen stack.
6529        ActivityOptions options = ActivityOptions.makeBasic();
6530        options.setLaunchStackId(StackId.FULLSCREEN_WORKSPACE_STACK_ID);
6531        return options.toBundle();
6532    }
6533
6534    protected void visibilityChanged(boolean visible) {
6535        if (mVisible != visible) {
6536            mVisible = visible;
6537            if (!visible) {
6538                closeAndSaveGuts(true /* removeLeavebehind */, true /* force */,
6539                        true /* removeControls */, -1 /* x */, -1 /* y */, true /* resetMenu */);
6540            }
6541        }
6542        updateVisibleToUser();
6543    }
6544
6545    protected void updateVisibleToUser() {
6546        boolean oldVisibleToUser = mVisibleToUser;
6547        mVisibleToUser = mVisible && mDeviceInteractive;
6548
6549        if (oldVisibleToUser != mVisibleToUser) {
6550            handleVisibleToUserChanged(mVisibleToUser);
6551        }
6552    }
6553
6554    /**
6555     * Clear Buzz/Beep/Blink.
6556     */
6557    public void clearNotificationEffects() {
6558        try {
6559            mBarService.clearNotificationEffects();
6560        } catch (RemoteException e) {
6561            // Won't fail unless the world has ended.
6562        }
6563    }
6564
6565    /**
6566     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
6567     * about the failure.
6568     *
6569     * WARNING: this will call back into us.  Don't hold any locks.
6570     */
6571    void handleNotificationError(StatusBarNotification n, String message) {
6572        removeNotification(n.getKey(), null);
6573        try {
6574            mBarService.onNotificationError(n.getPackageName(), n.getTag(), n.getId(), n.getUid(),
6575                    n.getInitialPid(), message, n.getUserId());
6576        } catch (RemoteException ex) {
6577            // The end is nigh.
6578        }
6579    }
6580
6581    protected StatusBarNotification removeNotificationViews(String key, RankingMap ranking) {
6582        NotificationData.Entry entry = mNotificationData.remove(key, ranking);
6583        if (entry == null) {
6584            Log.w(TAG, "removeNotification for unknown key: " + key);
6585            return null;
6586        }
6587        updateNotifications();
6588        Dependency.get(LeakDetector.class).trackGarbage(entry);
6589        return entry.notification;
6590    }
6591
6592    protected NotificationData.Entry createNotificationViews(StatusBarNotification sbn)
6593            throws InflationException {
6594        if (DEBUG) {
6595            Log.d(TAG, "createNotificationViews(notification=" + sbn);
6596        }
6597        NotificationData.Entry entry = new NotificationData.Entry(sbn);
6598        Dependency.get(LeakDetector.class).trackInstance(entry);
6599        entry.createIcons(mContext, sbn);
6600        // Construct the expanded view.
6601        inflateViews(entry, mStackScroller);
6602        return entry;
6603    }
6604
6605    protected void addNotificationViews(Entry entry) {
6606        if (entry == null) {
6607            return;
6608        }
6609        // Add the expanded view and icon.
6610        mNotificationData.add(entry);
6611        updateNotifications();
6612    }
6613
6614    /**
6615     * Updates expanded, dimmed and locked states of notification rows.
6616     */
6617    protected void updateRowStates() {
6618        final int N = mStackScroller.getChildCount();
6619
6620        int visibleNotifications = 0;
6621        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
6622        int maxNotifications = -1;
6623        if (onKeyguard) {
6624            maxNotifications = getMaxKeyguardNotifications(true /* recompute */);
6625        }
6626        mStackScroller.setMaxDisplayedNotifications(maxNotifications);
6627        Stack<ExpandableNotificationRow> stack = new Stack<>();
6628        for (int i = N - 1; i >= 0; i--) {
6629            View child = mStackScroller.getChildAt(i);
6630            if (!(child instanceof ExpandableNotificationRow)) {
6631                continue;
6632            }
6633            stack.push((ExpandableNotificationRow) child);
6634        }
6635        while(!stack.isEmpty()) {
6636            ExpandableNotificationRow row = stack.pop();
6637            NotificationData.Entry entry = row.getEntry();
6638            boolean childNotification = mGroupManager.isChildInGroupWithSummary(entry.notification);
6639            if (onKeyguard) {
6640                row.setOnKeyguard(true);
6641            } else {
6642                row.setOnKeyguard(false);
6643                row.setSystemExpanded(visibleNotifications == 0 && !childNotification);
6644            }
6645            entry.row.setShowAmbient(isDozing());
6646            int userId = entry.notification.getUserId();
6647            boolean suppressedSummary = mGroupManager.isSummaryOfSuppressedGroup(
6648                    entry.notification) && !entry.row.isRemoved();
6649            boolean showOnKeyguard = shouldShowOnKeyguard(entry.notification);
6650            if (suppressedSummary
6651                    || (isLockscreenPublicMode(userId) && !mShowLockscreenNotifications)
6652                    || (onKeyguard && !showOnKeyguard)) {
6653                entry.row.setVisibility(View.GONE);
6654            } else {
6655                boolean wasGone = entry.row.getVisibility() == View.GONE;
6656                if (wasGone) {
6657                    entry.row.setVisibility(View.VISIBLE);
6658                }
6659                if (!childNotification && !entry.row.isRemoved()) {
6660                    if (wasGone) {
6661                        // notify the scroller of a child addition
6662                        mStackScroller.generateAddAnimation(entry.row,
6663                                !showOnKeyguard /* fromMoreCard */);
6664                    }
6665                    visibleNotifications++;
6666                }
6667            }
6668            if (row.isSummaryWithChildren()) {
6669                List<ExpandableNotificationRow> notificationChildren =
6670                        row.getNotificationChildren();
6671                int size = notificationChildren.size();
6672                for (int i = size - 1; i >= 0; i--) {
6673                    stack.push(notificationChildren.get(i));
6674                }
6675            }
6676        }
6677        mNotificationPanel.setNoVisibleNotifications(visibleNotifications == 0);
6678
6679        mStackScroller.changeViewPosition(mDismissView, mStackScroller.getChildCount() - 1);
6680        mStackScroller.changeViewPosition(mEmptyShadeView, mStackScroller.getChildCount() - 2);
6681        mStackScroller.changeViewPosition(mNotificationShelf, mStackScroller.getChildCount() - 3);
6682    }
6683
6684    public boolean shouldShowOnKeyguard(StatusBarNotification sbn) {
6685        return mShowLockscreenNotifications && !mNotificationData.isAmbient(sbn.getKey());
6686    }
6687
6688    // extended in StatusBar
6689    protected void setShowLockscreenNotifications(boolean show) {
6690        mShowLockscreenNotifications = show;
6691    }
6692
6693    protected void setLockScreenAllowRemoteInput(boolean allowLockscreenRemoteInput) {
6694        mAllowLockscreenRemoteInput = allowLockscreenRemoteInput;
6695    }
6696
6697    private void updateLockscreenNotificationSetting() {
6698        final boolean show = Settings.Secure.getIntForUser(mContext.getContentResolver(),
6699                Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
6700                1,
6701                mCurrentUserId) != 0;
6702        final int dpmFlags = mDevicePolicyManager.getKeyguardDisabledFeatures(
6703                null /* admin */, mCurrentUserId);
6704        final boolean allowedByDpm = (dpmFlags
6705                & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS) == 0;
6706
6707        setShowLockscreenNotifications(show && allowedByDpm);
6708
6709        if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
6710            final boolean remoteInput = Settings.Secure.getIntForUser(mContext.getContentResolver(),
6711                    Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT,
6712                    0,
6713                    mCurrentUserId) != 0;
6714            final boolean remoteInputDpm =
6715                    (dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_REMOTE_INPUT) == 0;
6716
6717            setLockScreenAllowRemoteInput(remoteInput && remoteInputDpm);
6718        } else {
6719            setLockScreenAllowRemoteInput(false);
6720        }
6721    }
6722
6723    public void updateNotification(StatusBarNotification notification, RankingMap ranking)
6724            throws InflationException {
6725        if (DEBUG) Log.d(TAG, "updateNotification(" + notification + ")");
6726
6727        final String key = notification.getKey();
6728        abortExistingInflation(key);
6729        Entry entry = mNotificationData.get(key);
6730        if (entry == null) {
6731            return;
6732        } else {
6733            mHeadsUpEntriesToRemoveOnSwitch.remove(entry);
6734            mRemoteInputEntriesToRemoveOnCollapse.remove(entry);
6735        }
6736
6737        Notification n = notification.getNotification();
6738        mNotificationData.updateRanking(ranking);
6739
6740        final StatusBarNotification oldNotification = entry.notification;
6741        entry.notification = notification;
6742        mGroupManager.onEntryUpdated(entry, oldNotification);
6743
6744        entry.updateIcons(mContext, n);
6745        inflateViews(entry, mStackScroller);
6746
6747        boolean shouldPeek = shouldPeek(entry, notification);
6748        boolean alertAgain = alertAgain(entry, n);
6749
6750        updateHeadsUp(key, entry, shouldPeek, alertAgain);
6751        updateNotifications();
6752
6753        if (!notification.isClearable()) {
6754            // The user may have performed a dismiss action on the notification, since it's
6755            // not clearable we should snap it back.
6756            mStackScroller.snapViewIfNeeded(entry.row);
6757        }
6758
6759        if (DEBUG) {
6760            // Is this for you?
6761            boolean isForCurrentUser = isNotificationForCurrentProfiles(notification);
6762            Log.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
6763        }
6764        setAreThereNotifications();
6765    }
6766
6767    protected void updatePublicContentView(Entry entry,
6768            StatusBarNotification sbn) {
6769        final RemoteViews publicContentView = entry.cachedPublicContentView;
6770        View inflatedView = entry.getPublicContentView();
6771        if (entry.autoRedacted && publicContentView != null && inflatedView != null) {
6772            final boolean disabledByPolicy =
6773                    !adminAllowsUnredactedNotifications(entry.notification.getUserId());
6774            String notificationHiddenText = mContext.getString(disabledByPolicy
6775                    ? com.android.internal.R.string.notification_hidden_by_policy_text
6776                    : com.android.internal.R.string.notification_hidden_text);
6777            TextView titleView = (TextView) inflatedView.findViewById(android.R.id.title);
6778            if (titleView != null
6779                    && !titleView.getText().toString().equals(notificationHiddenText)) {
6780                titleView.setText(notificationHiddenText);
6781            }
6782        }
6783    }
6784
6785    protected void notifyHeadsUpScreenOff() {
6786        maybeEscalateHeadsUp();
6787    }
6788
6789    private boolean alertAgain(Entry oldEntry, Notification newNotification) {
6790        return oldEntry == null || !oldEntry.hasInterrupted()
6791                || (newNotification.flags & Notification.FLAG_ONLY_ALERT_ONCE) == 0;
6792    }
6793
6794    protected boolean shouldPeek(Entry entry) {
6795        return shouldPeek(entry, entry.notification);
6796    }
6797
6798    protected boolean shouldPeek(Entry entry, StatusBarNotification sbn) {
6799        if (!mUseHeadsUp || isDeviceInVrMode()) {
6800            return false;
6801        }
6802
6803        if (mNotificationData.shouldFilterOut(sbn)) {
6804            if (DEBUG) Log.d(TAG, "No peeking: filtered notification: " + sbn.getKey());
6805            return false;
6806        }
6807
6808        boolean inUse = mPowerManager.isScreenOn()
6809                && !SystemServicesProxy.getInstance(mContext).isDreaming();
6810
6811        if (!inUse && !isDozing()) {
6812            if (DEBUG) {
6813                Log.d(TAG, "No peeking: not in use: " + sbn.getKey());
6814            }
6815            return false;
6816        }
6817
6818        if (mNotificationData.shouldSuppressScreenOn(sbn.getKey())) {
6819            if (DEBUG) Log.d(TAG, "No peeking: suppressed by DND: " + sbn.getKey());
6820            return false;
6821        }
6822
6823        if (entry.hasJustLaunchedFullScreenIntent()) {
6824            if (DEBUG) Log.d(TAG, "No peeking: recent fullscreen: " + sbn.getKey());
6825            return false;
6826        }
6827
6828        if (isSnoozedPackage(sbn)) {
6829            if (DEBUG) Log.d(TAG, "No peeking: snoozed package: " + sbn.getKey());
6830            return false;
6831        }
6832
6833        // Allow peeking for DEFAULT notifications only if we're on Ambient Display.
6834        int importanceLevel = isDozing() ? NotificationManager.IMPORTANCE_DEFAULT
6835                : NotificationManager.IMPORTANCE_HIGH;
6836        if (mNotificationData.getImportance(sbn.getKey()) < importanceLevel) {
6837            if (DEBUG) Log.d(TAG, "No peeking: unimportant notification: " + sbn.getKey());
6838            return false;
6839        }
6840
6841        if (sbn.getNotification().fullScreenIntent != null) {
6842            if (mAccessibilityManager.isTouchExplorationEnabled()) {
6843                if (DEBUG) Log.d(TAG, "No peeking: accessible fullscreen: " + sbn.getKey());
6844                return false;
6845            } else {
6846                // we only allow head-up on the lockscreen if it doesn't have a fullscreen intent
6847                return !mStatusBarKeyguardViewManager.isShowing()
6848                        || mStatusBarKeyguardViewManager.isOccluded();
6849            }
6850        }
6851
6852        return true;
6853    }
6854
6855    /**
6856     * @return Whether the security bouncer from Keyguard is showing.
6857     */
6858    public boolean isBouncerShowing() {
6859        return mBouncerShowing;
6860    }
6861
6862    /**
6863     * @return a PackageManger for userId or if userId is < 0 (USER_ALL etc) then
6864     *         return PackageManager for mContext
6865     */
6866    public static PackageManager getPackageManagerForUser(Context context, int userId) {
6867        Context contextForUser = context;
6868        // UserHandle defines special userId as negative values, e.g. USER_ALL
6869        if (userId >= 0) {
6870            try {
6871                // Create a context for the correct user so if a package isn't installed
6872                // for user 0 we can still load information about the package.
6873                contextForUser =
6874                        context.createPackageContextAsUser(context.getPackageName(),
6875                        Context.CONTEXT_RESTRICTED,
6876                        new UserHandle(userId));
6877            } catch (NameNotFoundException e) {
6878                // Shouldn't fail to find the package name for system ui.
6879            }
6880        }
6881        return contextForUser.getPackageManager();
6882    }
6883
6884    @Override
6885    public void logNotificationExpansion(String key, boolean userAction, boolean expanded) {
6886        mUiOffloadThread.submit(() -> {
6887            try {
6888                mBarService.onNotificationExpansionChanged(key, userAction, expanded);
6889            } catch (RemoteException e) {
6890                // Ignore.
6891            }
6892        });
6893    }
6894
6895    public boolean isKeyguardSecure() {
6896        if (mStatusBarKeyguardViewManager == null) {
6897            // startKeyguard() hasn't been called yet, so we don't know.
6898            // Make sure anything that needs to know isKeyguardSecure() checks and re-checks this
6899            // value onVisibilityChanged().
6900            Slog.w(TAG, "isKeyguardSecure() called before startKeyguard(), returning false",
6901                    new Throwable());
6902            return false;
6903        }
6904        return mStatusBarKeyguardViewManager.isSecure();
6905    }
6906
6907    @Override
6908    public void showAssistDisclosure() {
6909        if (mAssistManager != null) {
6910            mAssistManager.showDisclosure();
6911        }
6912    }
6913
6914    @Override
6915    public void startAssist(Bundle args) {
6916        if (mAssistManager != null) {
6917            mAssistManager.startAssist(args);
6918        }
6919    }
6920    // End Extra BaseStatusBarMethods.
6921}
6922