StatusBar.java revision bd54d2c2bdc36e9ae317de088f0f7a25e955d905
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 (mState == StatusBarState.KEYGUARD) {
4060            instantExpandNotificationsPanel();
4061        } else if (mState == StatusBarState.FULLSCREEN_USER_SWITCHER) {
4062            instantCollapseNotificationPanel();
4063        }
4064        mLeaveOpenOnKeyguardHide = false;
4065        if (mDraggedDownRow != null) {
4066            mDraggedDownRow.setUserLocked(false);
4067            mDraggedDownRow.notifyHeightChanged(false  /* needsAnimation */);
4068            mDraggedDownRow = null;
4069        }
4070        mPendingRemoteInputView = null;
4071        mAssistManager.onLockscreenShown();
4072    }
4073
4074    private void onLaunchTransitionFadingEnded() {
4075        mNotificationPanel.setAlpha(1.0f);
4076        mNotificationPanel.onAffordanceLaunchEnded();
4077        releaseGestureWakeLock();
4078        runLaunchTransitionEndRunnable();
4079        mLaunchTransitionFadingAway = false;
4080        mScrimController.forceHideScrims(false /* hide */);
4081        updateMediaMetaData(true /* metaDataChanged */, true);
4082    }
4083
4084    public boolean isCollapsing() {
4085        return mNotificationPanel.isCollapsing();
4086    }
4087
4088    public void addPostCollapseAction(Runnable r) {
4089        mPostCollapseRunnables.add(r);
4090    }
4091
4092    public boolean isInLaunchTransition() {
4093        return mNotificationPanel.isLaunchTransitionRunning()
4094                || mNotificationPanel.isLaunchTransitionFinished();
4095    }
4096
4097    /**
4098     * Fades the content of the keyguard away after the launch transition is done.
4099     *
4100     * @param beforeFading the runnable to be run when the circle is fully expanded and the fading
4101     *                     starts
4102     * @param endRunnable the runnable to be run when the transition is done
4103     */
4104    public void fadeKeyguardAfterLaunchTransition(final Runnable beforeFading,
4105            Runnable endRunnable) {
4106        mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
4107        mLaunchTransitionEndRunnable = endRunnable;
4108        Runnable hideRunnable = new Runnable() {
4109            @Override
4110            public void run() {
4111                mLaunchTransitionFadingAway = true;
4112                if (beforeFading != null) {
4113                    beforeFading.run();
4114                }
4115                mScrimController.forceHideScrims(true /* hide */);
4116                updateMediaMetaData(false, true);
4117                mNotificationPanel.setAlpha(1);
4118                mStackScroller.setParentNotFullyVisible(true);
4119                mNotificationPanel.animate()
4120                        .alpha(0)
4121                        .setStartDelay(FADE_KEYGUARD_START_DELAY)
4122                        .setDuration(FADE_KEYGUARD_DURATION)
4123                        .withLayer()
4124                        .withEndAction(new Runnable() {
4125                            @Override
4126                            public void run() {
4127                                onLaunchTransitionFadingEnded();
4128                            }
4129                        });
4130                mCommandQueue.appTransitionStarting(SystemClock.uptimeMillis(),
4131                        LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4132            }
4133        };
4134        if (mNotificationPanel.isLaunchTransitionRunning()) {
4135            mNotificationPanel.setLaunchTransitionEndRunnable(hideRunnable);
4136        } else {
4137            hideRunnable.run();
4138        }
4139    }
4140
4141    /**
4142     * Fades the content of the Keyguard while we are dozing and makes it invisible when finished
4143     * fading.
4144     */
4145    public void fadeKeyguardWhilePulsing() {
4146        mNotificationPanel.animate()
4147                .alpha(0f)
4148                .setStartDelay(0)
4149                .setDuration(FADE_KEYGUARD_DURATION_PULSING)
4150                .setInterpolator(ScrimController.KEYGUARD_FADE_OUT_INTERPOLATOR)
4151                .start();
4152    }
4153
4154    /**
4155     * Plays the animation when an activity that was occluding Keyguard goes away.
4156     */
4157    public void animateKeyguardUnoccluding() {
4158        mScrimController.animateKeyguardUnoccluding(500);
4159        mNotificationPanel.setExpandedFraction(0f);
4160        animateExpandNotificationsPanel();
4161    }
4162
4163    /**
4164     * Starts the timeout when we try to start the affordances on Keyguard. We usually rely that
4165     * Keyguard goes away via fadeKeyguardAfterLaunchTransition, however, that might not happen
4166     * because the launched app crashed or something else went wrong.
4167     */
4168    public void startLaunchTransitionTimeout() {
4169        mHandler.sendEmptyMessageDelayed(MSG_LAUNCH_TRANSITION_TIMEOUT,
4170                LAUNCH_TRANSITION_TIMEOUT_MS);
4171    }
4172
4173    private void onLaunchTransitionTimeout() {
4174        Log.w(TAG, "Launch transition: Timeout!");
4175        mNotificationPanel.onAffordanceLaunchEnded();
4176        releaseGestureWakeLock();
4177        mNotificationPanel.resetViews();
4178    }
4179
4180    private void runLaunchTransitionEndRunnable() {
4181        if (mLaunchTransitionEndRunnable != null) {
4182            Runnable r = mLaunchTransitionEndRunnable;
4183
4184            // mLaunchTransitionEndRunnable might call showKeyguard, which would execute it again,
4185            // which would lead to infinite recursion. Protect against it.
4186            mLaunchTransitionEndRunnable = null;
4187            r.run();
4188        }
4189    }
4190
4191    /**
4192     * @return true if we would like to stay in the shade, false if it should go away entirely
4193     */
4194    public boolean hideKeyguard() {
4195        Trace.beginSection("StatusBar#hideKeyguard");
4196        boolean staying = mLeaveOpenOnKeyguardHide;
4197        setBarState(StatusBarState.SHADE);
4198        View viewToClick = null;
4199        if (mLeaveOpenOnKeyguardHide) {
4200            mLeaveOpenOnKeyguardHide = false;
4201            long delay = calculateGoingToFullShadeDelay();
4202            mNotificationPanel.animateToFullShade(delay);
4203            if (mDraggedDownRow != null) {
4204                mDraggedDownRow.setUserLocked(false);
4205                mDraggedDownRow = null;
4206            }
4207            viewToClick = mPendingRemoteInputView;
4208            mPendingRemoteInputView = null;
4209
4210            // Disable layout transitions in navbar for this transition because the load is just
4211            // too heavy for the CPU and GPU on any device.
4212            if (mNavigationBar != null) {
4213                mNavigationBar.disableAnimationsDuringHide(delay);
4214            }
4215        } else if (!mNotificationPanel.isCollapsing()) {
4216            instantCollapseNotificationPanel();
4217        }
4218        updateKeyguardState(staying, false /* fromShadeLocked */);
4219
4220        if (viewToClick != null && viewToClick.isAttachedToWindow()) {
4221            viewToClick.callOnClick();
4222        }
4223
4224        // Keyguard state has changed, but QS is not listening anymore. Make sure to update the tile
4225        // visibilities so next time we open the panel we know the correct height already.
4226        if (mQSPanel != null) {
4227            mQSPanel.refreshAllTiles();
4228        }
4229        mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
4230        releaseGestureWakeLock();
4231        mNotificationPanel.onAffordanceLaunchEnded();
4232        mNotificationPanel.animate().cancel();
4233        mNotificationPanel.setAlpha(1f);
4234        Trace.endSection();
4235        return staying;
4236    }
4237
4238    private void releaseGestureWakeLock() {
4239        if (mGestureWakeLock.isHeld()) {
4240            mGestureWakeLock.release();
4241        }
4242    }
4243
4244    public long calculateGoingToFullShadeDelay() {
4245        return mKeyguardFadingAwayDelay + mKeyguardFadingAwayDuration;
4246    }
4247
4248    /**
4249     * Notifies the status bar that Keyguard is going away very soon.
4250     */
4251    public void keyguardGoingAway() {
4252
4253        // Treat Keyguard exit animation as an app transition to achieve nice transition for status
4254        // bar.
4255        mKeyguardGoingAway = true;
4256        mKeyguardMonitor.notifyKeyguardGoingAway(true);
4257        mCommandQueue.appTransitionPending(true);
4258    }
4259
4260    /**
4261     * Notifies the status bar the Keyguard is fading away with the specified timings.
4262     *
4263     * @param startTime the start time of the animations in uptime millis
4264     * @param delay the precalculated animation delay in miliseconds
4265     * @param fadeoutDuration the duration of the exit animation, in milliseconds
4266     */
4267    public void setKeyguardFadingAway(long startTime, long delay, long fadeoutDuration) {
4268        mKeyguardFadingAway = true;
4269        mKeyguardFadingAwayDelay = delay;
4270        mKeyguardFadingAwayDuration = fadeoutDuration;
4271        mWaitingForKeyguardExit = false;
4272        mCommandQueue.appTransitionStarting(startTime + fadeoutDuration
4273                        - LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION,
4274                LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4275        recomputeDisableFlags(fadeoutDuration > 0 /* animate */);
4276        mCommandQueue.appTransitionStarting(
4277                    startTime - LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION,
4278                    LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
4279        mKeyguardMonitor.notifyKeyguardFadingAway(delay, fadeoutDuration);
4280    }
4281
4282    public boolean isKeyguardFadingAway() {
4283        return mKeyguardFadingAway;
4284    }
4285
4286    /**
4287     * Notifies that the Keyguard fading away animation is done.
4288     */
4289    public void finishKeyguardFadingAway() {
4290        mKeyguardFadingAway = false;
4291        mKeyguardGoingAway = false;
4292        mKeyguardMonitor.notifyKeyguardDoneFading();
4293    }
4294
4295    public void stopWaitingForKeyguardExit() {
4296        mWaitingForKeyguardExit = false;
4297    }
4298
4299    private void updatePublicMode() {
4300        final boolean showingKeyguard = mStatusBarKeyguardViewManager.isShowing();
4301        final boolean devicePublic = showingKeyguard
4302                && mStatusBarKeyguardViewManager.isSecure(mCurrentUserId);
4303
4304        // Look for public mode users. Users are considered public in either case of:
4305        //   - device keyguard is shown in secure mode;
4306        //   - profile is locked with a work challenge.
4307        for (int i = mCurrentProfiles.size() - 1; i >= 0; i--) {
4308            final int userId = mCurrentProfiles.valueAt(i).id;
4309            boolean isProfilePublic = devicePublic;
4310            if (!devicePublic && userId != mCurrentUserId) {
4311                if (mStatusBarKeyguardViewManager.isSecure(userId)) {
4312                    isProfilePublic = mKeyguardManager.isDeviceLocked(userId);
4313                }
4314            }
4315            setLockscreenPublicMode(isProfilePublic, userId);
4316        }
4317    }
4318
4319    protected void updateKeyguardState(boolean goingToFullShade, boolean fromShadeLocked) {
4320        Trace.beginSection("StatusBar#updateKeyguardState");
4321        if (mState == StatusBarState.KEYGUARD) {
4322            mKeyguardIndicationController.setVisible(true);
4323            mNotificationPanel.resetViews();
4324            if (mKeyguardUserSwitcher != null) {
4325                mKeyguardUserSwitcher.setKeyguard(true, fromShadeLocked);
4326            }
4327            mStatusBarView.removePendingHideExpandedRunnables();
4328        } else {
4329            mKeyguardIndicationController.setVisible(false);
4330            if (mKeyguardUserSwitcher != null) {
4331                mKeyguardUserSwitcher.setKeyguard(false,
4332                        goingToFullShade ||
4333                        mState == StatusBarState.SHADE_LOCKED ||
4334                        fromShadeLocked);
4335            }
4336        }
4337        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4338            mScrimController.setKeyguardShowing(true);
4339        } else {
4340            mScrimController.setKeyguardShowing(false);
4341        }
4342        mNotificationPanel.setBarState(mState, mKeyguardFadingAway, goingToFullShade);
4343        updateDozingState();
4344        updatePublicMode();
4345        updateStackScrollerState(goingToFullShade, fromShadeLocked);
4346        updateNotifications();
4347        checkBarModes();
4348        updateMediaMetaData(false, mState != StatusBarState.KEYGUARD);
4349        mKeyguardMonitor.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
4350                mStatusBarKeyguardViewManager.isSecure(),
4351                mStatusBarKeyguardViewManager.isOccluded());
4352        Trace.endSection();
4353    }
4354
4355    private void updateDozingState() {
4356        Trace.beginSection("StatusBar#updateDozingState");
4357        boolean animate = !mDozing && mDozeScrimController.isPulsing();
4358        mNotificationPanel.setDozing(mDozing, animate);
4359        mStackScroller.setDark(mDozing, animate, mWakeUpTouchLocation);
4360        mScrimController.setDozing(mDozing);
4361        mKeyguardIndicationController.setDozing(mDozing);
4362        mNotificationPanel.setDark(mDozing);
4363        updateQsExpansionEnabled();
4364
4365        // Immediately abort the dozing from the doze scrim controller in case of wake-and-unlock
4366        // for pulsing so the Keyguard fade-out animation scrim can take over.
4367        mDozeScrimController.setDozing(mDozing &&
4368                mFingerprintUnlockController.getMode()
4369                        != FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING, animate);
4370        updateRowStates();
4371        Trace.endSection();
4372    }
4373
4374    public void updateStackScrollerState(boolean goingToFullShade, boolean fromShadeLocked) {
4375        if (mStackScroller == null) return;
4376        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
4377        boolean publicMode = isAnyProfilePublicMode();
4378        mStackScroller.setHideSensitive(publicMode, goingToFullShade);
4379        mStackScroller.setDimmed(onKeyguard, fromShadeLocked /* animate */);
4380        mStackScroller.setExpandingEnabled(!onKeyguard);
4381        ActivatableNotificationView activatedChild = mStackScroller.getActivatedChild();
4382        mStackScroller.setActivatedChild(null);
4383        if (activatedChild != null) {
4384            activatedChild.makeInactive(false /* animate */);
4385        }
4386    }
4387
4388    public void userActivity() {
4389        if (mState == StatusBarState.KEYGUARD) {
4390            mKeyguardViewMediatorCallback.userActivity();
4391        }
4392    }
4393
4394    public boolean interceptMediaKey(KeyEvent event) {
4395        return mState == StatusBarState.KEYGUARD
4396                && mStatusBarKeyguardViewManager.interceptMediaKey(event);
4397    }
4398
4399    protected boolean shouldUnlockOnMenuPressed() {
4400        return mDeviceInteractive && mState != StatusBarState.SHADE
4401            && mStatusBarKeyguardViewManager.shouldDismissOnMenuPressed();
4402    }
4403
4404    public boolean onMenuPressed() {
4405        if (shouldUnlockOnMenuPressed()) {
4406            animateCollapsePanels(
4407                    CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
4408            return true;
4409        }
4410        return false;
4411    }
4412
4413    public void endAffordanceLaunch() {
4414        releaseGestureWakeLock();
4415        mNotificationPanel.onAffordanceLaunchEnded();
4416    }
4417
4418    public boolean onBackPressed() {
4419        if (mStatusBarKeyguardViewManager.onBackPressed()) {
4420            return true;
4421        }
4422        if (mNotificationPanel.isQsExpanded()) {
4423            if (mNotificationPanel.isQsDetailShowing()) {
4424                mNotificationPanel.closeQsDetail();
4425            } else {
4426                mNotificationPanel.animateCloseQs();
4427            }
4428            return true;
4429        }
4430        if (mState != StatusBarState.KEYGUARD && mState != StatusBarState.SHADE_LOCKED) {
4431            animateCollapsePanels();
4432            return true;
4433        }
4434        if (mKeyguardUserSwitcher.hideIfNotSimple(true)) {
4435            return true;
4436        }
4437        return false;
4438    }
4439
4440    public boolean onSpacePressed() {
4441        if (mDeviceInteractive && mState != StatusBarState.SHADE) {
4442            animateCollapsePanels(
4443                    CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
4444            return true;
4445        }
4446        return false;
4447    }
4448
4449    private void showBouncerIfKeyguard() {
4450        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4451            showBouncer();
4452        }
4453    }
4454
4455    protected void showBouncer() {
4456        mWaitingForKeyguardExit = mStatusBarKeyguardViewManager.isShowing();
4457        mStatusBarKeyguardViewManager.dismiss();
4458    }
4459
4460    private void instantExpandNotificationsPanel() {
4461
4462        // Make our window larger and the panel expanded.
4463        makeExpandedVisible(true);
4464        mNotificationPanel.expand(false /* animate */);
4465    }
4466
4467    private void instantCollapseNotificationPanel() {
4468        mNotificationPanel.instantCollapse();
4469    }
4470
4471    @Override
4472    public void onActivated(ActivatableNotificationView view) {
4473        mLockscreenGestureLogger.write(
4474                MetricsEvent.ACTION_LS_NOTE,
4475                0 /* lengthDp - N/A */, 0 /* velocityDp - N/A */);
4476        mKeyguardIndicationController.showTransientIndication(R.string.notification_tap_again);
4477        ActivatableNotificationView previousView = mStackScroller.getActivatedChild();
4478        if (previousView != null) {
4479            previousView.makeInactive(true /* animate */);
4480        }
4481        mStackScroller.setActivatedChild(view);
4482    }
4483
4484    /**
4485     * @param state The {@link StatusBarState} to set.
4486     */
4487    public void setBarState(int state) {
4488        // If we're visible and switched to SHADE_LOCKED (the user dragged
4489        // down on the lockscreen), clear notification LED, vibration,
4490        // ringing.
4491        // Other transitions are covered in handleVisibleToUserChanged().
4492        if (state != mState && mVisible && (state == StatusBarState.SHADE_LOCKED
4493                || (state == StatusBarState.SHADE && isGoingToNotificationShade()))) {
4494            clearNotificationEffects();
4495        }
4496        if (state == StatusBarState.KEYGUARD) {
4497            removeRemoteInputEntriesKeptUntilCollapsed();
4498            maybeEscalateHeadsUp();
4499        }
4500        mState = state;
4501        mGroupManager.setStatusBarState(state);
4502        mHeadsUpManager.setStatusBarState(state);
4503        mFalsingManager.setStatusBarState(state);
4504        mStatusBarWindowManager.setStatusBarState(state);
4505        mStackScroller.setStatusBarState(state);
4506        updateReportRejectedTouchVisibility();
4507        updateDozing();
4508        mNotificationShelf.setStatusBarState(state);
4509    }
4510
4511    @Override
4512    public void onActivationReset(ActivatableNotificationView view) {
4513        if (view == mStackScroller.getActivatedChild()) {
4514            mKeyguardIndicationController.hideTransientIndication();
4515            mStackScroller.setActivatedChild(null);
4516        }
4517    }
4518
4519    public void onTrackingStarted() {
4520        runPostCollapseRunnables();
4521    }
4522
4523    public void onClosingFinished() {
4524        runPostCollapseRunnables();
4525        if (!isPanelFullyCollapsed()) {
4526            // if we set it not to be focusable when collapsing, we have to undo it when we aborted
4527            // the closing
4528            mStatusBarWindowManager.setStatusBarFocusable(true);
4529        }
4530    }
4531
4532    public void onUnlockHintStarted() {
4533        mFalsingManager.onUnlockHintStarted();
4534        mKeyguardIndicationController.showTransientIndication(R.string.keyguard_unlock);
4535    }
4536
4537    public void onHintFinished() {
4538        // Delay the reset a bit so the user can read the text.
4539        mKeyguardIndicationController.hideTransientIndicationDelayed(HINT_RESET_DELAY_MS);
4540    }
4541
4542    public void onCameraHintStarted() {
4543        mFalsingManager.onCameraHintStarted();
4544        mKeyguardIndicationController.showTransientIndication(R.string.camera_hint);
4545    }
4546
4547    public void onVoiceAssistHintStarted() {
4548        mFalsingManager.onLeftAffordanceHintStarted();
4549        mKeyguardIndicationController.showTransientIndication(R.string.voice_hint);
4550    }
4551
4552    public void onPhoneHintStarted() {
4553        mFalsingManager.onLeftAffordanceHintStarted();
4554        mKeyguardIndicationController.showTransientIndication(R.string.phone_hint);
4555    }
4556
4557    public void onTrackingStopped(boolean expand) {
4558        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
4559            if (!expand && !mUnlockMethodCache.canSkipBouncer()) {
4560                showBouncerIfKeyguard();
4561            }
4562        }
4563    }
4564
4565    protected int getMaxKeyguardNotifications(boolean recompute) {
4566        if (recompute) {
4567            mMaxKeyguardNotifications = Math.max(1,
4568                    mNotificationPanel.computeMaxKeyguardNotifications(
4569                            mMaxAllowedKeyguardNotifications));
4570            return mMaxKeyguardNotifications;
4571        }
4572        return mMaxKeyguardNotifications;
4573    }
4574
4575    public int getMaxKeyguardNotifications() {
4576        return getMaxKeyguardNotifications(false /* recompute */);
4577    }
4578
4579    // TODO: Figure out way to remove this.
4580    public NavigationBarView getNavigationBarView() {
4581        return (NavigationBarView) mNavigationBar.getView();
4582    }
4583
4584    // ---------------------- DragDownHelper.OnDragDownListener ------------------------------------
4585
4586
4587    /* Only ever called as a consequence of a lockscreen expansion gesture. */
4588    @Override
4589    public boolean onDraggedDown(View startingChild, int dragLengthY) {
4590        if (hasActiveNotifications() && (!isDozing() || isPulsing())) {
4591            mLockscreenGestureLogger.write(
4592                    MetricsEvent.ACTION_LS_SHADE,
4593                    (int) (dragLengthY / mDisplayMetrics.density),
4594                    0 /* velocityDp - N/A */);
4595
4596            // We have notifications, go to locked shade.
4597            goToLockedShade(startingChild);
4598            if (startingChild instanceof ExpandableNotificationRow) {
4599                ExpandableNotificationRow row = (ExpandableNotificationRow) startingChild;
4600                row.onExpandedByGesture(true /* drag down is always an open */);
4601            }
4602            return true;
4603        } else {
4604            // abort gesture.
4605            return false;
4606        }
4607    }
4608
4609    @Override
4610    public void onDragDownReset() {
4611        mStackScroller.setDimmed(true /* dimmed */, true /* animated */);
4612        mStackScroller.resetScrollPosition();
4613    }
4614
4615    @Override
4616    public void onCrossedThreshold(boolean above) {
4617        mStackScroller.setDimmed(!above /* dimmed */, true /* animate */);
4618    }
4619
4620    @Override
4621    public void onTouchSlopExceeded() {
4622        mStackScroller.removeLongPressCallback();
4623    }
4624
4625    @Override
4626    public void setEmptyDragAmount(float amount) {
4627        mNotificationPanel.setEmptyDragAmount(amount);
4628    }
4629
4630    /**
4631     * If secure with redaction: Show bouncer, go to unlocked shade.
4632     *
4633     * <p>If secure without redaction or no security: Go to {@link StatusBarState#SHADE_LOCKED}.</p>
4634     *
4635     * @param expandView The view to expand after going to the shade.
4636     */
4637    public void goToLockedShade(View expandView) {
4638        int userId = mCurrentUserId;
4639        ExpandableNotificationRow row = null;
4640        if (expandView instanceof ExpandableNotificationRow) {
4641            row = (ExpandableNotificationRow) expandView;
4642            row.setUserExpanded(true /* userExpanded */, true /* allowChildExpansion */);
4643            // Indicate that the group expansion is changing at this time -- this way the group
4644            // and children backgrounds / divider animations will look correct.
4645            row.setGroupExpansionChanging(true);
4646            if (row.getStatusBarNotification() != null) {
4647                userId = row.getStatusBarNotification().getUserId();
4648            }
4649        }
4650        boolean fullShadeNeedsBouncer = !userAllowsPrivateNotificationsInPublic(mCurrentUserId)
4651                || !mShowLockscreenNotifications || mFalsingManager.shouldEnforceBouncer();
4652        if (isLockscreenPublicMode(userId) && fullShadeNeedsBouncer) {
4653            mLeaveOpenOnKeyguardHide = true;
4654            showBouncerIfKeyguard();
4655            mDraggedDownRow = row;
4656            mPendingRemoteInputView = null;
4657        } else {
4658            mNotificationPanel.animateToFullShade(0 /* delay */);
4659            setBarState(StatusBarState.SHADE_LOCKED);
4660            updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
4661        }
4662    }
4663
4664    public void onLockedNotificationImportanceChange(OnDismissAction dismissAction) {
4665        mLeaveOpenOnKeyguardHide = true;
4666        dismissKeyguardThenExecute(dismissAction, true /* afterKeyguardGone */);
4667    }
4668
4669    protected void onLockedRemoteInput(ExpandableNotificationRow row, View clicked) {
4670        mLeaveOpenOnKeyguardHide = true;
4671        showBouncer();
4672        mPendingRemoteInputView = clicked;
4673    }
4674
4675    protected void onMakeExpandedVisibleForRemoteInput(ExpandableNotificationRow row,
4676            View clickedView) {
4677        if (isKeyguardShowing()) {
4678            onLockedRemoteInput(row, clickedView);
4679        } else {
4680            row.setUserExpanded(true);
4681            row.getPrivateLayout().setOnExpandedVisibleListener(clickedView::performClick);
4682        }
4683    }
4684
4685    protected boolean startWorkChallengeIfNecessary(int userId, IntentSender intendSender,
4686            String notificationKey) {
4687        // Clear pending remote view, as we do not want to trigger pending remote input view when
4688        // it's called by other code
4689        mPendingWorkRemoteInputView = null;
4690        // Begin old BaseStatusBar.startWorkChallengeIfNecessary.
4691        final Intent newIntent = mKeyguardManager.createConfirmDeviceCredentialIntent(null,
4692                null, userId);
4693        if (newIntent == null) {
4694            return false;
4695        }
4696        final Intent callBackIntent = new Intent(NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION);
4697        callBackIntent.putExtra(Intent.EXTRA_INTENT, intendSender);
4698        callBackIntent.putExtra(Intent.EXTRA_INDEX, notificationKey);
4699        callBackIntent.setPackage(mContext.getPackageName());
4700
4701        PendingIntent callBackPendingIntent = PendingIntent.getBroadcast(
4702                mContext,
4703                0,
4704                callBackIntent,
4705                PendingIntent.FLAG_CANCEL_CURRENT |
4706                        PendingIntent.FLAG_ONE_SHOT |
4707                        PendingIntent.FLAG_IMMUTABLE);
4708        newIntent.putExtra(
4709                Intent.EXTRA_INTENT,
4710                callBackPendingIntent.getIntentSender());
4711        try {
4712            ActivityManager.getService().startConfirmDeviceCredentialIntent(newIntent,
4713                    null /*options*/);
4714        } catch (RemoteException ex) {
4715            // ignore
4716        }
4717        return true;
4718        // End old BaseStatusBar.startWorkChallengeIfNecessary.
4719    }
4720
4721    protected void onLockedWorkRemoteInput(int userId, ExpandableNotificationRow row,
4722            View clicked) {
4723        // Collapse notification and show work challenge
4724        animateCollapsePanels();
4725        startWorkChallengeIfNecessary(userId, null, null);
4726        // Add pending remote input view after starting work challenge, as starting work challenge
4727        // will clear all previous pending review view
4728        mPendingWorkRemoteInputView = clicked;
4729    }
4730
4731    private boolean isAnyProfilePublicMode() {
4732        for (int i = mCurrentProfiles.size() - 1; i >= 0; i--) {
4733            if (isLockscreenPublicMode(mCurrentProfiles.valueAt(i).id)) {
4734                return true;
4735            }
4736        }
4737        return false;
4738    }
4739
4740    protected void onWorkChallengeChanged() {
4741        updatePublicMode();
4742        updateNotifications();
4743        if (mPendingWorkRemoteInputView != null && !isAnyProfilePublicMode()) {
4744            // Expand notification panel and the notification row, then click on remote input view
4745            final Runnable clickPendingViewRunnable = new Runnable() {
4746                @Override
4747                public void run() {
4748                    final View pendingWorkRemoteInputView = mPendingWorkRemoteInputView;
4749                    if (pendingWorkRemoteInputView == null) {
4750                        return;
4751                    }
4752
4753                    // Climb up the hierarchy until we get to the container for this row.
4754                    ViewParent p = pendingWorkRemoteInputView.getParent();
4755                    while (!(p instanceof ExpandableNotificationRow)) {
4756                        if (p == null) {
4757                            return;
4758                        }
4759                        p = p.getParent();
4760                    }
4761
4762                    final ExpandableNotificationRow row = (ExpandableNotificationRow) p;
4763                    ViewParent viewParent = row.getParent();
4764                    if (viewParent instanceof NotificationStackScrollLayout) {
4765                        final NotificationStackScrollLayout scrollLayout =
4766                                (NotificationStackScrollLayout) viewParent;
4767                        row.makeActionsVisibile();
4768                        row.post(new Runnable() {
4769                            @Override
4770                            public void run() {
4771                                final Runnable finishScrollingCallback = new Runnable() {
4772                                    @Override
4773                                    public void run() {
4774                                        mPendingWorkRemoteInputView.callOnClick();
4775                                        mPendingWorkRemoteInputView = null;
4776                                        scrollLayout.setFinishScrollingCallback(null);
4777                                    }
4778                                };
4779                                if (scrollLayout.scrollTo(row)) {
4780                                    // It scrolls! So call it when it's finished.
4781                                    scrollLayout.setFinishScrollingCallback(
4782                                            finishScrollingCallback);
4783                                } else {
4784                                    // It does not scroll, so call it now!
4785                                    finishScrollingCallback.run();
4786                                }
4787                            }
4788                        });
4789                    }
4790                }
4791            };
4792            mNotificationPanel.getViewTreeObserver().addOnGlobalLayoutListener(
4793                    new ViewTreeObserver.OnGlobalLayoutListener() {
4794                        @Override
4795                        public void onGlobalLayout() {
4796                            if (mNotificationPanel.mStatusBar.getStatusBarWindow()
4797                                    .getHeight() != mNotificationPanel.mStatusBar
4798                                            .getStatusBarHeight()) {
4799                                mNotificationPanel.getViewTreeObserver()
4800                                        .removeOnGlobalLayoutListener(this);
4801                                mNotificationPanel.post(clickPendingViewRunnable);
4802                            }
4803                        }
4804                    });
4805            instantExpandNotificationsPanel();
4806        }
4807    }
4808
4809    @Override
4810    public void onExpandClicked(Entry clickedEntry, boolean nowExpanded) {
4811        mHeadsUpManager.setExpanded(clickedEntry, nowExpanded);
4812        if (mState == StatusBarState.KEYGUARD && nowExpanded) {
4813            goToLockedShade(clickedEntry.row);
4814        }
4815    }
4816
4817    /**
4818     * Goes back to the keyguard after hanging around in {@link StatusBarState#SHADE_LOCKED}.
4819     */
4820    public void goToKeyguard() {
4821        if (mState == StatusBarState.SHADE_LOCKED) {
4822            mStackScroller.onGoToKeyguard();
4823            setBarState(StatusBarState.KEYGUARD);
4824            updateKeyguardState(false /* goingToFullShade */, true /* fromShadeLocked*/);
4825        }
4826    }
4827
4828    public long getKeyguardFadingAwayDelay() {
4829        return mKeyguardFadingAwayDelay;
4830    }
4831
4832    public long getKeyguardFadingAwayDuration() {
4833        return mKeyguardFadingAwayDuration;
4834    }
4835
4836    public void setBouncerShowing(boolean bouncerShowing) {
4837        mBouncerShowing = bouncerShowing;
4838        mStatusBarView.setBouncerShowing(bouncerShowing);
4839        recomputeDisableFlags(true /* animate */);
4840    }
4841
4842    public void onStartedGoingToSleep() {
4843        mStartedGoingToSleep = true;
4844    }
4845
4846    public void onFinishedGoingToSleep() {
4847        mNotificationPanel.onAffordanceLaunchEnded();
4848        releaseGestureWakeLock();
4849        mLaunchCameraOnScreenTurningOn = false;
4850        mStartedGoingToSleep = false;
4851        mDeviceInteractive = false;
4852        mWakeUpComingFromTouch = false;
4853        mWakeUpTouchLocation = null;
4854        mStackScroller.setAnimationsEnabled(false);
4855        mVisualStabilityManager.setScreenOn(false);
4856        updateVisibleToUser();
4857
4858        // We need to disable touch events because these might
4859        // collapse the panel after we expanded it, and thus we would end up with a blank
4860        // Keyguard.
4861        mNotificationPanel.setTouchDisabled(true);
4862        mStatusBarWindow.cancelCurrentTouch();
4863        if (mLaunchCameraOnFinishedGoingToSleep) {
4864            mLaunchCameraOnFinishedGoingToSleep = false;
4865
4866            // This gets executed before we will show Keyguard, so post it in order that the state
4867            // is correct.
4868            mHandler.post(new Runnable() {
4869                @Override
4870                public void run() {
4871                    onCameraLaunchGestureDetected(mLastCameraLaunchSource);
4872                }
4873            });
4874        }
4875    }
4876
4877    public void onStartedWakingUp() {
4878        mDeviceInteractive = true;
4879        mStackScroller.setAnimationsEnabled(true);
4880        mVisualStabilityManager.setScreenOn(true);
4881        mNotificationPanel.setTouchDisabled(false);
4882        updateVisibleToUser();
4883    }
4884
4885    public void onScreenTurningOn() {
4886        mScreenTurningOn = true;
4887        mFalsingManager.onScreenTurningOn();
4888        mNotificationPanel.onScreenTurningOn();
4889        if (mLaunchCameraOnScreenTurningOn) {
4890            mNotificationPanel.launchCamera(false, mLastCameraLaunchSource);
4891            mLaunchCameraOnScreenTurningOn = false;
4892        }
4893    }
4894
4895    private void vibrateForCameraGesture() {
4896        // Make sure to pass -1 for repeat so VibratorService doesn't stop us when going to sleep.
4897        mVibrator.vibrate(mCameraLaunchGestureVibePattern, -1 /* repeat */);
4898    }
4899
4900    public void onScreenTurnedOn() {
4901        mScreenTurningOn = false;
4902        mDozeScrimController.onScreenTurnedOn();
4903    }
4904
4905    @Override
4906    public void showScreenPinningRequest(int taskId) {
4907        if (mKeyguardMonitor.isShowing()) {
4908            // Don't allow apps to trigger this from keyguard.
4909            return;
4910        }
4911        // Show screen pinning request, since this comes from an app, show 'no thanks', button.
4912        showScreenPinningRequest(taskId, true);
4913    }
4914
4915    public void showScreenPinningRequest(int taskId, boolean allowCancel) {
4916        mScreenPinningRequest.showPrompt(taskId, allowCancel);
4917    }
4918
4919    public boolean hasActiveNotifications() {
4920        return !mNotificationData.getActiveNotifications().isEmpty();
4921    }
4922
4923    public void wakeUpIfDozing(long time, View where) {
4924        if (mDozing) {
4925            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
4926            pm.wakeUp(time, "com.android.systemui:NODOZE");
4927            mWakeUpComingFromTouch = true;
4928            where.getLocationInWindow(mTmpInt2);
4929            mWakeUpTouchLocation = new PointF(mTmpInt2[0] + where.getWidth() / 2,
4930                    mTmpInt2[1] + where.getHeight() / 2);
4931            mNotificationPanel.setTouchDisabled(false);
4932            mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
4933            mFalsingManager.onScreenOnFromTouch();
4934        }
4935    }
4936
4937    @Override
4938    public void appTransitionCancelled() {
4939        EventBus.getDefault().send(new AppTransitionFinishedEvent());
4940    }
4941
4942    @Override
4943    public void appTransitionFinished() {
4944        EventBus.getDefault().send(new AppTransitionFinishedEvent());
4945    }
4946
4947    @Override
4948    public void onCameraLaunchGestureDetected(int source) {
4949        mLastCameraLaunchSource = source;
4950        if (mStartedGoingToSleep) {
4951            mLaunchCameraOnFinishedGoingToSleep = true;
4952            return;
4953        }
4954        if (!mNotificationPanel.canCameraGestureBeLaunched(
4955                mStatusBarKeyguardViewManager.isShowing() && mExpandedVisible)) {
4956            return;
4957        }
4958        if (!mDeviceInteractive) {
4959            PowerManager pm = mContext.getSystemService(PowerManager.class);
4960            pm.wakeUp(SystemClock.uptimeMillis(), "com.android.systemui:CAMERA_GESTURE");
4961            mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
4962        }
4963        vibrateForCameraGesture();
4964        if (!mStatusBarKeyguardViewManager.isShowing()) {
4965            startActivity(KeyguardBottomAreaView.INSECURE_CAMERA_INTENT,
4966                    true /* dismissShade */);
4967        } else {
4968            if (!mDeviceInteractive) {
4969                // Avoid flickering of the scrim when we instant launch the camera and the bouncer
4970                // comes on.
4971                mScrimController.dontAnimateBouncerChangesUntilNextFrame();
4972                mGestureWakeLock.acquire(LAUNCH_TRANSITION_TIMEOUT_MS + 1000L);
4973            }
4974            if (mScreenTurningOn || mStatusBarKeyguardViewManager.isScreenTurnedOn()) {
4975                mNotificationPanel.launchCamera(mDeviceInteractive /* animate */, source);
4976            } else {
4977                // We need to defer the camera launch until the screen comes on, since otherwise
4978                // we will dismiss us too early since we are waiting on an activity to be drawn and
4979                // incorrectly get notified because of the screen on event (which resumes and pauses
4980                // some activities)
4981                mLaunchCameraOnScreenTurningOn = true;
4982            }
4983        }
4984    }
4985
4986    public void notifyFpAuthModeChanged() {
4987        updateDozing();
4988    }
4989
4990    private void updateDozing() {
4991        Trace.beginSection("StatusBar#updateDozing");
4992        // When in wake-and-unlock while pulsing, keep dozing state until fully unlocked.
4993        mDozing = mDozingRequested && mState == StatusBarState.KEYGUARD
4994                || mFingerprintUnlockController.getMode()
4995                        == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING;
4996        mStatusBarWindowManager.setDozing(mDozing);
4997        updateDozingState();
4998        Trace.endSection();
4999    }
5000
5001    public boolean isKeyguardShowing() {
5002        return mStatusBarKeyguardViewManager.isShowing();
5003    }
5004
5005    private final class DozeServiceHost implements DozeHost {
5006        private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
5007
5008        @Override
5009        public String toString() {
5010            return "PSB.DozeServiceHost[mCallbacks=" + mCallbacks.size() + "]";
5011        }
5012
5013        public void firePowerSaveChanged(boolean active) {
5014            for (Callback callback : mCallbacks) {
5015                callback.onPowerSaveChanged(active);
5016            }
5017        }
5018
5019        public void fireNotificationHeadsUp() {
5020            for (Callback callback : mCallbacks) {
5021                callback.onNotificationHeadsUp();
5022            }
5023        }
5024
5025        @Override
5026        public void addCallback(@NonNull Callback callback) {
5027            mCallbacks.add(callback);
5028        }
5029
5030        @Override
5031        public void removeCallback(@NonNull Callback callback) {
5032            mCallbacks.remove(callback);
5033        }
5034
5035        @Override
5036        public void startDozing() {
5037            if (!mDozingRequested) {
5038                mDozingRequested = true;
5039                DozeLog.traceDozing(mContext, mDozing);
5040                updateDozing();
5041            }
5042        }
5043
5044        @Override
5045        public void pulseWhileDozing(@NonNull PulseCallback callback, int reason) {
5046            mDozeScrimController.pulse(new PulseCallback() {
5047
5048                @Override
5049                public void onPulseStarted() {
5050                    callback.onPulseStarted();
5051                    Collection<HeadsUpManager.HeadsUpEntry> pulsingEntries =
5052                            mHeadsUpManager.getAllEntries();
5053                    if (!pulsingEntries.isEmpty()) {
5054                        // Only pulse the stack scroller if there's actually something to show.
5055                        // Otherwise just show the always-on screen.
5056                        setPulsing(pulsingEntries);
5057                    }
5058                }
5059
5060                @Override
5061                public void onPulseFinished() {
5062                    callback.onPulseFinished();
5063                    setPulsing(null);
5064                }
5065
5066                private void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> pulsing) {
5067                    mStackScroller.setPulsing(pulsing);
5068                    mNotificationPanel.setPulsing(pulsing != null);
5069                    mVisualStabilityManager.setPulsing(pulsing != null);
5070                }
5071            }, reason);
5072        }
5073
5074        @Override
5075        public void stopDozing() {
5076            if (mDozingRequested) {
5077                mDozingRequested = false;
5078                DozeLog.traceDozing(mContext, mDozing);
5079                updateDozing();
5080            }
5081        }
5082
5083        @Override
5084        public void dozeTimeTick() {
5085            mKeyguardStatusView.refreshTime();
5086        }
5087
5088        @Override
5089        public boolean isPowerSaveActive() {
5090            return mBatteryController.isPowerSave();
5091        }
5092
5093        @Override
5094        public boolean isPulsingBlocked() {
5095            return mFingerprintUnlockController.getMode()
5096                    == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK;
5097        }
5098
5099        @Override
5100        public void startPendingIntentDismissingKeyguard(PendingIntent intent) {
5101            StatusBar.this.startPendingIntentDismissingKeyguard(intent);
5102        }
5103
5104        @Override
5105        public void abortPulsing() {
5106            mDozeScrimController.abortPulsing();
5107        }
5108
5109        @Override
5110        public void extendPulse() {
5111            mDozeScrimController.extendPulse();
5112        }
5113
5114    }
5115
5116    // Begin Extra BaseStatusBar methods.
5117
5118    protected CommandQueue mCommandQueue;
5119    protected IStatusBarService mBarService;
5120
5121    // all notifications
5122    protected NotificationData mNotificationData;
5123    protected NotificationStackScrollLayout mStackScroller;
5124
5125    protected NotificationGroupManager mGroupManager = new NotificationGroupManager();
5126
5127    protected RemoteInputController mRemoteInputController;
5128
5129    // for heads up notifications
5130    protected HeadsUpManager mHeadsUpManager;
5131
5132    // handling reordering
5133    protected VisualStabilityManager mVisualStabilityManager = new VisualStabilityManager();
5134
5135    protected int mCurrentUserId = 0;
5136    final protected SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
5137
5138    protected int mLayoutDirection = -1; // invalid
5139    protected AccessibilityManager mAccessibilityManager;
5140
5141    protected boolean mDeviceInteractive;
5142
5143    protected boolean mVisible;
5144    protected ArraySet<Entry> mHeadsUpEntriesToRemoveOnSwitch = new ArraySet<>();
5145    protected ArraySet<Entry> mRemoteInputEntriesToRemoveOnCollapse = new ArraySet<>();
5146
5147    /**
5148     * Notifications with keys in this set are not actually around anymore. We kept them around
5149     * when they were canceled in response to a remote input interaction. This allows us to show
5150     * what you replied and allows you to continue typing into it.
5151     */
5152    protected ArraySet<String> mKeysKeptForRemoteInput = new ArraySet<>();
5153
5154    // mScreenOnFromKeyguard && mVisible.
5155    private boolean mVisibleToUser;
5156
5157    private Locale mLocale;
5158
5159    protected boolean mUseHeadsUp = false;
5160    protected boolean mHeadsUpTicker = false;
5161    protected boolean mDisableNotificationAlerts = false;
5162
5163    protected DevicePolicyManager mDevicePolicyManager;
5164    protected IDreamManager mDreamManager;
5165    protected PowerManager mPowerManager;
5166    protected StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
5167
5168    // public mode, private notifications, etc
5169    private final SparseBooleanArray mLockscreenPublicMode = new SparseBooleanArray();
5170    private final SparseBooleanArray mUsersAllowingPrivateNotifications = new SparseBooleanArray();
5171    private final SparseBooleanArray mUsersAllowingNotifications = new SparseBooleanArray();
5172
5173    private UserManager mUserManager;
5174
5175    protected KeyguardManager mKeyguardManager;
5176    private LockPatternUtils mLockPatternUtils;
5177    private DeviceProvisionedController mDeviceProvisionedController;
5178
5179    // UI-specific methods
5180
5181    protected WindowManager mWindowManager;
5182    protected IWindowManager mWindowManagerService;
5183
5184    protected Display mDisplay;
5185
5186    protected RecentsComponent mRecents;
5187
5188    protected int mZenMode;
5189
5190    // which notification is currently being longpress-examined by the user
5191    private NotificationGuts mNotificationGutsExposed;
5192    private MenuItem mGutsMenuItem;
5193
5194    private KeyboardShortcuts mKeyboardShortcuts;
5195
5196    protected NotificationShelf mNotificationShelf;
5197    protected DismissView mDismissView;
5198    protected EmptyShadeView mEmptyShadeView;
5199
5200    private NotificationClicker mNotificationClicker = new NotificationClicker();
5201
5202    protected AssistManager mAssistManager;
5203
5204    protected boolean mVrMode;
5205
5206    private Set<String> mNonBlockablePkgs;
5207
5208    @Override  // NotificationData.Environment
5209    public boolean isDeviceProvisioned() {
5210        return mDeviceProvisionedController.isDeviceProvisioned();
5211    }
5212
5213    private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
5214        @Override
5215        public void onVrStateChanged(boolean enabled) {
5216            mVrMode = enabled;
5217        }
5218    };
5219
5220    public boolean isDeviceInVrMode() {
5221        return mVrMode;
5222    }
5223
5224    private final DeviceProvisionedListener mDeviceProvisionedListener =
5225            new DeviceProvisionedListener() {
5226        @Override
5227        public void onDeviceProvisionedChanged() {
5228            updateNotifications();
5229        }
5230    };
5231
5232    protected final ContentObserver mSettingsObserver = new ContentObserver(mHandler) {
5233        @Override
5234        public void onChange(boolean selfChange) {
5235            final int mode = Settings.Global.getInt(mContext.getContentResolver(),
5236                    Settings.Global.ZEN_MODE, Settings.Global.ZEN_MODE_OFF);
5237            setZenMode(mode);
5238
5239            updateLockscreenNotificationSetting();
5240        }
5241    };
5242
5243    private final ContentObserver mLockscreenSettingsObserver = new ContentObserver(mHandler) {
5244        @Override
5245        public void onChange(boolean selfChange) {
5246            // We don't know which user changed LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS or
5247            // LOCK_SCREEN_SHOW_NOTIFICATIONS, so we just dump our cache ...
5248            mUsersAllowingPrivateNotifications.clear();
5249            mUsersAllowingNotifications.clear();
5250            // ... and refresh all the notifications
5251            updateLockscreenNotificationSetting();
5252            updateNotifications();
5253        }
5254    };
5255
5256    private RemoteViews.OnClickHandler mOnClickHandler = new RemoteViews.OnClickHandler() {
5257
5258        @Override
5259        public boolean onClickHandler(
5260                final View view, final PendingIntent pendingIntent, final Intent fillInIntent) {
5261            wakeUpIfDozing(SystemClock.uptimeMillis(), view);
5262
5263
5264            if (handleRemoteInput(view, pendingIntent, fillInIntent)) {
5265                return true;
5266            }
5267
5268            if (DEBUG) {
5269                Log.v(TAG, "Notification click handler invoked for intent: " + pendingIntent);
5270            }
5271            logActionClick(view);
5272            // The intent we are sending is for the application, which
5273            // won't have permission to immediately start an activity after
5274            // the user switches to home.  We know it is safe to do at this
5275            // point, so make sure new activity switches are now allowed.
5276            try {
5277                ActivityManager.getService().resumeAppSwitches();
5278            } catch (RemoteException e) {
5279            }
5280            final boolean isActivity = pendingIntent.isActivity();
5281            if (isActivity) {
5282                final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
5283                final boolean afterKeyguardGone = PreviewInflater.wouldLaunchResolverActivity(
5284                        mContext, pendingIntent.getIntent(), mCurrentUserId);
5285                dismissKeyguardThenExecute(new OnDismissAction() {
5286                    @Override
5287                    public boolean onDismiss() {
5288                        try {
5289                            ActivityManager.getService().resumeAppSwitches();
5290                        } catch (RemoteException e) {
5291                        }
5292
5293                        boolean handled = superOnClickHandler(view, pendingIntent, fillInIntent);
5294
5295                        // close the shade if it was open
5296                        if (handled) {
5297                            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
5298                                    true /* force */);
5299                            visibilityChanged(false);
5300                            mAssistManager.hideAssist();
5301                        }
5302
5303                        // Wait for activity start.
5304                        return handled;
5305                    }
5306                }, afterKeyguardGone);
5307                return true;
5308            } else {
5309                return superOnClickHandler(view, pendingIntent, fillInIntent);
5310            }
5311        }
5312
5313        private void logActionClick(View view) {
5314            ViewParent parent = view.getParent();
5315            String key = getNotificationKeyForParent(parent);
5316            if (key == null) {
5317                Log.w(TAG, "Couldn't determine notification for click.");
5318                return;
5319            }
5320            int index = -1;
5321            // If this is a default template, determine the index of the button.
5322            if (view.getId() == com.android.internal.R.id.action0 &&
5323                    parent != null && parent instanceof ViewGroup) {
5324                ViewGroup actionGroup = (ViewGroup) parent;
5325                index = actionGroup.indexOfChild(view);
5326            }
5327            try {
5328                mBarService.onNotificationActionClick(key, index);
5329            } catch (RemoteException e) {
5330                // Ignore
5331            }
5332        }
5333
5334        private String getNotificationKeyForParent(ViewParent parent) {
5335            while (parent != null) {
5336                if (parent instanceof ExpandableNotificationRow) {
5337                    return ((ExpandableNotificationRow) parent).getStatusBarNotification().getKey();
5338                }
5339                parent = parent.getParent();
5340            }
5341            return null;
5342        }
5343
5344        private boolean superOnClickHandler(View view, PendingIntent pendingIntent,
5345                Intent fillInIntent) {
5346            return super.onClickHandler(view, pendingIntent, fillInIntent,
5347                    StackId.FULLSCREEN_WORKSPACE_STACK_ID);
5348        }
5349
5350        private boolean handleRemoteInput(View view, PendingIntent pendingIntent, Intent fillInIntent) {
5351            Object tag = view.getTag(com.android.internal.R.id.remote_input_tag);
5352            RemoteInput[] inputs = null;
5353            if (tag instanceof RemoteInput[]) {
5354                inputs = (RemoteInput[]) tag;
5355            }
5356
5357            if (inputs == null) {
5358                return false;
5359            }
5360
5361            RemoteInput input = null;
5362
5363            for (RemoteInput i : inputs) {
5364                if (i.getAllowFreeFormInput()) {
5365                    input = i;
5366                }
5367            }
5368
5369            if (input == null) {
5370                return false;
5371            }
5372
5373            ViewParent p = view.getParent();
5374            RemoteInputView riv = null;
5375            while (p != null) {
5376                if (p instanceof View) {
5377                    View pv = (View) p;
5378                    if (pv.isRootNamespace()) {
5379                        riv = findRemoteInputView(pv);
5380                        break;
5381                    }
5382                }
5383                p = p.getParent();
5384            }
5385            ExpandableNotificationRow row = null;
5386            while (p != null) {
5387                if (p instanceof ExpandableNotificationRow) {
5388                    row = (ExpandableNotificationRow) p;
5389                    break;
5390                }
5391                p = p.getParent();
5392            }
5393
5394            if (row == null) {
5395                return false;
5396            }
5397
5398            row.setUserExpanded(true);
5399
5400            if (!mAllowLockscreenRemoteInput) {
5401                final int userId = pendingIntent.getCreatorUserHandle().getIdentifier();
5402                if (isLockscreenPublicMode(userId)) {
5403                    onLockedRemoteInput(row, view);
5404                    return true;
5405                }
5406                if (mUserManager.getUserInfo(userId).isManagedProfile()
5407                        && mKeyguardManager.isDeviceLocked(userId)) {
5408                    onLockedWorkRemoteInput(userId, row, view);
5409                    return true;
5410                }
5411            }
5412
5413            if (riv == null) {
5414                riv = findRemoteInputView(row.getPrivateLayout().getExpandedChild());
5415                if (riv == null) {
5416                    return false;
5417                }
5418                if (!row.getPrivateLayout().getExpandedChild().isShown()) {
5419                    onMakeExpandedVisibleForRemoteInput(row, view);
5420                    return true;
5421                }
5422            }
5423
5424            int width = view.getWidth();
5425            if (view instanceof TextView) {
5426                // Center the reveal on the text which might be off-center from the TextView
5427                TextView tv = (TextView) view;
5428                if (tv.getLayout() != null) {
5429                    int innerWidth = (int) tv.getLayout().getLineWidth(0);
5430                    innerWidth += tv.getCompoundPaddingLeft() + tv.getCompoundPaddingRight();
5431                    width = Math.min(width, innerWidth);
5432                }
5433            }
5434            int cx = view.getLeft() + width / 2;
5435            int cy = view.getTop() + view.getHeight() / 2;
5436            int w = riv.getWidth();
5437            int h = riv.getHeight();
5438            int r = Math.max(
5439                    Math.max(cx + cy, cx + (h - cy)),
5440                    Math.max((w - cx) + cy, (w - cx) + (h - cy)));
5441
5442            riv.setRevealParameters(cx, cy, r);
5443            riv.setPendingIntent(pendingIntent);
5444            riv.setRemoteInput(inputs, input);
5445            riv.focusAnimated();
5446
5447            return true;
5448        }
5449
5450        private RemoteInputView findRemoteInputView(View v) {
5451            if (v == null) {
5452                return null;
5453            }
5454            return (RemoteInputView) v.findViewWithTag(RemoteInputView.VIEW_TAG);
5455        }
5456    };
5457
5458    private final BroadcastReceiver mBaseBroadcastReceiver = new BroadcastReceiver() {
5459        @Override
5460        public void onReceive(Context context, Intent intent) {
5461            String action = intent.getAction();
5462            if (Intent.ACTION_USER_SWITCHED.equals(action)) {
5463                mCurrentUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
5464                updateCurrentProfilesCache();
5465                if (true) Log.v(TAG, "userId " + mCurrentUserId + " is in the house");
5466
5467                updateLockscreenNotificationSetting();
5468
5469                userSwitched(mCurrentUserId);
5470            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
5471                updateCurrentProfilesCache();
5472            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
5473                List<ActivityManager.RecentTaskInfo> recentTask = null;
5474                try {
5475                    recentTask = ActivityManager.getService().getRecentTasks(1,
5476                            ActivityManager.RECENT_WITH_EXCLUDED
5477                            | ActivityManager.RECENT_INCLUDE_PROFILES,
5478                            mCurrentUserId).getList();
5479                } catch (RemoteException e) {
5480                    // Abandon hope activity manager not running.
5481                }
5482                if (recentTask != null && recentTask.size() > 0) {
5483                    UserInfo user = mUserManager.getUserInfo(recentTask.get(0).userId);
5484                    if (user != null && user.isManagedProfile()) {
5485                        Toast toast = Toast.makeText(mContext,
5486                                R.string.managed_profile_foreground_toast,
5487                                Toast.LENGTH_SHORT);
5488                        TextView text = (TextView) toast.getView().findViewById(
5489                                android.R.id.message);
5490                        text.setCompoundDrawablesRelativeWithIntrinsicBounds(
5491                                R.drawable.stat_sys_managed_profile_status, 0, 0, 0);
5492                        int paddingPx = mContext.getResources().getDimensionPixelSize(
5493                                R.dimen.managed_profile_toast_padding);
5494                        text.setCompoundDrawablePadding(paddingPx);
5495                        toast.show();
5496                    }
5497                }
5498            } else if (BANNER_ACTION_CANCEL.equals(action) || BANNER_ACTION_SETUP.equals(action)) {
5499                NotificationManager noMan = (NotificationManager)
5500                        mContext.getSystemService(Context.NOTIFICATION_SERVICE);
5501                noMan.cancel(SystemMessage.NOTE_HIDDEN_NOTIFICATIONS);
5502
5503                Settings.Secure.putInt(mContext.getContentResolver(),
5504                        Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
5505                if (BANNER_ACTION_SETUP.equals(action)) {
5506                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
5507                            true /* force */);
5508                    mContext.startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_REDACTION)
5509                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
5510
5511                    );
5512                }
5513            } else if (NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION.equals(action)) {
5514                final IntentSender intentSender = intent.getParcelableExtra(Intent.EXTRA_INTENT);
5515                final String notificationKey = intent.getStringExtra(Intent.EXTRA_INDEX);
5516                if (intentSender != null) {
5517                    try {
5518                        mContext.startIntentSender(intentSender, null, 0, 0, 0);
5519                    } catch (IntentSender.SendIntentException e) {
5520                        /* ignore */
5521                    }
5522                }
5523                if (notificationKey != null) {
5524                    try {
5525                        mBarService.onNotificationClick(notificationKey);
5526                    } catch (RemoteException e) {
5527                        /* ignore */
5528                    }
5529                }
5530            }
5531        }
5532    };
5533
5534    private final BroadcastReceiver mAllUsersReceiver = new BroadcastReceiver() {
5535        @Override
5536        public void onReceive(Context context, Intent intent) {
5537            final String action = intent.getAction();
5538            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5539
5540            if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(action) &&
5541                    isCurrentProfile(getSendingUserId())) {
5542                mUsersAllowingPrivateNotifications.clear();
5543                updateLockscreenNotificationSetting();
5544                updateNotifications();
5545            } else if (Intent.ACTION_DEVICE_LOCKED_CHANGED.equals(action)) {
5546                if (userId != mCurrentUserId && isCurrentProfile(userId)) {
5547                    onWorkChallengeChanged();
5548                }
5549            }
5550        }
5551    };
5552
5553    private final NotificationListenerService mNotificationListener =
5554            new NotificationListenerService() {
5555        @Override
5556        public void onListenerConnected() {
5557            if (DEBUG) Log.d(TAG, "onListenerConnected");
5558            final StatusBarNotification[] notifications = getActiveNotifications();
5559            if (notifications == null) {
5560                Log.w(TAG, "onListenerConnected unable to get active notifications.");
5561                return;
5562            }
5563            final RankingMap currentRanking = getCurrentRanking();
5564            mHandler.post(new Runnable() {
5565                @Override
5566                public void run() {
5567                    for (StatusBarNotification sbn : notifications) {
5568                        try {
5569                            addNotification(sbn, currentRanking);
5570                        } catch (InflationException e) {
5571                            handleInflationException(sbn, e);
5572                        }
5573                    }
5574                }
5575            });
5576        }
5577
5578        @Override
5579        public void onNotificationPosted(final StatusBarNotification sbn,
5580                final RankingMap rankingMap) {
5581            if (DEBUG) Log.d(TAG, "onNotificationPosted: " + sbn);
5582            if (sbn != null) {
5583                mHandler.post(new Runnable() {
5584                    @Override
5585                    public void run() {
5586                        processForRemoteInput(sbn.getNotification());
5587                        String key = sbn.getKey();
5588                        mKeysKeptForRemoteInput.remove(key);
5589                        boolean isUpdate = mNotificationData.get(key) != null;
5590                        // In case we don't allow child notifications, we ignore children of
5591                        // notifications that have a summary, since we're not going to show them
5592                        // anyway. This is true also when the summary is canceled,
5593                        // because children are automatically canceled by NoMan in that case.
5594                        if (!ENABLE_CHILD_NOTIFICATIONS
5595                            && mGroupManager.isChildInGroupWithSummary(sbn)) {
5596                            if (DEBUG) {
5597                                Log.d(TAG, "Ignoring group child due to existing summary: " + sbn);
5598                            }
5599
5600                            // Remove existing notification to avoid stale data.
5601                            if (isUpdate) {
5602                                removeNotification(key, rankingMap);
5603                            } else {
5604                                mNotificationData.updateRanking(rankingMap);
5605                            }
5606                            return;
5607                        }
5608                        try {
5609                            if (isUpdate) {
5610                                updateNotification(sbn, rankingMap);
5611                            } else {
5612                                addNotification(sbn, rankingMap);
5613                            }
5614                        } catch (InflationException e) {
5615                            handleInflationException(sbn, e);
5616                        }
5617                    }
5618                });
5619            }
5620        }
5621
5622        @Override
5623        public void onNotificationRemoved(StatusBarNotification sbn,
5624                final RankingMap rankingMap) {
5625            if (DEBUG) Log.d(TAG, "onNotificationRemoved: " + sbn);
5626            if (sbn != null) {
5627                final String key = sbn.getKey();
5628                mHandler.post(new Runnable() {
5629                    @Override
5630                    public void run() {
5631                        removeNotification(key, rankingMap);
5632                    }
5633                });
5634            }
5635        }
5636
5637        @Override
5638        public void onNotificationRankingUpdate(final RankingMap rankingMap) {
5639            if (DEBUG) Log.d(TAG, "onRankingUpdate");
5640            if (rankingMap != null) {
5641            mHandler.post(new Runnable() {
5642                @Override
5643                public void run() {
5644                    updateNotificationRanking(rankingMap);
5645                }
5646            });
5647        }                            }
5648
5649    };
5650
5651    private void updateCurrentProfilesCache() {
5652        synchronized (mCurrentProfiles) {
5653            mCurrentProfiles.clear();
5654            if (mUserManager != null) {
5655                for (UserInfo user : mUserManager.getProfiles(mCurrentUserId)) {
5656                    mCurrentProfiles.put(user.id, user);
5657                }
5658            }
5659        }
5660    }
5661
5662    protected void notifyUserAboutHiddenNotifications() {
5663        if (0 != Settings.Secure.getInt(mContext.getContentResolver(),
5664                Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 1)) {
5665            Log.d(TAG, "user hasn't seen notification about hidden notifications");
5666            if (!mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
5667                Log.d(TAG, "insecure lockscreen, skipping notification");
5668                Settings.Secure.putInt(mContext.getContentResolver(),
5669                        Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
5670                return;
5671            }
5672            Log.d(TAG, "disabling lockecreen notifications and alerting the user");
5673            // disable lockscreen notifications until user acts on the banner.
5674            Settings.Secure.putInt(mContext.getContentResolver(),
5675                    Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0);
5676            Settings.Secure.putInt(mContext.getContentResolver(),
5677                    Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0);
5678
5679            final String packageName = mContext.getPackageName();
5680            PendingIntent cancelIntent = PendingIntent.getBroadcast(mContext, 0,
5681                    new Intent(BANNER_ACTION_CANCEL).setPackage(packageName),
5682                    PendingIntent.FLAG_CANCEL_CURRENT);
5683            PendingIntent setupIntent = PendingIntent.getBroadcast(mContext, 0,
5684                    new Intent(BANNER_ACTION_SETUP).setPackage(packageName),
5685                    PendingIntent.FLAG_CANCEL_CURRENT);
5686
5687            final int colorRes = com.android.internal.R.color.system_notification_accent_color;
5688            Notification.Builder note =
5689                    new Notification.Builder(mContext, NotificationChannels.GENERAL)
5690                            .setSmallIcon(R.drawable.ic_android)
5691                            .setContentTitle(mContext.getString(
5692                                    R.string.hidden_notifications_title))
5693                            .setContentText(mContext.getString(R.string.hidden_notifications_text))
5694                            .setOngoing(true)
5695                            .setColor(mContext.getColor(colorRes))
5696                            .setContentIntent(setupIntent)
5697                            .addAction(R.drawable.ic_close,
5698                                    mContext.getString(R.string.hidden_notifications_cancel),
5699                                    cancelIntent)
5700                            .addAction(R.drawable.ic_settings,
5701                                    mContext.getString(R.string.hidden_notifications_setup),
5702                                    setupIntent);
5703            overrideNotificationAppName(mContext, note);
5704
5705            NotificationManager noMan =
5706                    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
5707            noMan.notify(SystemMessage.NOTE_HIDDEN_NOTIFICATIONS, note.build());
5708        }
5709    }
5710
5711    @Override  // NotificationData.Environment
5712    public boolean isNotificationForCurrentProfiles(StatusBarNotification n) {
5713        final int thisUserId = mCurrentUserId;
5714        final int notificationUserId = n.getUserId();
5715        if (DEBUG && MULTIUSER_DEBUG) {
5716            Log.v(TAG, String.format("%s: current userid: %d, notification userid: %d",
5717                    n, thisUserId, notificationUserId));
5718        }
5719        return isCurrentProfile(notificationUserId);
5720    }
5721
5722    protected void setNotificationShown(StatusBarNotification n) {
5723        setNotificationsShown(new String[]{n.getKey()});
5724    }
5725
5726    protected void setNotificationsShown(String[] keys) {
5727        try {
5728            mNotificationListener.setNotificationsShown(keys);
5729        } catch (RuntimeException e) {
5730            Log.d(TAG, "failed setNotificationsShown: ", e);
5731        }
5732    }
5733
5734    protected boolean isCurrentProfile(int userId) {
5735        synchronized (mCurrentProfiles) {
5736            return userId == UserHandle.USER_ALL || mCurrentProfiles.get(userId) != null;
5737        }
5738    }
5739
5740    @Override
5741    public NotificationGroupManager getGroupManager() {
5742        return mGroupManager;
5743    }
5744
5745    public boolean isMediaNotification(NotificationData.Entry entry) {
5746        // TODO: confirm that there's a valid media key
5747        return entry.getExpandedContentView() != null &&
5748               entry.getExpandedContentView()
5749                       .findViewById(com.android.internal.R.id.media_actions) != null;
5750    }
5751
5752    // The button in the guts that links to the system notification settings for that app
5753    private void startAppNotificationSettingsActivity(String packageName, final int appUid,
5754            final NotificationChannel channel) {
5755        final Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
5756        intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);
5757        intent.putExtra(Settings.EXTRA_APP_UID, appUid);
5758        if (channel != null) {
5759            intent.putExtra(EXTRA_FRAGMENT_ARG_KEY, channel.getId());
5760        }
5761        startNotificationGutsIntent(intent, appUid);
5762    }
5763
5764    private void startNotificationGutsIntent(final Intent intent, final int appUid) {
5765        dismissKeyguardThenExecute(new OnDismissAction() {
5766            @Override
5767            public boolean onDismiss() {
5768                AsyncTask.execute(new Runnable() {
5769                    @Override
5770                    public void run() {
5771                        TaskStackBuilder.create(mContext)
5772                                .addNextIntentWithParentStack(intent)
5773                                .startActivities(getActivityOptions(),
5774                                        new UserHandle(UserHandle.getUserId(appUid)));
5775                    }
5776                });
5777                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */);
5778                return true;
5779            }
5780        }, false /* afterKeyguardGone */);
5781    }
5782
5783    public void setNotificationSnoozed(StatusBarNotification sbn, SnoozeOption snoozeOption) {
5784        if (snoozeOption.criterion != null) {
5785            mNotificationListener.snoozeNotification(sbn.getKey(), snoozeOption.criterion.getId());
5786        } else {
5787            mNotificationListener.snoozeNotification(sbn.getKey(),
5788                    snoozeOption.snoozeForMinutes * 60 * 1000);
5789        }
5790    }
5791
5792    private void bindGuts(final ExpandableNotificationRow row, MenuItem item) {
5793        row.inflateGuts();
5794        row.setGutsView(item);
5795        final StatusBarNotification sbn = row.getStatusBarNotification();
5796        row.setTag(sbn.getPackageName());
5797        final NotificationGuts guts = row.getGuts();
5798        guts.setClosedListener((NotificationGuts g) -> {
5799            if (!g.willBeRemoved() && !row.isRemoved()) {
5800                mStackScroller.onHeightChanged(row, !isPanelFullyCollapsed() /* needsAnimation */);
5801            }
5802            mNotificationGutsExposed = null;
5803            mGutsMenuItem = null;
5804        });
5805
5806        View gutsView = item.getGutsView();
5807        if (gutsView instanceof NotificationSnooze) {
5808            NotificationSnooze snoozeGuts = (NotificationSnooze) gutsView;
5809            snoozeGuts.setSnoozeListener(mStackScroller.getSwipeActionHelper());
5810            snoozeGuts.setStatusBarNotification(sbn);
5811            snoozeGuts.setSnoozeOptions(row.getEntry().snoozeCriteria);
5812            guts.setHeightChangedListener((NotificationGuts g) -> {
5813                mStackScroller.onHeightChanged(row, row.isShown() /* needsAnimation */);
5814            });
5815        }
5816
5817        if (gutsView instanceof NotificationInfo) {
5818            final UserHandle userHandle = sbn.getUser();
5819            PackageManager pmUser = getPackageManagerForUser(mContext,
5820                    userHandle.getIdentifier());
5821            final INotificationManager iNotificationManager = INotificationManager.Stub.asInterface(
5822                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
5823            final String pkg = sbn.getPackageName();
5824            NotificationInfo info = (NotificationInfo) gutsView;
5825            // Settings link is only valid for notifications that specify a user, unless this is the
5826            // system user.
5827            NotificationInfo.OnSettingsClickListener onSettingsClick = null;
5828            if (!userHandle.equals(UserHandle.ALL) || mCurrentUserId == UserHandle.USER_SYSTEM) {
5829                onSettingsClick = (View v, NotificationChannel channel, int appUid) -> {
5830                    mMetricsLogger.action(MetricsEvent.ACTION_NOTE_INFO);
5831                    guts.resetFalsingCheck();
5832                    startAppNotificationSettingsActivity(pkg, appUid, channel);
5833                };
5834            }
5835            final NotificationInfo.OnAppSettingsClickListener onAppSettingsClick = (View v,
5836                    Intent intent) -> {
5837                mMetricsLogger.action(MetricsEvent.ACTION_APP_NOTE_SETTINGS);
5838                guts.resetFalsingCheck();
5839                startNotificationGutsIntent(intent, sbn.getUid());
5840            };
5841            final View.OnClickListener onDoneClick = (View v) -> {
5842                saveAndCloseNotificationMenu(info, row, guts, v);
5843            };
5844            final NotificationInfo.CheckSaveListener checkSaveListener =
5845                    (Runnable saveImportance) -> {
5846                // If the user has security enabled, show challenge if the setting is changed.
5847                if (isLockscreenPublicMode(userHandle.getIdentifier())
5848                        && (mState == StatusBarState.KEYGUARD
5849                                || mState == StatusBarState.SHADE_LOCKED)) {
5850                    onLockedNotificationImportanceChange(() -> {
5851                        saveImportance.run();
5852                        return true;
5853                    });
5854                } else {
5855                    saveImportance.run();
5856                }
5857            };
5858
5859            ArraySet<NotificationChannel> channels = new ArraySet<NotificationChannel>();
5860            channels.add(row.getEntry().channel);
5861            if (row.isSummaryWithChildren()) {
5862                // If this is a summary, then add in the children notification channels for the
5863                // same user and pkg.
5864                final List<ExpandableNotificationRow> childrenRows = row.getNotificationChildren();
5865                final int numChildren = childrenRows.size();
5866                for (int i = 0; i < numChildren; i++) {
5867                    final ExpandableNotificationRow childRow = childrenRows.get(i);
5868                    final NotificationChannel childChannel = childRow.getEntry().channel;
5869                    final StatusBarNotification childSbn = childRow.getStatusBarNotification();
5870                    if (childSbn.getUser().equals(userHandle) &&
5871                            childSbn.getPackageName().equals(pkg)) {
5872                        channels.add(childChannel);
5873                    }
5874                }
5875            }
5876            try {
5877                info.bindNotification(pmUser, iNotificationManager, pkg, new ArrayList(channels),
5878                        row.getEntry().channel.getImportance(), sbn, onSettingsClick,
5879                        onAppSettingsClick, onDoneClick, checkSaveListener,
5880                        mNonBlockablePkgs);
5881            } catch (RemoteException e) {
5882                Log.e(TAG, e.toString());
5883            }
5884        }
5885    }
5886
5887    private void saveAndCloseNotificationMenu(NotificationInfo info,
5888            ExpandableNotificationRow row, NotificationGuts guts, View done) {
5889        guts.resetFalsingCheck();
5890        int[] rowLocation = new int[2];
5891        int[] doneLocation = new int[2];
5892        row.getLocationOnScreen(rowLocation);
5893        done.getLocationOnScreen(doneLocation);
5894
5895        final int centerX = done.getWidth() / 2;
5896        final int centerY = done.getHeight() / 2;
5897        final int x = doneLocation[0] - rowLocation[0] + centerX;
5898        final int y = doneLocation[1] - rowLocation[1] + centerY;
5899        dismissPopups(x, y);
5900    }
5901
5902    protected SwipeHelper.LongPressListener getNotificationLongClicker() {
5903        return new SwipeHelper.LongPressListener() {
5904            @Override
5905            public boolean onLongPress(View v, final int x, final int y,
5906                    MenuItem item) {
5907                if (!(v instanceof ExpandableNotificationRow)) {
5908                    return false;
5909                }
5910                if (v.getWindowToken() == null) {
5911                    Log.e(TAG, "Trying to show notification guts, but not attached to window");
5912                    return false;
5913                }
5914
5915                final ExpandableNotificationRow row = (ExpandableNotificationRow) v;
5916                if (row.isDark()) {
5917                    return false;
5918                }
5919                bindGuts(row, item);
5920                NotificationGuts guts = row.getGuts();
5921
5922                // Assume we are a status_bar_notification_row
5923                if (guts == null) {
5924                    // This view has no guts. Examples are the more card or the dismiss all view
5925                    return false;
5926                }
5927
5928                // Already showing?
5929                if (guts.getVisibility() == View.VISIBLE) {
5930                    dismissPopups(x, y);
5931                    return false;
5932                }
5933
5934                mMetricsLogger.action(MetricsEvent.ACTION_NOTE_CONTROLS);
5935
5936                // ensure that it's laid but not visible until actually laid out
5937                guts.setVisibility(View.INVISIBLE);
5938                // Post to ensure the the guts are properly laid out.
5939                guts.post(new Runnable() {
5940                    @Override
5941                    public void run() {
5942                        if (row.getWindowToken() == null) {
5943                            Log.e(TAG, "Trying to show notification guts, but not attached to "
5944                                    + "window");
5945                            return;
5946                        }
5947                        dismissPopups(-1 /* x */, -1 /* y */, false /* resetMenu */,
5948                                false /* animate */);
5949                        guts.setVisibility(View.VISIBLE);
5950                        final double horz = Math.max(guts.getWidth() - x, x);
5951                        final double vert = Math.max(guts.getHeight() - y, y);
5952                        final float r = (float) Math.hypot(horz, vert);
5953                        final Animator a
5954                                = ViewAnimationUtils.createCircularReveal(guts, x, y, 0, r);
5955                        a.setDuration(StackStateAnimator.ANIMATION_DURATION_STANDARD);
5956                        a.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
5957                        a.addListener(new AnimatorListenerAdapter() {
5958                            @Override
5959                            public void onAnimationEnd(Animator animation) {
5960                                super.onAnimationEnd(animation);
5961                                // Move the notification view back over the menu
5962                                row.resetTranslation();
5963                            }
5964                        });
5965                        a.start();
5966                        final boolean needsFalsingProtection =
5967                                (mState == StatusBarState.KEYGUARD &&
5968                                !mAccessibilityManager.isTouchExplorationEnabled());
5969                        guts.setExposed(true /* exposed */, needsFalsingProtection);
5970                        row.closeRemoteInput();
5971                        mStackScroller.onHeightChanged(row, true /* needsAnimation */);
5972                        mNotificationGutsExposed = guts;
5973                        mGutsMenuItem = item;
5974                    }
5975                });
5976                return true;
5977            }
5978        };
5979    }
5980
5981    /**
5982     * Returns the exposed NotificationGuts or null if none are exposed.
5983     */
5984    public NotificationGuts getExposedGuts() {
5985        return mNotificationGutsExposed;
5986    }
5987
5988    public void dismissPopups() {
5989        dismissPopups(-1 /* x */, -1 /* y */, true /* resetMenu */, false /* animate */);
5990    }
5991
5992    private void dismissPopups(int x, int y) {
5993        dismissPopups(x, y, true /* resetMenu */, false /* animate */);
5994    }
5995
5996    public void dismissPopups(int x, int y, boolean resetMenu, boolean animate) {
5997        if (mNotificationGutsExposed != null) {
5998            mNotificationGutsExposed.closeControls(x, y, true /* save */);
5999        }
6000        if (resetMenu) {
6001            mStackScroller.resetExposedMenuView(animate, true /* force */);
6002        }
6003    }
6004
6005    @Override
6006    public void toggleSplitScreen() {
6007        toggleSplitScreenMode(-1 /* metricsDockAction */, -1 /* metricsUndockAction */);
6008    }
6009
6010    @Override
6011    public void preloadRecentApps() {
6012        int msg = MSG_PRELOAD_RECENT_APPS;
6013        mHandler.removeMessages(msg);
6014        mHandler.sendEmptyMessage(msg);
6015    }
6016
6017    @Override
6018    public void cancelPreloadRecentApps() {
6019        int msg = MSG_CANCEL_PRELOAD_RECENT_APPS;
6020        mHandler.removeMessages(msg);
6021        mHandler.sendEmptyMessage(msg);
6022    }
6023
6024    @Override
6025    public void dismissKeyboardShortcutsMenu() {
6026        int msg = MSG_DISMISS_KEYBOARD_SHORTCUTS_MENU;
6027        mHandler.removeMessages(msg);
6028        mHandler.sendEmptyMessage(msg);
6029    }
6030
6031    @Override
6032    public void toggleKeyboardShortcutsMenu(int deviceId) {
6033        int msg = MSG_TOGGLE_KEYBOARD_SHORTCUTS_MENU;
6034        mHandler.removeMessages(msg);
6035        mHandler.obtainMessage(msg, deviceId, 0).sendToTarget();
6036    }
6037
6038    protected void sendCloseSystemWindows(String reason) {
6039        try {
6040            ActivityManager.getService().closeSystemDialogs(reason);
6041        } catch (RemoteException e) {
6042        }
6043    }
6044
6045    protected void toggleKeyboardShortcuts(int deviceId) {
6046        KeyboardShortcuts.toggle(mContext, deviceId);
6047    }
6048
6049    protected void dismissKeyboardShortcuts() {
6050        KeyboardShortcuts.dismiss();
6051    }
6052
6053    /**
6054     * Save the current "public" (locked and secure) state of the lockscreen.
6055     */
6056    public void setLockscreenPublicMode(boolean publicMode, int userId) {
6057        mLockscreenPublicMode.put(userId, publicMode);
6058    }
6059
6060    public boolean isLockscreenPublicMode(int userId) {
6061        return mLockscreenPublicMode.get(userId, false);
6062    }
6063
6064    /**
6065     * Has the given user chosen to allow notifications to be shown even when the lockscreen is in
6066     * "public" (secure & locked) mode?
6067     */
6068    public boolean userAllowsNotificationsInPublic(int userHandle) {
6069        if (userHandle == UserHandle.USER_ALL) {
6070            return true;
6071        }
6072
6073        if (mUsersAllowingNotifications.indexOfKey(userHandle) < 0) {
6074            final boolean allowed = 0 != Settings.Secure.getIntForUser(
6075                    mContext.getContentResolver(),
6076                    Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0, userHandle);
6077            mUsersAllowingNotifications.append(userHandle, allowed);
6078            return allowed;
6079        }
6080
6081        return mUsersAllowingNotifications.get(userHandle);
6082    }
6083
6084    /**
6085     * Has the given user chosen to allow their private (full) notifications to be shown even
6086     * when the lockscreen is in "public" (secure & locked) mode?
6087     */
6088    public boolean userAllowsPrivateNotificationsInPublic(int userHandle) {
6089        if (userHandle == UserHandle.USER_ALL) {
6090            return true;
6091        }
6092
6093        if (mUsersAllowingPrivateNotifications.indexOfKey(userHandle) < 0) {
6094            final boolean allowedByUser = 0 != Settings.Secure.getIntForUser(
6095                    mContext.getContentResolver(),
6096                    Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0, userHandle);
6097            final boolean allowedByDpm = adminAllowsUnredactedNotifications(userHandle);
6098            final boolean allowed = allowedByUser && allowedByDpm;
6099            mUsersAllowingPrivateNotifications.append(userHandle, allowed);
6100            return allowed;
6101        }
6102
6103        return mUsersAllowingPrivateNotifications.get(userHandle);
6104    }
6105
6106    private boolean adminAllowsUnredactedNotifications(int userHandle) {
6107        if (userHandle == UserHandle.USER_ALL) {
6108            return true;
6109        }
6110        final int dpmFlags = mDevicePolicyManager.getKeyguardDisabledFeatures(null /* admin */,
6111                    userHandle);
6112        return (dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS) == 0;
6113    }
6114
6115    /**
6116     * Returns true if we're on a secure lockscreen and the user wants to hide notification data.
6117     * If so, notifications should be hidden.
6118     */
6119    @Override  // NotificationData.Environment
6120    public boolean shouldHideNotifications(int userId) {
6121        return isLockscreenPublicMode(userId) && !userAllowsNotificationsInPublic(userId)
6122                || (userId != mCurrentUserId && shouldHideNotifications(mCurrentUserId));
6123    }
6124
6125    /**
6126     * Returns true if we're on a secure lockscreen and the user wants to hide notifications via
6127     * package-specific override.
6128     */
6129    @Override // NotificationDate.Environment
6130    public boolean shouldHideNotifications(String key) {
6131        return isLockscreenPublicMode(mCurrentUserId)
6132                && mNotificationData.getVisibilityOverride(key) == Notification.VISIBILITY_SECRET;
6133    }
6134
6135    /**
6136     * Returns true if we're on a secure lockscreen.
6137     */
6138    @Override  // NotificationData.Environment
6139    public boolean isSecurelyLocked(int userId) {
6140        return isLockscreenPublicMode(userId);
6141    }
6142
6143    public void onNotificationClear(StatusBarNotification notification) {
6144        try {
6145            mBarService.onNotificationClear(
6146                    notification.getPackageName(),
6147                    notification.getTag(),
6148                    notification.getId(),
6149                    notification.getUserId());
6150        } catch (android.os.RemoteException ex) {
6151            // oh well
6152        }
6153    }
6154
6155    /**
6156     * Called when the notification panel layouts
6157     */
6158    public void onPanelLaidOut() {
6159        if (mState == StatusBarState.KEYGUARD) {
6160            // Since the number of notifications is determined based on the height of the view, we
6161            // need to update them.
6162            int maxBefore = getMaxKeyguardNotifications(false /* recompute */);
6163            int maxNotifications = getMaxKeyguardNotifications(true /* recompute */);
6164            if (maxBefore != maxNotifications) {
6165                updateRowStates();
6166            }
6167        }
6168    }
6169
6170    protected void inflateViews(Entry entry, ViewGroup parent) {
6171        PackageManager pmUser = getPackageManagerForUser(mContext,
6172                entry.notification.getUser().getIdentifier());
6173
6174        final StatusBarNotification sbn = entry.notification;
6175        if (entry.row != null) {
6176            entry.reset();
6177            updateNotification(entry, pmUser, sbn, entry.row);
6178        } else {
6179            new RowInflaterTask().inflate(mContext, parent, entry,
6180                    row -> {
6181                        bindRow(entry, pmUser, sbn, row);
6182                        updateNotification(entry, pmUser, sbn, row);
6183                    });
6184        }
6185
6186    }
6187
6188    private void bindRow(Entry entry, PackageManager pmUser,
6189            StatusBarNotification sbn, ExpandableNotificationRow row) {
6190        row.setExpansionLogger(this, entry.notification.getKey());
6191        row.setGroupManager(mGroupManager);
6192        row.setHeadsUpManager(mHeadsUpManager);
6193        row.setRemoteInputController(mRemoteInputController);
6194        row.setOnExpandClickListener(this);
6195        row.setRemoteViewClickHandler(mOnClickHandler);
6196        row.setInflationCallback(this);
6197
6198        // Get the app name.
6199        // Note that Notification.Builder#bindHeaderAppName has similar logic
6200        // but since this field is used in the guts, it must be accurate.
6201        // Therefore we will only show the application label, or, failing that, the
6202        // package name. No substitutions.
6203        final String pkg = sbn.getPackageName();
6204        String appname = pkg;
6205        try {
6206            final ApplicationInfo info = pmUser.getApplicationInfo(pkg,
6207                    PackageManager.MATCH_UNINSTALLED_PACKAGES
6208                            | PackageManager.MATCH_DISABLED_COMPONENTS);
6209            if (info != null) {
6210                appname = String.valueOf(pmUser.getApplicationLabel(info));
6211            }
6212        } catch (NameNotFoundException e) {
6213            // Do nothing
6214        }
6215        row.setAppName(appname);
6216        row.setOnDismissRunnable(() ->
6217                performRemoveNotification(row.getStatusBarNotification()));
6218        row.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
6219        if (ENABLE_REMOTE_INPUT) {
6220            row.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
6221        }
6222    }
6223
6224    private void updateNotification(Entry entry, PackageManager pmUser,
6225            StatusBarNotification sbn, ExpandableNotificationRow row) {
6226        row.setNeedsRedaction(needsRedaction(entry));
6227        boolean isLowPriority = mNotificationData.isAmbient(sbn.getKey());
6228        row.setIsLowPriority(isLowPriority);
6229        // bind the click event to the content area
6230        mNotificationClicker.register(row, sbn);
6231
6232        // Extract target SDK version.
6233        try {
6234            ApplicationInfo info = pmUser.getApplicationInfo(sbn.getPackageName(), 0);
6235            entry.targetSdk = info.targetSdkVersion;
6236        } catch (NameNotFoundException ex) {
6237            Log.e(TAG, "Failed looking up ApplicationInfo for " + sbn.getPackageName(), ex);
6238        }
6239        row.setLegacy(entry.targetSdk >= Build.VERSION_CODES.GINGERBREAD
6240                && entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
6241        entry.setIconTag(R.id.icon_is_pre_L, entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
6242        entry.autoRedacted = entry.notification.getNotification().publicVersion == null;
6243
6244        entry.row = row;
6245        entry.row.setOnActivatedListener(this);
6246
6247        boolean useIncreasedCollapsedHeight = mMessagingUtil.isImportantMessaging(sbn,
6248                mNotificationData.getImportance(sbn.getKey()));
6249        boolean useIncreasedHeadsUp = useIncreasedCollapsedHeight && mPanelExpanded;
6250        row.setUseIncreasedCollapsedHeight(useIncreasedCollapsedHeight);
6251        row.setUseIncreasedHeadsUpHeight(useIncreasedHeadsUp);
6252        row.updateNotification(entry);
6253    }
6254
6255    /**
6256     * Adds RemoteInput actions from the WearableExtender; to be removed once more apps support this
6257     * via first-class API.
6258     *
6259     * TODO: Remove once enough apps specify remote inputs on their own.
6260     */
6261    private void processForRemoteInput(Notification n) {
6262        if (!ENABLE_REMOTE_INPUT) return;
6263
6264        if (n.extras != null && n.extras.containsKey("android.wearable.EXTENSIONS") &&
6265                (n.actions == null || n.actions.length == 0)) {
6266            Notification.Action viableAction = null;
6267            Notification.WearableExtender we = new Notification.WearableExtender(n);
6268
6269            List<Notification.Action> actions = we.getActions();
6270            final int numActions = actions.size();
6271
6272            for (int i = 0; i < numActions; i++) {
6273                Notification.Action action = actions.get(i);
6274                if (action == null) {
6275                    continue;
6276                }
6277                RemoteInput[] remoteInputs = action.getRemoteInputs();
6278                if (remoteInputs == null) {
6279                    continue;
6280                }
6281                for (RemoteInput ri : remoteInputs) {
6282                    if (ri.getAllowFreeFormInput()) {
6283                        viableAction = action;
6284                        break;
6285                    }
6286                }
6287                if (viableAction != null) {
6288                    break;
6289                }
6290            }
6291
6292            if (viableAction != null) {
6293                Notification.Builder rebuilder = Notification.Builder.recoverBuilder(mContext, n);
6294                rebuilder.setActions(viableAction);
6295                rebuilder.build(); // will rewrite n
6296            }
6297        }
6298    }
6299
6300    public void startPendingIntentDismissingKeyguard(final PendingIntent intent) {
6301        if (!isDeviceProvisioned()) return;
6302
6303        final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
6304        final boolean afterKeyguardGone = intent.isActivity()
6305                && PreviewInflater.wouldLaunchResolverActivity(mContext, intent.getIntent(),
6306                mCurrentUserId);
6307        dismissKeyguardThenExecute(new OnDismissAction() {
6308            @Override
6309            public boolean onDismiss() {
6310                new Thread() {
6311                    @Override
6312                    public void run() {
6313                        try {
6314                            // The intent we are sending is for the application, which
6315                            // won't have permission to immediately start an activity after
6316                            // the user switches to home.  We know it is safe to do at this
6317                            // point, so make sure new activity switches are now allowed.
6318                            ActivityManager.getService().resumeAppSwitches();
6319                        } catch (RemoteException e) {
6320                        }
6321                        try {
6322                            intent.send(null, 0, null, null, null, null, getActivityOptions());
6323                        } catch (PendingIntent.CanceledException e) {
6324                            // the stack trace isn't very helpful here.
6325                            // Just log the exception message.
6326                            Log.w(TAG, "Sending intent failed: " + e);
6327
6328                            // TODO: Dismiss Keyguard.
6329                        }
6330                        if (intent.isActivity()) {
6331                            mAssistManager.hideAssist();
6332                        }
6333                    }
6334                }.start();
6335
6336                // close the shade if it was open
6337                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
6338                        true /* force */, true /* delayed */);
6339                visibilityChanged(false);
6340
6341                return true;
6342            }
6343        }, afterKeyguardGone);
6344    }
6345
6346
6347    private final class NotificationClicker implements View.OnClickListener {
6348
6349        @Override
6350        public void onClick(final View v) {
6351            if (!(v instanceof ExpandableNotificationRow)) {
6352                Log.e(TAG, "NotificationClicker called on a view that is not a notification row.");
6353                return;
6354            }
6355
6356            wakeUpIfDozing(SystemClock.uptimeMillis(), v);
6357
6358            final ExpandableNotificationRow row = (ExpandableNotificationRow) v;
6359            final StatusBarNotification sbn = row.getStatusBarNotification();
6360            if (sbn == null) {
6361                Log.e(TAG, "NotificationClicker called on an unclickable notification,");
6362                return;
6363            }
6364
6365            // Check if the notification is displaying the menu, if so slide notification back
6366            if (row.getProvider() != null && row.getProvider().isMenuVisible()) {
6367                row.animateTranslateNotification(0);
6368                return;
6369            }
6370
6371            Notification notification = sbn.getNotification();
6372            final PendingIntent intent = notification.contentIntent != null
6373                    ? notification.contentIntent
6374                    : notification.fullScreenIntent;
6375            final String notificationKey = sbn.getKey();
6376
6377            // Mark notification for one frame.
6378            row.setJustClicked(true);
6379            DejankUtils.postAfterTraversal(new Runnable() {
6380                @Override
6381                public void run() {
6382                    row.setJustClicked(false);
6383                }
6384            });
6385
6386            final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
6387            final boolean afterKeyguardGone = intent.isActivity()
6388                    && PreviewInflater.wouldLaunchResolverActivity(mContext, intent.getIntent(),
6389                            mCurrentUserId);
6390            dismissKeyguardThenExecute(new OnDismissAction() {
6391                @Override
6392                public boolean onDismiss() {
6393                    if (mHeadsUpManager != null && mHeadsUpManager.isHeadsUp(notificationKey)) {
6394                        // Release the HUN notification to the shade.
6395
6396                        if (isPanelFullyCollapsed()) {
6397                            HeadsUpManager.setIsClickedNotification(row, true);
6398                        }
6399                        //
6400                        // In most cases, when FLAG_AUTO_CANCEL is set, the notification will
6401                        // become canceled shortly by NoMan, but we can't assume that.
6402                        mHeadsUpManager.releaseImmediately(notificationKey);
6403                    }
6404                    StatusBarNotification parentToCancel = null;
6405                    if (shouldAutoCancel(sbn) && mGroupManager.isOnlyChildInGroup(sbn)) {
6406                        StatusBarNotification summarySbn = mGroupManager.getLogicalGroupSummary(sbn)
6407                                        .getStatusBarNotification();
6408                        if (shouldAutoCancel(summarySbn)) {
6409                            parentToCancel = summarySbn;
6410                        }
6411                    }
6412                    final StatusBarNotification parentToCancelFinal = parentToCancel;
6413                    new Thread() {
6414                        @Override
6415                        public void run() {
6416                            try {
6417                                // The intent we are sending is for the application, which
6418                                // won't have permission to immediately start an activity after
6419                                // the user switches to home.  We know it is safe to do at this
6420                                // point, so make sure new activity switches are now allowed.
6421                                ActivityManager.getService().resumeAppSwitches();
6422                            } catch (RemoteException e) {
6423                            }
6424                            if (intent != null) {
6425                                // If we are launching a work activity and require to launch
6426                                // separate work challenge, we defer the activity action and cancel
6427                                // notification until work challenge is unlocked.
6428                                if (intent.isActivity()) {
6429                                    final int userId = intent.getCreatorUserHandle()
6430                                            .getIdentifier();
6431                                    if (mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)
6432                                            && mKeyguardManager.isDeviceLocked(userId)) {
6433                                        // TODO(b/28935539): should allow certain activities to
6434                                        // bypass work challenge
6435                                        if (startWorkChallengeIfNecessary(userId,
6436                                                intent.getIntentSender(), notificationKey)) {
6437                                            // Show work challenge, do not run PendingIntent and
6438                                            // remove notification
6439                                            return;
6440                                        }
6441                                    }
6442                                }
6443                                try {
6444                                    intent.send(null, 0, null, null, null, null,
6445                                            getActivityOptions());
6446                                } catch (PendingIntent.CanceledException e) {
6447                                    // the stack trace isn't very helpful here.
6448                                    // Just log the exception message.
6449                                    Log.w(TAG, "Sending contentIntent failed: " + e);
6450
6451                                    // TODO: Dismiss Keyguard.
6452                                }
6453                                if (intent.isActivity()) {
6454                                    mAssistManager.hideAssist();
6455                                }
6456                            }
6457
6458                            try {
6459                                mBarService.onNotificationClick(notificationKey);
6460                            } catch (RemoteException ex) {
6461                                // system process is dead if we're here.
6462                            }
6463                            if (parentToCancelFinal != null) {
6464                                // We have to post it to the UI thread for synchronization
6465                                mHandler.post(new Runnable() {
6466                                    @Override
6467                                    public void run() {
6468                                        Runnable removeRunnable = new Runnable() {
6469                                            @Override
6470                                            public void run() {
6471                                                performRemoveNotification(parentToCancelFinal);
6472                                            }
6473                                        };
6474                                        if (isCollapsing()) {
6475                                            // To avoid lags we're only performing the remove
6476                                            // after the shade was collapsed
6477                                            addPostCollapseAction(removeRunnable);
6478                                        } else {
6479                                            removeRunnable.run();
6480                                        }
6481                                    }
6482                                });
6483                            }
6484                        }
6485                    }.start();
6486
6487                    // close the shade if it was open
6488                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
6489                            true /* force */, true /* delayed */);
6490                    visibilityChanged(false);
6491
6492                    return true;
6493                }
6494            }, afterKeyguardGone);
6495        }
6496
6497        private boolean shouldAutoCancel(StatusBarNotification sbn) {
6498            int flags = sbn.getNotification().flags;
6499            if ((flags & Notification.FLAG_AUTO_CANCEL) != Notification.FLAG_AUTO_CANCEL) {
6500                return false;
6501            }
6502            if ((flags & Notification.FLAG_FOREGROUND_SERVICE) != 0) {
6503                return false;
6504            }
6505            return true;
6506        }
6507
6508        public void register(ExpandableNotificationRow row, StatusBarNotification sbn) {
6509            Notification notification = sbn.getNotification();
6510            if (notification.contentIntent != null || notification.fullScreenIntent != null) {
6511                row.setOnClickListener(this);
6512            } else {
6513                row.setOnClickListener(null);
6514            }
6515        }
6516    }
6517
6518    protected Bundle getActivityOptions() {
6519        // Anything launched from the notification shade should always go into the
6520        // fullscreen stack.
6521        ActivityOptions options = ActivityOptions.makeBasic();
6522        options.setLaunchStackId(StackId.FULLSCREEN_WORKSPACE_STACK_ID);
6523        return options.toBundle();
6524    }
6525
6526    protected void visibilityChanged(boolean visible) {
6527        if (mVisible != visible) {
6528            mVisible = visible;
6529            if (!visible) {
6530                dismissPopups();
6531            }
6532        }
6533        updateVisibleToUser();
6534    }
6535
6536    protected void updateVisibleToUser() {
6537        boolean oldVisibleToUser = mVisibleToUser;
6538        mVisibleToUser = mVisible && mDeviceInteractive;
6539
6540        if (oldVisibleToUser != mVisibleToUser) {
6541            handleVisibleToUserChanged(mVisibleToUser);
6542        }
6543    }
6544
6545    /**
6546     * Clear Buzz/Beep/Blink.
6547     */
6548    public void clearNotificationEffects() {
6549        try {
6550            mBarService.clearNotificationEffects();
6551        } catch (RemoteException e) {
6552            // Won't fail unless the world has ended.
6553        }
6554    }
6555
6556    /**
6557     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
6558     * about the failure.
6559     *
6560     * WARNING: this will call back into us.  Don't hold any locks.
6561     */
6562    void handleNotificationError(StatusBarNotification n, String message) {
6563        removeNotification(n.getKey(), null);
6564        try {
6565            mBarService.onNotificationError(n.getPackageName(), n.getTag(), n.getId(), n.getUid(),
6566                    n.getInitialPid(), message, n.getUserId());
6567        } catch (RemoteException ex) {
6568            // The end is nigh.
6569        }
6570    }
6571
6572    protected StatusBarNotification removeNotificationViews(String key, RankingMap ranking) {
6573        NotificationData.Entry entry = mNotificationData.remove(key, ranking);
6574        if (entry == null) {
6575            Log.w(TAG, "removeNotification for unknown key: " + key);
6576            return null;
6577        }
6578        updateNotifications();
6579        Dependency.get(LeakDetector.class).trackGarbage(entry);
6580        return entry.notification;
6581    }
6582
6583    protected NotificationData.Entry createNotificationViews(StatusBarNotification sbn)
6584            throws InflationException {
6585        if (DEBUG) {
6586            Log.d(TAG, "createNotificationViews(notification=" + sbn);
6587        }
6588        NotificationData.Entry entry = new NotificationData.Entry(sbn);
6589        Dependency.get(LeakDetector.class).trackInstance(entry);
6590        entry.createIcons(mContext, sbn);
6591        // Construct the expanded view.
6592        inflateViews(entry, mStackScroller);
6593        return entry;
6594    }
6595
6596    protected void addNotificationViews(Entry entry) {
6597        if (entry == null) {
6598            return;
6599        }
6600        // Add the expanded view and icon.
6601        mNotificationData.add(entry);
6602        updateNotifications();
6603    }
6604
6605    /**
6606     * Updates expanded, dimmed and locked states of notification rows.
6607     */
6608    protected void updateRowStates() {
6609        final int N = mStackScroller.getChildCount();
6610
6611        int visibleNotifications = 0;
6612        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
6613        int maxNotifications = -1;
6614        if (onKeyguard) {
6615            maxNotifications = getMaxKeyguardNotifications(true /* recompute */);
6616        }
6617        mStackScroller.setMaxDisplayedNotifications(maxNotifications);
6618        Stack<ExpandableNotificationRow> stack = new Stack<>();
6619        for (int i = N - 1; i >= 0; i--) {
6620            View child = mStackScroller.getChildAt(i);
6621            if (!(child instanceof ExpandableNotificationRow)) {
6622                continue;
6623            }
6624            stack.push((ExpandableNotificationRow) child);
6625        }
6626        while(!stack.isEmpty()) {
6627            ExpandableNotificationRow row = stack.pop();
6628            NotificationData.Entry entry = row.getEntry();
6629            boolean childNotification = mGroupManager.isChildInGroupWithSummary(entry.notification);
6630            if (onKeyguard) {
6631                row.setOnKeyguard(true);
6632            } else {
6633                row.setOnKeyguard(false);
6634                row.setSystemExpanded(visibleNotifications == 0 && !childNotification);
6635            }
6636            entry.row.setShowAmbient(isDozing());
6637            int userId = entry.notification.getUserId();
6638            boolean suppressedSummary = mGroupManager.isSummaryOfSuppressedGroup(
6639                    entry.notification) && !entry.row.isRemoved();
6640            boolean showOnKeyguard = shouldShowOnKeyguard(entry.notification);
6641            if (suppressedSummary
6642                    || (isLockscreenPublicMode(userId) && !mShowLockscreenNotifications)
6643                    || (onKeyguard && !showOnKeyguard)) {
6644                entry.row.setVisibility(View.GONE);
6645            } else {
6646                boolean wasGone = entry.row.getVisibility() == View.GONE;
6647                if (wasGone) {
6648                    entry.row.setVisibility(View.VISIBLE);
6649                }
6650                if (!childNotification && !entry.row.isRemoved()) {
6651                    if (wasGone) {
6652                        // notify the scroller of a child addition
6653                        mStackScroller.generateAddAnimation(entry.row,
6654                                !showOnKeyguard /* fromMoreCard */);
6655                    }
6656                    visibleNotifications++;
6657                }
6658            }
6659            if (row.isSummaryWithChildren()) {
6660                List<ExpandableNotificationRow> notificationChildren =
6661                        row.getNotificationChildren();
6662                int size = notificationChildren.size();
6663                for (int i = size - 1; i >= 0; i--) {
6664                    stack.push(notificationChildren.get(i));
6665                }
6666            }
6667        }
6668        mNotificationPanel.setNoVisibleNotifications(visibleNotifications == 0);
6669
6670        mStackScroller.changeViewPosition(mDismissView, mStackScroller.getChildCount() - 1);
6671        mStackScroller.changeViewPosition(mEmptyShadeView, mStackScroller.getChildCount() - 2);
6672        mStackScroller.changeViewPosition(mNotificationShelf, mStackScroller.getChildCount() - 3);
6673    }
6674
6675    public boolean shouldShowOnKeyguard(StatusBarNotification sbn) {
6676        return mShowLockscreenNotifications && !mNotificationData.isAmbient(sbn.getKey());
6677    }
6678
6679    // extended in StatusBar
6680    protected void setShowLockscreenNotifications(boolean show) {
6681        mShowLockscreenNotifications = show;
6682    }
6683
6684    protected void setLockScreenAllowRemoteInput(boolean allowLockscreenRemoteInput) {
6685        mAllowLockscreenRemoteInput = allowLockscreenRemoteInput;
6686    }
6687
6688    private void updateLockscreenNotificationSetting() {
6689        final boolean show = Settings.Secure.getIntForUser(mContext.getContentResolver(),
6690                Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
6691                1,
6692                mCurrentUserId) != 0;
6693        final int dpmFlags = mDevicePolicyManager.getKeyguardDisabledFeatures(
6694                null /* admin */, mCurrentUserId);
6695        final boolean allowedByDpm = (dpmFlags
6696                & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS) == 0;
6697
6698        setShowLockscreenNotifications(show && allowedByDpm);
6699
6700        if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
6701            final boolean remoteInput = Settings.Secure.getIntForUser(mContext.getContentResolver(),
6702                    Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT,
6703                    0,
6704                    mCurrentUserId) != 0;
6705            final boolean remoteInputDpm =
6706                    (dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_REMOTE_INPUT) == 0;
6707
6708            setLockScreenAllowRemoteInput(remoteInput && remoteInputDpm);
6709        } else {
6710            setLockScreenAllowRemoteInput(false);
6711        }
6712    }
6713
6714    public void updateNotification(StatusBarNotification notification, RankingMap ranking)
6715            throws InflationException {
6716        if (DEBUG) Log.d(TAG, "updateNotification(" + notification + ")");
6717
6718        final String key = notification.getKey();
6719        abortExistingInflation(key);
6720        Entry entry = mNotificationData.get(key);
6721        if (entry == null) {
6722            return;
6723        } else {
6724            mHeadsUpEntriesToRemoveOnSwitch.remove(entry);
6725            mRemoteInputEntriesToRemoveOnCollapse.remove(entry);
6726        }
6727
6728        Notification n = notification.getNotification();
6729        mNotificationData.updateRanking(ranking);
6730
6731        final StatusBarNotification oldNotification = entry.notification;
6732        entry.notification = notification;
6733        mGroupManager.onEntryUpdated(entry, oldNotification);
6734
6735        entry.updateIcons(mContext, n);
6736        inflateViews(entry, mStackScroller);
6737
6738        boolean shouldPeek = shouldPeek(entry, notification);
6739        boolean alertAgain = alertAgain(entry, n);
6740
6741        updateHeadsUp(key, entry, shouldPeek, alertAgain);
6742        updateNotifications();
6743
6744        if (!notification.isClearable()) {
6745            // The user may have performed a dismiss action on the notification, since it's
6746            // not clearable we should snap it back.
6747            mStackScroller.snapViewIfNeeded(entry.row);
6748        }
6749
6750        if (DEBUG) {
6751            // Is this for you?
6752            boolean isForCurrentUser = isNotificationForCurrentProfiles(notification);
6753            Log.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
6754        }
6755        setAreThereNotifications();
6756    }
6757
6758    protected void updatePublicContentView(Entry entry,
6759            StatusBarNotification sbn) {
6760        final RemoteViews publicContentView = entry.cachedPublicContentView;
6761        View inflatedView = entry.getPublicContentView();
6762        if (entry.autoRedacted && publicContentView != null && inflatedView != null) {
6763            final boolean disabledByPolicy =
6764                    !adminAllowsUnredactedNotifications(entry.notification.getUserId());
6765            String notificationHiddenText = mContext.getString(disabledByPolicy
6766                    ? com.android.internal.R.string.notification_hidden_by_policy_text
6767                    : com.android.internal.R.string.notification_hidden_text);
6768            TextView titleView = (TextView) inflatedView.findViewById(android.R.id.title);
6769            if (titleView != null
6770                    && !titleView.getText().toString().equals(notificationHiddenText)) {
6771                titleView.setText(notificationHiddenText);
6772            }
6773        }
6774    }
6775
6776    protected void notifyHeadsUpScreenOff() {
6777        maybeEscalateHeadsUp();
6778    }
6779
6780    private boolean alertAgain(Entry oldEntry, Notification newNotification) {
6781        return oldEntry == null || !oldEntry.hasInterrupted()
6782                || (newNotification.flags & Notification.FLAG_ONLY_ALERT_ONCE) == 0;
6783    }
6784
6785    protected boolean shouldPeek(Entry entry) {
6786        return shouldPeek(entry, entry.notification);
6787    }
6788
6789    protected boolean shouldPeek(Entry entry, StatusBarNotification sbn) {
6790        if (!mUseHeadsUp || isDeviceInVrMode()) {
6791            return false;
6792        }
6793
6794        if (mNotificationData.shouldFilterOut(sbn)) {
6795            if (DEBUG) Log.d(TAG, "No peeking: filtered notification: " + sbn.getKey());
6796            return false;
6797        }
6798
6799        boolean inUse = mPowerManager.isScreenOn();
6800        try {
6801            inUse = inUse && !mDreamManager.isDreaming();
6802        } catch (RemoteException e) {
6803            Log.d(TAG, "failed to query dream manager", e);
6804        }
6805
6806        if (!inUse && !isDozing()) {
6807            if (DEBUG) {
6808                Log.d(TAG, "No peeking: not in use: " + sbn.getKey());
6809            }
6810            return false;
6811        }
6812
6813        if (mNotificationData.shouldSuppressScreenOn(sbn.getKey())) {
6814            if (DEBUG) Log.d(TAG, "No peeking: suppressed by DND: " + sbn.getKey());
6815            return false;
6816        }
6817
6818        if (entry.hasJustLaunchedFullScreenIntent()) {
6819            if (DEBUG) Log.d(TAG, "No peeking: recent fullscreen: " + sbn.getKey());
6820            return false;
6821        }
6822
6823        if (isSnoozedPackage(sbn)) {
6824            if (DEBUG) Log.d(TAG, "No peeking: snoozed package: " + sbn.getKey());
6825            return false;
6826        }
6827
6828        // Allow peeking for DEFAULT notifications only if we're on Ambient Display.
6829        int importanceLevel = isDozing() ? NotificationManager.IMPORTANCE_DEFAULT
6830                : NotificationManager.IMPORTANCE_HIGH;
6831        if (mNotificationData.getImportance(sbn.getKey()) < importanceLevel) {
6832            if (DEBUG) Log.d(TAG, "No peeking: unimportant notification: " + sbn.getKey());
6833            return false;
6834        }
6835
6836        if (sbn.getNotification().fullScreenIntent != null) {
6837            if (mAccessibilityManager.isTouchExplorationEnabled()) {
6838                if (DEBUG) Log.d(TAG, "No peeking: accessible fullscreen: " + sbn.getKey());
6839                return false;
6840            } else {
6841                // we only allow head-up on the lockscreen if it doesn't have a fullscreen intent
6842                return !mStatusBarKeyguardViewManager.isShowing()
6843                        || mStatusBarKeyguardViewManager.isOccluded();
6844            }
6845        }
6846
6847        return true;
6848    }
6849
6850    /**
6851     * @return Whether the security bouncer from Keyguard is showing.
6852     */
6853    public boolean isBouncerShowing() {
6854        return mBouncerShowing;
6855    }
6856
6857    /**
6858     * @return a PackageManger for userId or if userId is < 0 (USER_ALL etc) then
6859     *         return PackageManager for mContext
6860     */
6861    public static PackageManager getPackageManagerForUser(Context context, int userId) {
6862        Context contextForUser = context;
6863        // UserHandle defines special userId as negative values, e.g. USER_ALL
6864        if (userId >= 0) {
6865            try {
6866                // Create a context for the correct user so if a package isn't installed
6867                // for user 0 we can still load information about the package.
6868                contextForUser =
6869                        context.createPackageContextAsUser(context.getPackageName(),
6870                        Context.CONTEXT_RESTRICTED,
6871                        new UserHandle(userId));
6872            } catch (NameNotFoundException e) {
6873                // Shouldn't fail to find the package name for system ui.
6874            }
6875        }
6876        return contextForUser.getPackageManager();
6877    }
6878
6879    @Override
6880    public void logNotificationExpansion(String key, boolean userAction, boolean expanded) {
6881        try {
6882            mBarService.onNotificationExpansionChanged(key, userAction, expanded);
6883        } catch (RemoteException e) {
6884            // Ignore.
6885        }
6886    }
6887
6888    public boolean isKeyguardSecure() {
6889        if (mStatusBarKeyguardViewManager == null) {
6890            // startKeyguard() hasn't been called yet, so we don't know.
6891            // Make sure anything that needs to know isKeyguardSecure() checks and re-checks this
6892            // value onVisibilityChanged().
6893            Slog.w(TAG, "isKeyguardSecure() called before startKeyguard(), returning false",
6894                    new Throwable());
6895            return false;
6896        }
6897        return mStatusBarKeyguardViewManager.isSecure();
6898    }
6899
6900    @Override
6901    public void showAssistDisclosure() {
6902        if (mAssistManager != null) {
6903            mAssistManager.showDisclosure();
6904        }
6905    }
6906
6907    @Override
6908    public void startAssist(Bundle args) {
6909        if (mAssistManager != null) {
6910            mAssistManager.startAssist(args);
6911        }
6912    }
6913    // End Extra BaseStatusBarMethods.
6914}
6915