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