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