PhoneStatusBar.java revision 0e66439387e36876de94a60658917a7f3b0e6d27
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.systemui.statusbar.phone;
18
19
20import static android.app.StatusBarManager.NAVIGATION_HINT_BACK_ALT;
21import static android.app.StatusBarManager.NAVIGATION_HINT_IME_SHOWN;
22import static android.app.StatusBarManager.WINDOW_STATE_HIDDEN;
23import static android.app.StatusBarManager.WINDOW_STATE_SHOWING;
24import static android.app.StatusBarManager.windowStateToString;
25import static com.android.systemui.statusbar.phone.BarTransitions.MODE_LIGHTS_OUT;
26import static com.android.systemui.statusbar.phone.BarTransitions.MODE_OPAQUE;
27import static com.android.systemui.statusbar.phone.BarTransitions.MODE_SEMI_TRANSPARENT;
28import static com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSLUCENT;
29import static com.android.systemui.statusbar.phone.BarTransitions.MODE_TRANSPARENT;
30import static com.android.systemui.statusbar.phone.BarTransitions.MODE_WARNING;
31
32import android.animation.Animator;
33import android.animation.AnimatorListenerAdapter;
34import android.animation.TimeInterpolator;
35import android.annotation.NonNull;
36import android.app.ActivityManager;
37import android.app.ActivityManagerNative;
38import android.app.IActivityManager;
39import android.app.Notification;
40import android.app.PendingIntent;
41import android.app.StatusBarManager;
42import android.content.BroadcastReceiver;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
46import android.content.res.Configuration;
47import android.content.res.Resources;
48import android.database.ContentObserver;
49import android.graphics.Bitmap;
50import android.graphics.Canvas;
51import android.graphics.ColorFilter;
52import android.graphics.PixelFormat;
53import android.graphics.Point;
54import android.graphics.PorterDuff;
55import android.graphics.PorterDuffXfermode;
56import android.graphics.Rect;
57import android.graphics.Xfermode;
58import android.graphics.drawable.ColorDrawable;
59import android.graphics.drawable.Drawable;
60import android.inputmethodservice.InputMethodService;
61import android.media.AudioAttributes;
62import android.media.MediaMetadata;
63import android.media.session.MediaController;
64import android.media.session.MediaSession;
65import android.media.session.MediaSessionManager;
66import android.media.session.PlaybackState;
67import android.os.AsyncTask;
68import android.os.Bundle;
69import android.os.Handler;
70import android.os.IBinder;
71import android.os.Message;
72import android.os.PowerManager;
73import android.os.RemoteException;
74import android.os.SystemClock;
75import android.os.UserHandle;
76import android.provider.Settings;
77import android.service.notification.NotificationListenerService;
78import android.service.notification.NotificationListenerService.RankingMap;
79import android.service.notification.StatusBarNotification;
80import android.util.ArraySet;
81import android.util.DisplayMetrics;
82import android.util.EventLog;
83import android.util.Log;
84import android.view.Display;
85import android.view.Gravity;
86import android.view.HardwareCanvas;
87import android.view.KeyEvent;
88import android.view.LayoutInflater;
89import android.view.MotionEvent;
90import android.view.VelocityTracker;
91import android.view.View;
92import android.view.ViewGroup;
93import android.view.ViewGroup.LayoutParams;
94import android.view.ViewPropertyAnimator;
95import android.view.ViewStub;
96import android.view.ViewTreeObserver;
97import android.view.WindowManager;
98import android.view.accessibility.AccessibilityEvent;
99import android.view.accessibility.AccessibilityManager;
100import android.view.animation.AccelerateDecelerateInterpolator;
101import android.view.animation.AccelerateInterpolator;
102import android.view.animation.Animation;
103import android.view.animation.AnimationUtils;
104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.Interpolator;
106import android.view.animation.LinearInterpolator;
107import android.view.animation.PathInterpolator;
108import android.widget.FrameLayout;
109import android.widget.ImageView;
110import android.widget.LinearLayout;
111import android.widget.TextView;
112
113import com.android.internal.statusbar.StatusBarIcon;
114import com.android.keyguard.KeyguardHostView.OnDismissAction;
115import com.android.keyguard.ViewMediatorCallback;
116import com.android.systemui.BatteryMeterView;
117import com.android.systemui.DemoMode;
118import com.android.systemui.EventLogTags;
119import com.android.systemui.FontSizeUtils;
120import com.android.systemui.R;
121import com.android.systemui.doze.DozeHost;
122import com.android.systemui.doze.DozeLog;
123import com.android.systemui.keyguard.KeyguardViewMediator;
124import com.android.systemui.qs.QSPanel;
125import com.android.systemui.statusbar.ActivatableNotificationView;
126import com.android.systemui.statusbar.BackDropView;
127import com.android.systemui.statusbar.BaseStatusBar;
128import com.android.systemui.statusbar.CommandQueue;
129import com.android.systemui.statusbar.DismissView;
130import com.android.systemui.statusbar.DragDownHelper;
131import com.android.systemui.statusbar.EmptyShadeView;
132import com.android.systemui.statusbar.ExpandableNotificationRow;
133import com.android.systemui.statusbar.GestureRecorder;
134import com.android.systemui.statusbar.KeyguardIndicationController;
135import com.android.systemui.statusbar.NotificationData;
136import com.android.systemui.statusbar.NotificationData.Entry;
137import com.android.systemui.statusbar.NotificationOverflowContainer;
138import com.android.systemui.statusbar.ScrimView;
139import com.android.systemui.statusbar.SignalClusterView;
140import com.android.systemui.statusbar.SpeedBumpView;
141import com.android.systemui.statusbar.StatusBarIconView;
142import com.android.systemui.statusbar.StatusBarState;
143import com.android.systemui.statusbar.policy.AccessibilityController;
144import com.android.systemui.statusbar.policy.BatteryController;
145import com.android.systemui.statusbar.policy.BatteryController.BatteryStateChangeCallback;
146import com.android.systemui.statusbar.policy.BluetoothControllerImpl;
147import com.android.systemui.statusbar.policy.BrightnessMirrorController;
148import com.android.systemui.statusbar.policy.CastControllerImpl;
149import com.android.systemui.statusbar.policy.FlashlightController;
150import com.android.systemui.statusbar.policy.HeadsUpNotificationView;
151import com.android.systemui.statusbar.policy.HotspotControllerImpl;
152import com.android.systemui.statusbar.policy.KeyButtonView;
153import com.android.systemui.statusbar.policy.KeyguardMonitor;
154import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
155import com.android.systemui.statusbar.policy.LocationControllerImpl;
156import com.android.systemui.statusbar.policy.NetworkControllerImpl;
157import com.android.systemui.statusbar.policy.NextAlarmController;
158import com.android.systemui.statusbar.policy.PreviewInflater;
159import com.android.systemui.statusbar.policy.RotationLockControllerImpl;
160import com.android.systemui.statusbar.policy.SecurityControllerImpl;
161import com.android.systemui.statusbar.policy.UserInfoController;
162import com.android.systemui.statusbar.policy.UserSwitcherController;
163import com.android.systemui.statusbar.policy.ZenModeController;
164import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
165import com.android.systemui.statusbar.stack.NotificationStackScrollLayout.OnChildLocationsChangedListener;
166import com.android.systemui.statusbar.stack.StackScrollAlgorithm;
167import com.android.systemui.statusbar.stack.StackScrollState.ViewState;
168import com.android.systemui.volume.VolumeComponent;
169
170import java.io.FileDescriptor;
171import java.io.PrintWriter;
172import java.util.ArrayList;
173import java.util.Collection;
174import java.util.Collections;
175import java.util.List;
176
177public class PhoneStatusBar extends BaseStatusBar implements DemoMode,
178        DragDownHelper.DragDownCallback, ActivityStarter {
179    static final String TAG = "PhoneStatusBar";
180    public static final boolean DEBUG = BaseStatusBar.DEBUG;
181    public static final boolean SPEW = false;
182    public static final boolean DUMPTRUCK = true; // extra dumpsys info
183    public static final boolean DEBUG_GESTURES = false;
184    public static final boolean DEBUG_MEDIA = false;
185    public static final boolean DEBUG_MEDIA_FAKE_ARTWORK = false;
186    public static final boolean DEBUG_EMPTY_KEYGUARD = true;
187
188    public static final boolean DEBUG_WINDOW_STATE = false;
189
190    // additional instrumentation for testing purposes; intended to be left on during development
191    public static final boolean CHATTY = DEBUG;
192
193    public static final String ACTION_STATUSBAR_START
194            = "com.android.internal.policy.statusbar.START";
195
196    public static final boolean SHOW_LOCKSCREEN_MEDIA_ARTWORK = true;
197
198    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
199    private static final int MSG_CLOSE_PANELS = 1001;
200    private static final int MSG_OPEN_SETTINGS_PANEL = 1002;
201    // 1020-1040 reserved for BaseStatusBar
202
203    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
204
205    private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10; // see NotificationManagerService
206    private static final int HIDE_ICONS_BELOW_SCORE = Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
207
208    private static final int STATUS_OR_NAV_TRANSIENT =
209            View.STATUS_BAR_TRANSIENT | View.NAVIGATION_BAR_TRANSIENT;
210    private static final long AUTOHIDE_TIMEOUT_MS = 3000;
211
212    /** The minimum delay in ms between reports of notification visibility. */
213    private static final int VISIBILITY_REPORT_MIN_DELAY_MS = 500;
214
215    /**
216     * The delay to reset the hint text when the hint animation is finished running.
217     */
218    private static final int HINT_RESET_DELAY_MS = 1200;
219
220    private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
221            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
222            .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
223            .build();
224
225    public static final int FADE_KEYGUARD_START_DELAY = 100;
226    public static final int FADE_KEYGUARD_DURATION = 300;
227
228    /** Allow some time inbetween the long press for back and recents. */
229    private static final int LOCK_TO_APP_GESTURE_TOLERENCE = 200;
230
231    PhoneStatusBarPolicy mIconPolicy;
232
233    // These are no longer handled by the policy, because we need custom strategies for them
234    BluetoothControllerImpl mBluetoothController;
235    SecurityControllerImpl mSecurityController;
236    BatteryController mBatteryController;
237    LocationControllerImpl mLocationController;
238    NetworkControllerImpl mNetworkController;
239    HotspotControllerImpl mHotspotController;
240    RotationLockControllerImpl mRotationLockController;
241    UserInfoController mUserInfoController;
242    ZenModeController mZenModeController;
243    CastControllerImpl mCastController;
244    VolumeComponent mVolumeComponent;
245    KeyguardUserSwitcher mKeyguardUserSwitcher;
246    FlashlightController mFlashlightController;
247    UserSwitcherController mUserSwitcherController;
248    NextAlarmController mNextAlarmController;
249    KeyguardMonitor mKeyguardMonitor;
250    BrightnessMirrorController mBrightnessMirrorController;
251    AccessibilityController mAccessibilityController;
252
253    int mNaturalBarHeight = -1;
254    int mIconSize = -1;
255    int mIconHPadding = -1;
256    Display mDisplay;
257    Point mCurrentDisplaySize = new Point();
258
259    StatusBarWindowView mStatusBarWindow;
260    PhoneStatusBarView mStatusBarView;
261    private int mStatusBarWindowState = WINDOW_STATE_SHOWING;
262    private StatusBarWindowManager mStatusBarWindowManager;
263    private UnlockMethodCache mUnlockMethodCache;
264    private DozeServiceHost mDozeServiceHost;
265    private boolean mScreenOnComingFromTouch;
266
267    int mPixelFormat;
268    Object mQueueLock = new Object();
269
270    // viewgroup containing the normal contents of the statusbar
271    LinearLayout mStatusBarContents;
272
273    // right-hand icons
274    LinearLayout mSystemIconArea;
275    LinearLayout mSystemIcons;
276
277    // left-hand icons
278    LinearLayout mStatusIcons;
279    LinearLayout mStatusIconsKeyguard;
280
281    // the icons themselves
282    IconMerger mNotificationIcons;
283    View mNotificationIconArea;
284
285    // [+>
286    View mMoreIcon;
287
288    // expanded notifications
289    NotificationPanelView mNotificationPanel; // the sliding/resizing panel within the notification window
290    View mExpandedContents;
291    int mNotificationPanelGravity;
292    int mNotificationPanelMarginBottomPx;
293    float mNotificationPanelMinHeightFrac;
294    TextView mNotificationPanelDebugText;
295
296    // settings
297    View mFlipSettingsView;
298    private QSPanel mQSPanel;
299
300    // top bar
301    StatusBarHeaderView mHeader;
302    KeyguardStatusBarView mKeyguardStatusBar;
303    View mKeyguardStatusView;
304    KeyguardBottomAreaView mKeyguardBottomArea;
305    boolean mLeaveOpenOnKeyguardHide;
306    KeyguardIndicationController mKeyguardIndicationController;
307
308    private boolean mKeyguardFadingAway;
309    private long mKeyguardFadingAwayDelay;
310    private long mKeyguardFadingAwayDuration;
311
312    int mKeyguardMaxNotificationCount;
313
314    // carrier/wifi label
315    private TextView mCarrierLabel;
316    private boolean mCarrierLabelVisible = false;
317    private int mCarrierLabelHeight;
318    private int mStatusBarHeaderHeight;
319
320    private boolean mShowCarrierInPanel = false;
321
322    // position
323    int[] mPositionTmp = new int[2];
324    boolean mExpandedVisible;
325
326    private int mNavigationBarWindowState = WINDOW_STATE_SHOWING;
327
328    // the tracker view
329    int mTrackingPosition; // the position of the top of the tracking view.
330
331    // ticker
332    private boolean mTickerEnabled;
333    private Ticker mTicker;
334    private View mTickerView;
335    private boolean mTicking;
336
337    // Tracking finger for opening/closing.
338    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
339    boolean mTracking;
340    VelocityTracker mVelocityTracker;
341
342    int[] mAbsPos = new int[2];
343    ArrayList<Runnable> mPostCollapseRunnables = new ArrayList<>();
344
345    // for disabling the status bar
346    int mDisabled = 0;
347
348    // tracking calls to View.setSystemUiVisibility()
349    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
350
351    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
352
353    // XXX: gesture research
354    private final GestureRecorder mGestureRec = DEBUG_GESTURES
355        ? new GestureRecorder("/sdcard/statusbar_gestures.dat")
356        : null;
357
358    private int mNavigationIconHints = 0;
359
360    // ensure quick settings is disabled until the current user makes it through the setup wizard
361    private boolean mUserSetup = false;
362    private ContentObserver mUserSetupObserver = new ContentObserver(new Handler()) {
363        @Override
364        public void onChange(boolean selfChange) {
365            final boolean userSetup = 0 != Settings.Secure.getIntForUser(
366                    mContext.getContentResolver(),
367                    Settings.Secure.USER_SETUP_COMPLETE,
368                    0 /*default */,
369                    mCurrentUserId);
370            if (MULTIUSER_DEBUG) Log.d(TAG, String.format("User setup changed: " +
371                    "selfChange=%s userSetup=%s mUserSetup=%s",
372                    selfChange, userSetup, mUserSetup));
373
374            if (userSetup != mUserSetup) {
375                mUserSetup = userSetup;
376                if (!mUserSetup && mStatusBarView != null)
377                    animateCollapseQuickSettings();
378            }
379        }
380    };
381
382    final private ContentObserver mHeadsUpObserver = new ContentObserver(mHandler) {
383        @Override
384        public void onChange(boolean selfChange) {
385            boolean wasUsing = mUseHeadsUp;
386            mUseHeadsUp = ENABLE_HEADS_UP && !mDisableNotificationAlerts
387                    && Settings.Global.HEADS_UP_OFF != Settings.Global.getInt(
388                    mContext.getContentResolver(), Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED,
389                    Settings.Global.HEADS_UP_OFF);
390            mHeadsUpTicker = mUseHeadsUp && 0 != Settings.Global.getInt(
391                    mContext.getContentResolver(), SETTING_HEADS_UP_TICKER, 0);
392            Log.d(TAG, "heads up is " + (mUseHeadsUp ? "enabled" : "disabled"));
393            if (wasUsing != mUseHeadsUp) {
394                if (!mUseHeadsUp) {
395                    Log.d(TAG, "dismissing any existing heads up notification on disable event");
396                    setHeadsUpVisibility(false);
397                    mHeadsUpNotificationView.release();
398                    removeHeadsUpView();
399                } else {
400                    addHeadsUpView();
401                }
402            }
403        }
404    };
405
406    private int mInteractingWindows;
407    private boolean mAutohideSuspended;
408    private int mStatusBarMode;
409    private int mNavigationBarMode;
410    private Boolean mScreenOn;
411
412    // The second field is a bit different from the first one because it only listens to screen on/
413    // screen of events from Keyguard. We need this so we don't have a race condition with the
414    // broadcast. In the future, we should remove the first field altogether and rename the second
415    // field.
416    private boolean mScreenOnFromKeyguard;
417
418    private ViewMediatorCallback mKeyguardViewMediatorCallback;
419    private ScrimController mScrimController;
420
421    private final Runnable mAutohide = new Runnable() {
422        @Override
423        public void run() {
424            int requested = mSystemUiVisibility & ~STATUS_OR_NAV_TRANSIENT;
425            if (mSystemUiVisibility != requested) {
426                notifyUiVisibilityChanged(requested);
427            }
428        }};
429
430    private boolean mVisible;
431    private boolean mWaitingForKeyguardExit;
432    private boolean mDozing;
433    private boolean mScrimSrcModeEnabled;
434
435    private Interpolator mLinearOutSlowIn;
436    private Interpolator mLinearInterpolator = new LinearInterpolator();
437    private Interpolator mBackdropInterpolator = new AccelerateDecelerateInterpolator();
438    public static final Interpolator ALPHA_IN = new PathInterpolator(0.4f, 0f, 1f, 1f);
439    public static final Interpolator ALPHA_OUT = new PathInterpolator(0f, 0f, 0.8f, 1f);
440
441    private BackDropView mBackdrop;
442    private ImageView mBackdropFront, mBackdropBack;
443    private PorterDuffXfermode mSrcXferMode = new PorterDuffXfermode(PorterDuff.Mode.SRC);
444    private PorterDuffXfermode mSrcOverXferMode = new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER);
445
446    private MediaSessionManager mMediaSessionManager;
447    private MediaController mMediaController;
448    private String mMediaNotificationKey;
449    private MediaMetadata mMediaMetadata;
450    private MediaController.Callback mMediaListener
451            = new MediaController.Callback() {
452        @Override
453        public void onPlaybackStateChanged(PlaybackState state) {
454            super.onPlaybackStateChanged(state);
455            if (DEBUG_MEDIA) Log.v(TAG, "DEBUG_MEDIA: onPlaybackStateChanged: " + state);
456        }
457
458        @Override
459        public void onMetadataChanged(MediaMetadata metadata) {
460            super.onMetadataChanged(metadata);
461            if (DEBUG_MEDIA) Log.v(TAG, "DEBUG_MEDIA: onMetadataChanged: " + metadata);
462            mMediaMetadata = metadata;
463            updateMediaMetaData(true);
464        }
465    };
466
467    private final OnChildLocationsChangedListener mOnChildLocationsChangedListener =
468            new OnChildLocationsChangedListener() {
469        @Override
470        public void onChildLocationsChanged(NotificationStackScrollLayout stackScrollLayout) {
471            userActivity();
472        }
473    };
474
475    private int mDisabledUnmodified;
476
477    /** Keys of notifications currently visible to the user. */
478    private final ArraySet<String> mCurrentlyVisibleNotifications = new ArraySet<String>();
479    private long mLastVisibilityReportUptimeMs;
480
481    private final ShadeUpdates mShadeUpdates = new ShadeUpdates();
482
483    private int mDrawCount;
484    private Runnable mLaunchTransitionEndRunnable;
485    private boolean mLaunchTransitionFadingAway;
486    private ExpandableNotificationRow mDraggedDownRow;
487
488    private static final int VISIBLE_LOCATIONS = ViewState.LOCATION_FIRST_CARD
489            | ViewState.LOCATION_TOP_STACK_PEEKING
490            | ViewState.LOCATION_MAIN_AREA
491            | ViewState.LOCATION_BOTTOM_STACK_PEEKING;
492
493    private final OnChildLocationsChangedListener mNotificationLocationsChangedListener =
494            new OnChildLocationsChangedListener() {
495                @Override
496                public void onChildLocationsChanged(
497                        NotificationStackScrollLayout stackScrollLayout) {
498                    if (mHandler.hasCallbacks(mVisibilityReporter)) {
499                        // Visibilities will be reported when the existing
500                        // callback is executed.
501                        return;
502                    }
503                    // Calculate when we're allowed to run the visibility
504                    // reporter. Note that this timestamp might already have
505                    // passed. That's OK, the callback will just be executed
506                    // ASAP.
507                    long nextReportUptimeMs =
508                            mLastVisibilityReportUptimeMs + VISIBILITY_REPORT_MIN_DELAY_MS;
509                    mHandler.postAtTime(mVisibilityReporter, nextReportUptimeMs);
510                }
511            };
512
513    // Tracks notifications currently visible in mNotificationStackScroller and
514    // emits visibility events via NoMan on changes.
515    private final Runnable mVisibilityReporter = new Runnable() {
516        private final ArrayList<String> mTmpNewlyVisibleNotifications = new ArrayList<String>();
517        private final ArrayList<String> mTmpCurrentlyVisibleNotifications = new ArrayList<String>();
518
519        @Override
520        public void run() {
521            mLastVisibilityReportUptimeMs = SystemClock.uptimeMillis();
522
523            // 1. Loop over mNotificationData entries:
524            //   A. Keep list of visible notifications.
525            //   B. Keep list of previously hidden, now visible notifications.
526            // 2. Compute no-longer visible notifications by removing currently
527            //    visible notifications from the set of previously visible
528            //    notifications.
529            // 3. Report newly visible and no-longer visible notifications.
530            // 4. Keep currently visible notifications for next report.
531            ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
532            int N = activeNotifications.size();
533            for (int i = 0; i < N; i++) {
534                Entry entry = activeNotifications.get(i);
535                String key = entry.notification.getKey();
536                boolean previouslyVisible = mCurrentlyVisibleNotifications.contains(key);
537                boolean currentlyVisible =
538                        (mStackScroller.getChildLocation(entry.row) & VISIBLE_LOCATIONS) != 0;
539                if (currentlyVisible) {
540                    // Build new set of visible notifications.
541                    mTmpCurrentlyVisibleNotifications.add(key);
542                }
543                if (!previouslyVisible && currentlyVisible) {
544                    mTmpNewlyVisibleNotifications.add(key);
545                }
546            }
547            ArraySet<String> noLongerVisibleNotifications = mCurrentlyVisibleNotifications;
548            noLongerVisibleNotifications.removeAll(mTmpCurrentlyVisibleNotifications);
549
550            logNotificationVisibilityChanges(
551                    mTmpNewlyVisibleNotifications, noLongerVisibleNotifications);
552
553            mCurrentlyVisibleNotifications.clear();
554            mCurrentlyVisibleNotifications.addAll(mTmpCurrentlyVisibleNotifications);
555
556            mTmpNewlyVisibleNotifications.clear();
557            mTmpCurrentlyVisibleNotifications.clear();
558        }
559    };
560
561    private final View.OnClickListener mOverflowClickListener = new View.OnClickListener() {
562        @Override
563        public void onClick(View v) {
564            goToLockedShade(null);
565        }
566    };
567
568    @Override
569    public void start() {
570        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
571                .getDefaultDisplay();
572        updateDisplaySize();
573        mScrimSrcModeEnabled = mContext.getResources().getBoolean(
574                R.bool.config_status_bar_scrim_behind_use_src);
575        super.start(); // calls createAndAddWindows()
576
577        mMediaSessionManager
578                = (MediaSessionManager) mContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
579        // TODO: use MediaSessionManager.SessionListener to hook us up to future updates
580        // in session state
581
582        addNavigationBar();
583
584        // Lastly, call to the icon policy to install/update all the icons.
585        mIconPolicy = new PhoneStatusBarPolicy(mContext, mCastController);
586        mSettingsObserver.onChange(false); // set up
587
588        mHeadsUpObserver.onChange(true); // set up
589        if (ENABLE_HEADS_UP) {
590            mContext.getContentResolver().registerContentObserver(
591                    Settings.Global.getUriFor(Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED), true,
592                    mHeadsUpObserver);
593            mContext.getContentResolver().registerContentObserver(
594                    Settings.Global.getUriFor(SETTING_HEADS_UP_TICKER), true,
595                    mHeadsUpObserver);
596        }
597        mUnlockMethodCache = UnlockMethodCache.getInstance(mContext);
598        startKeyguard();
599
600        mDozeServiceHost = new DozeServiceHost();
601        putComponent(DozeHost.class, mDozeServiceHost);
602        putComponent(PhoneStatusBar.class, this);
603
604        setControllerUsers();
605
606        notifyUserAboutHiddenNotifications();
607    }
608
609    // ================================================================================
610    // Constructing the view
611    // ================================================================================
612    protected PhoneStatusBarView makeStatusBarView() {
613        final Context context = mContext;
614
615        Resources res = context.getResources();
616
617        updateDisplaySize(); // populates mDisplayMetrics
618        updateResources();
619
620        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
621
622        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
623                R.layout.super_status_bar, null);
624        mStatusBarWindow.mService = this;
625        mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {
626            @Override
627            public boolean onTouch(View v, MotionEvent event) {
628                checkUserAutohide(v, event);
629                if (event.getAction() == MotionEvent.ACTION_DOWN) {
630                    if (mExpandedVisible) {
631                        animateCollapsePanels();
632                    }
633                }
634                return mStatusBarWindow.onTouchEvent(event);
635            }});
636
637        mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
638        mStatusBarView.setBar(this);
639
640        PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
641        mStatusBarView.setPanelHolder(holder);
642
643        mNotificationPanel = (NotificationPanelView) mStatusBarWindow.findViewById(
644                R.id.notification_panel);
645        mNotificationPanel.setStatusBar(this);
646
647        if (!ActivityManager.isHighEndGfx()) {
648            mStatusBarWindow.setBackground(null);
649            mNotificationPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
650                    R.color.notification_panel_solid_background)));
651        }
652        if (ENABLE_HEADS_UP) {
653            mHeadsUpNotificationView =
654                    (HeadsUpNotificationView) View.inflate(context, R.layout.heads_up, null);
655            mHeadsUpNotificationView.setVisibility(View.GONE);
656            mHeadsUpNotificationView.setBar(this);
657        }
658        if (MULTIUSER_DEBUG) {
659            mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(
660                    R.id.header_debug_info);
661            mNotificationPanelDebugText.setVisibility(View.VISIBLE);
662        }
663
664        updateShowSearchHoldoff();
665
666        try {
667            boolean showNav = mWindowManagerService.hasNavigationBar();
668            if (DEBUG) Log.v(TAG, "hasNavigationBar=" + showNav);
669            if (showNav) {
670                mNavigationBarView =
671                    (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
672
673                mNavigationBarView.setDisabledFlags(mDisabled);
674                mNavigationBarView.setBar(this);
675                mNavigationBarView.setOnVerticalChangedListener(
676                        new NavigationBarView.OnVerticalChangedListener() {
677                    @Override
678                    public void onVerticalChanged(boolean isVertical) {
679                        if (mSearchPanelView != null) {
680                            mSearchPanelView.setHorizontal(isVertical);
681                        }
682                        mNotificationPanel.setQsScrimEnabled(!isVertical);
683                    }
684                });
685                mNavigationBarView.setOnTouchListener(new View.OnTouchListener() {
686                    @Override
687                    public boolean onTouch(View v, MotionEvent event) {
688                        checkUserAutohide(v, event);
689                        return false;
690                    }});
691            }
692        } catch (RemoteException ex) {
693            // no window manager? good luck with that
694        }
695
696        // figure out which pixel-format to use for the status bar.
697        mPixelFormat = PixelFormat.OPAQUE;
698
699        mSystemIconArea = (LinearLayout) mStatusBarView.findViewById(R.id.system_icon_area);
700        mSystemIcons = (LinearLayout) mStatusBarView.findViewById(R.id.system_icons);
701        mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
702        mNotificationIconArea = mStatusBarView.findViewById(R.id.notification_icon_area_inner);
703        mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
704        mMoreIcon = mStatusBarView.findViewById(R.id.moreIcon);
705        mNotificationIcons.setOverflowIndicator(mMoreIcon);
706        mStatusBarContents = (LinearLayout)mStatusBarView.findViewById(R.id.status_bar_contents);
707
708        mStackScroller = (NotificationStackScrollLayout) mStatusBarWindow.findViewById(
709                R.id.notification_stack_scroller);
710        mStackScroller.setLongPressListener(getNotificationLongClicker());
711        mStackScroller.setPhoneStatusBar(this);
712
713        mKeyguardIconOverflowContainer =
714                (NotificationOverflowContainer) LayoutInflater.from(mContext).inflate(
715                        R.layout.status_bar_notification_keyguard_overflow, mStackScroller, false);
716        mKeyguardIconOverflowContainer.setOnActivatedListener(this);
717        mKeyguardIconOverflowContainer.setOnClickListener(mOverflowClickListener);
718        mStackScroller.addView(mKeyguardIconOverflowContainer);
719
720        SpeedBumpView speedBump = (SpeedBumpView) LayoutInflater.from(mContext).inflate(
721                        R.layout.status_bar_notification_speed_bump, mStackScroller, false);
722        mStackScroller.setSpeedBumpView(speedBump);
723        mEmptyShadeView = (EmptyShadeView) LayoutInflater.from(mContext).inflate(
724                R.layout.status_bar_no_notifications, mStackScroller, false);
725        mStackScroller.setEmptyShadeView(mEmptyShadeView);
726        mDismissView = (DismissView) LayoutInflater.from(mContext).inflate(
727                R.layout.status_bar_notification_dismiss_all, mStackScroller, false);
728        mDismissView.setOnButtonClickListener(new View.OnClickListener() {
729            @Override
730            public void onClick(View v) {
731                clearAllNotifications();
732            }
733        });
734        mStackScroller.setDismissView(mDismissView);
735        mExpandedContents = mStackScroller;
736
737        mBackdrop = (BackDropView) mStatusBarWindow.findViewById(R.id.backdrop);
738        mBackdropFront = (ImageView) mBackdrop.findViewById(R.id.backdrop_front);
739        mBackdropBack = (ImageView) mBackdrop.findViewById(R.id.backdrop_back);
740
741        ScrimView scrimBehind = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_behind);
742        ScrimView scrimInFront = (ScrimView) mStatusBarWindow.findViewById(R.id.scrim_in_front);
743        mScrimController = new ScrimController(scrimBehind, scrimInFront, mScrimSrcModeEnabled);
744        mScrimController.setBackDropView(mBackdrop);
745        mStatusBarView.setScrimController(mScrimController);
746
747        mHeader = (StatusBarHeaderView) mStatusBarWindow.findViewById(R.id.header);
748        mHeader.setActivityStarter(this);
749        mKeyguardStatusBar = (KeyguardStatusBarView) mStatusBarWindow.findViewById(R.id.keyguard_header);
750        mStatusIconsKeyguard = (LinearLayout) mKeyguardStatusBar.findViewById(R.id.statusIcons);
751        mKeyguardStatusView = mStatusBarWindow.findViewById(R.id.keyguard_status_view);
752        mKeyguardBottomArea =
753                (KeyguardBottomAreaView) mStatusBarWindow.findViewById(R.id.keyguard_bottom_area);
754        mKeyguardBottomArea.setActivityStarter(this);
755        mKeyguardIndicationController = new KeyguardIndicationController(mContext,
756                (KeyguardIndicationTextView) mStatusBarWindow.findViewById(
757                        R.id.keyguard_indication_text));
758        mKeyguardBottomArea.setKeyguardIndicationController(mKeyguardIndicationController);
759
760        mTickerEnabled = res.getBoolean(R.bool.enable_ticker);
761        if (mTickerEnabled) {
762            final ViewStub tickerStub = (ViewStub) mStatusBarView.findViewById(R.id.ticker_stub);
763            if (tickerStub != null) {
764                mTickerView = tickerStub.inflate();
765                mTicker = new MyTicker(context, mStatusBarView);
766
767                TickerView tickerView = (TickerView) mStatusBarView.findViewById(R.id.tickerText);
768                tickerView.mTicker = mTicker;
769            }
770        }
771
772        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
773
774        // set the inital view visibility
775        setAreThereNotifications();
776
777        // Other icons
778        mLocationController = new LocationControllerImpl(mContext); // will post a notification
779        mBatteryController = new BatteryController(mContext);
780        mBatteryController.addStateChangedCallback(new BatteryStateChangeCallback() {
781            @Override
782            public void onPowerSaveChanged() {
783                mHandler.post(mCheckBarModes);
784                if (mDozeServiceHost != null) {
785                    mDozeServiceHost.firePowerSaveChanged(mBatteryController.isPowerSave());
786                }
787            }
788            @Override
789            public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
790                // noop
791            }
792        });
793        mNetworkController = new NetworkControllerImpl(mContext);
794        mHotspotController = new HotspotControllerImpl(mContext);
795        mBluetoothController = new BluetoothControllerImpl(mContext);
796        mSecurityController = new SecurityControllerImpl(mContext);
797        if (mContext.getResources().getBoolean(R.bool.config_showRotationLock)) {
798            mRotationLockController = new RotationLockControllerImpl(mContext);
799        }
800        mUserInfoController = new UserInfoController(mContext);
801        mVolumeComponent = getComponent(VolumeComponent.class);
802        mZenModeController = mVolumeComponent.getZenController();
803        mCastController = new CastControllerImpl(mContext);
804        final SignalClusterView signalCluster =
805                (SignalClusterView) mStatusBarView.findViewById(R.id.signal_cluster);
806        final SignalClusterView signalClusterKeyguard =
807                (SignalClusterView) mKeyguardStatusBar.findViewById(R.id.signal_cluster);
808        final SignalClusterView signalClusterQs =
809                (SignalClusterView) mHeader.findViewById(R.id.signal_cluster);
810        mNetworkController.addSignalCluster(signalCluster);
811        mNetworkController.addSignalCluster(signalClusterKeyguard);
812        mNetworkController.addSignalCluster(signalClusterQs);
813        signalCluster.setSecurityController(mSecurityController);
814        signalCluster.setNetworkController(mNetworkController);
815        signalClusterKeyguard.setSecurityController(mSecurityController);
816        signalClusterKeyguard.setNetworkController(mNetworkController);
817        signalClusterQs.setSecurityController(mSecurityController);
818        signalClusterQs.setNetworkController(mNetworkController);
819        final boolean isAPhone = mNetworkController.hasVoiceCallingFeature();
820        if (isAPhone) {
821            mNetworkController.addEmergencyLabelView(mHeader);
822        }
823
824        mCarrierLabel = (TextView)mStatusBarWindow.findViewById(R.id.carrier_label);
825        mShowCarrierInPanel = (mCarrierLabel != null);
826        if (DEBUG) Log.v(TAG, "carrierlabel=" + mCarrierLabel + " show=" + mShowCarrierInPanel);
827        if (mShowCarrierInPanel) {
828            mCarrierLabel.setVisibility(mCarrierLabelVisible ? View.VISIBLE : View.INVISIBLE);
829
830            // for mobile devices, we always show mobile connection info here (SPN/PLMN)
831            // for other devices, we show whatever network is connected
832            if (mNetworkController.hasMobileDataFeature()) {
833                mNetworkController.addMobileLabelView(mCarrierLabel);
834            } else {
835                mNetworkController.addCombinedLabelView(mCarrierLabel);
836            }
837
838            // set up the dynamic hide/show of the label
839            // TODO: uncomment, handle this for the Stack scroller aswell
840//                ((NotificationRowLayout) mStackScroller)
841// .setOnSizeChangedListener(new OnSizeChangedListener() {
842//                @Override
843//                public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {
844//                    updateCarrierLabelVisibility(false);
845        }
846
847        mFlashlightController = new FlashlightController(mContext);
848        mKeyguardBottomArea.setFlashlightController(mFlashlightController);
849        mKeyguardBottomArea.setPhoneStatusBar(this);
850        mAccessibilityController = new AccessibilityController(mContext);
851        mKeyguardBottomArea.setAccessibilityController(mAccessibilityController);
852        mNextAlarmController = new NextAlarmController(mContext);
853        mKeyguardMonitor = new KeyguardMonitor();
854        mUserSwitcherController = new UserSwitcherController(mContext, mKeyguardMonitor);
855
856        mKeyguardUserSwitcher = new KeyguardUserSwitcher(mContext,
857                (ViewStub) mStatusBarWindow.findViewById(R.id.keyguard_user_switcher),
858                mKeyguardStatusBar, mNotificationPanel, mUserSwitcherController);
859
860
861        // Set up the quick settings tile panel
862        mQSPanel = (QSPanel) mStatusBarWindow.findViewById(R.id.quick_settings_panel);
863        if (mQSPanel != null) {
864            final QSTileHost qsh = new QSTileHost(mContext, this,
865                    mBluetoothController, mLocationController, mRotationLockController,
866                    mNetworkController, mZenModeController, mHotspotController,
867                    mCastController, mFlashlightController,
868                    mUserSwitcherController, mKeyguardMonitor,
869                    mSecurityController);
870            mQSPanel.setHost(qsh);
871            mQSPanel.setTiles(qsh.getTiles());
872            mBrightnessMirrorController = new BrightnessMirrorController(mStatusBarWindow);
873            mQSPanel.setBrightnessMirror(mBrightnessMirrorController);
874            mHeader.setQSPanel(mQSPanel);
875            qsh.setCallback(new QSTileHost.Callback() {
876                @Override
877                public void onTilesChanged() {
878                    mQSPanel.setTiles(qsh.getTiles());
879                }
880            });
881        }
882
883        // User info. Trigger first load.
884        mHeader.setUserInfoController(mUserInfoController);
885        mKeyguardStatusBar.setUserInfoController(mUserInfoController);
886        mUserInfoController.reloadUserInfo();
887
888        mHeader.setBatteryController(mBatteryController);
889        ((BatteryMeterView) mStatusBarView.findViewById(R.id.battery)).setBatteryController(
890                mBatteryController);
891        mKeyguardStatusBar.setBatteryController(mBatteryController);
892        mHeader.setNextAlarmController(mNextAlarmController);
893
894        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
895        mBroadcastReceiver.onReceive(mContext,
896                new Intent(pm.isScreenOn() ? Intent.ACTION_SCREEN_ON : Intent.ACTION_SCREEN_OFF));
897
898        // receive broadcasts
899        IntentFilter filter = new IntentFilter();
900        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
901        filter.addAction(Intent.ACTION_SCREEN_OFF);
902        filter.addAction(Intent.ACTION_SCREEN_ON);
903        if (DEBUG_MEDIA_FAKE_ARTWORK) {
904            filter.addAction("fake_artwork");
905        }
906        filter.addAction(ACTION_DEMO);
907        context.registerReceiver(mBroadcastReceiver, filter);
908
909        // listen for USER_SETUP_COMPLETE setting (per-user)
910        resetUserSetupObserver();
911
912        startGlyphRasterizeHack();
913        return mStatusBarView;
914    }
915
916    private void clearAllNotifications() {
917
918        // animate-swipe all dismissable notifications, then animate the shade closed
919        int numChildren = mStackScroller.getChildCount();
920
921        final ArrayList<View> viewsToHide = new ArrayList<View>(numChildren);
922        for (int i = 0; i < numChildren; i++) {
923            final View child = mStackScroller.getChildAt(i);
924            if (mStackScroller.canChildBeDismissed(child)) {
925                if (child.getVisibility() == View.VISIBLE) {
926                    viewsToHide.add(child);
927                }
928            }
929        }
930        if (viewsToHide.isEmpty()) {
931            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
932            return;
933        }
934
935        addPostCollapseAction(new Runnable() {
936            @Override
937            public void run() {
938                try {
939                    mBarService.onClearAllNotifications(mCurrentUserId);
940                } catch (Exception ex) { }
941            }
942        });
943
944        performDismissAllAnimations(viewsToHide);
945
946    }
947
948    private void performDismissAllAnimations(ArrayList<View> hideAnimatedList) {
949        Runnable animationFinishAction = new Runnable() {
950            @Override
951            public void run() {
952                mStackScroller.post(new Runnable() {
953                    @Override
954                    public void run() {
955                        mStackScroller.setDismissAllInProgress(false);
956                    }
957                });
958                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
959            }
960        };
961
962        // let's disable our normal animations
963        mStackScroller.setDismissAllInProgress(true);
964
965        // Decrease the delay for every row we animate to give the sense of
966        // accelerating the swipes
967        int rowDelayDecrement = 10;
968        int currentDelay = 140;
969        int totalDelay = 0;
970        int numItems = hideAnimatedList.size();
971        for (int i = 0; i < numItems; i++) {
972            View view = hideAnimatedList.get(i);
973            Runnable endRunnable = null;
974            if (i == numItems - 1) {
975                endRunnable = animationFinishAction;
976            }
977            mStackScroller.dismissViewAnimated(view, endRunnable, totalDelay, 260);
978            currentDelay = Math.max(50, currentDelay - rowDelayDecrement);
979            totalDelay += currentDelay;
980        }
981    }
982
983    /**
984     * Hack to improve glyph rasterization for scaled text views.
985     */
986    private void startGlyphRasterizeHack() {
987        mStatusBarView.getViewTreeObserver().addOnPreDrawListener(
988                new ViewTreeObserver.OnPreDrawListener() {
989            @Override
990            public boolean onPreDraw() {
991                if (mDrawCount == 1) {
992                    mStatusBarView.getViewTreeObserver().removeOnPreDrawListener(this);
993                    HardwareCanvas.setProperty("extraRasterBucket",
994                            Float.toString(StackScrollAlgorithm.DIMMED_SCALE));
995                    HardwareCanvas.setProperty("extraRasterBucket", Float.toString(
996                            mContext.getResources().getDimensionPixelSize(
997                                    R.dimen.qs_time_collapsed_size)
998                            / mContext.getResources().getDimensionPixelSize(
999                                    R.dimen.qs_time_expanded_size)));
1000                }
1001                mDrawCount++;
1002                return true;
1003            }
1004        });
1005    }
1006
1007    @Override
1008    protected void setZenMode(int mode) {
1009        super.setZenMode(mode);
1010        if (mIconPolicy != null) {
1011            mIconPolicy.setZenMode(mode);
1012        }
1013    }
1014
1015    private void startKeyguard() {
1016        KeyguardViewMediator keyguardViewMediator = getComponent(KeyguardViewMediator.class);
1017        mStatusBarKeyguardViewManager = keyguardViewMediator.registerStatusBar(this,
1018                mStatusBarWindow, mStatusBarWindowManager, mScrimController);
1019        mKeyguardViewMediatorCallback = keyguardViewMediator.getViewMediatorCallback();
1020    }
1021
1022    @Override
1023    protected View getStatusBarView() {
1024        return mStatusBarView;
1025    }
1026
1027    public StatusBarWindowView getStatusBarWindow() {
1028        return mStatusBarWindow;
1029    }
1030
1031    @Override
1032    protected WindowManager.LayoutParams getSearchLayoutParams(LayoutParams layoutParams) {
1033        boolean opaque = false;
1034        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1035                LayoutParams.MATCH_PARENT,
1036                LayoutParams.MATCH_PARENT,
1037                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
1038                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1039                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
1040                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1041                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
1042        if (ActivityManager.isHighEndGfx()) {
1043            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1044        }
1045        lp.gravity = Gravity.BOTTOM | Gravity.START;
1046        lp.setTitle("SearchPanel");
1047        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
1048        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
1049        return lp;
1050    }
1051
1052    @Override
1053    protected void updateSearchPanel() {
1054        super.updateSearchPanel();
1055        if (mNavigationBarView != null) {
1056            mNavigationBarView.setDelegateView(mSearchPanelView);
1057        }
1058    }
1059
1060    @Override
1061    public void showSearchPanel() {
1062        super.showSearchPanel();
1063        mHandler.removeCallbacks(mShowSearchPanel);
1064
1065        // we want to freeze the sysui state wherever it is
1066        mSearchPanelView.setSystemUiVisibility(mSystemUiVisibility);
1067
1068        if (mNavigationBarView != null) {
1069            WindowManager.LayoutParams lp =
1070                (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
1071            lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
1072            mWindowManager.updateViewLayout(mNavigationBarView, lp);
1073        }
1074    }
1075
1076    @Override
1077    public void hideSearchPanel() {
1078        super.hideSearchPanel();
1079        if (mNavigationBarView != null) {
1080            WindowManager.LayoutParams lp =
1081                (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
1082            lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
1083            mWindowManager.updateViewLayout(mNavigationBarView, lp);
1084        }
1085    }
1086
1087    public int getStatusBarHeight() {
1088        if (mNaturalBarHeight < 0) {
1089            final Resources res = mContext.getResources();
1090            mNaturalBarHeight =
1091                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
1092        }
1093        return mNaturalBarHeight;
1094    }
1095
1096    private View.OnClickListener mRecentsClickListener = new View.OnClickListener() {
1097        public void onClick(View v) {
1098            awakenDreams();
1099            toggleRecentApps();
1100        }
1101    };
1102
1103    private long mLastLockToAppLongPress;
1104    private View.OnLongClickListener mLongPressBackRecentsListener =
1105            new View.OnLongClickListener() {
1106        @Override
1107        public boolean onLongClick(View v) {
1108            handleLongPressBackRecents(v);
1109            return true;
1110        }
1111    };
1112
1113    private int mShowSearchHoldoff = 0;
1114    private Runnable mShowSearchPanel = new Runnable() {
1115        public void run() {
1116            showSearchPanel();
1117            awakenDreams();
1118        }
1119    };
1120
1121    View.OnTouchListener mHomeActionListener = new View.OnTouchListener() {
1122        public boolean onTouch(View v, MotionEvent event) {
1123            switch(event.getAction()) {
1124                case MotionEvent.ACTION_DOWN:
1125                if (!shouldDisableNavbarGestures()) {
1126                    mHandler.removeCallbacks(mShowSearchPanel);
1127                    mHandler.postDelayed(mShowSearchPanel, mShowSearchHoldoff);
1128                }
1129            break;
1130
1131            case MotionEvent.ACTION_UP:
1132            case MotionEvent.ACTION_CANCEL:
1133                mHandler.removeCallbacks(mShowSearchPanel);
1134                awakenDreams();
1135            break;
1136        }
1137        return false;
1138        }
1139    };
1140
1141    private void awakenDreams() {
1142        if (mDreamManager != null) {
1143            try {
1144                mDreamManager.awaken();
1145            } catch (RemoteException e) {
1146                // fine, stay asleep then
1147            }
1148        }
1149    }
1150
1151    private void prepareNavigationBarView() {
1152        mNavigationBarView.reorient();
1153
1154        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
1155        mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPreloadOnTouchListener);
1156        mNavigationBarView.getRecentsButton().setLongClickable(true);
1157        mNavigationBarView.getRecentsButton().setOnLongClickListener(mLongPressBackRecentsListener);
1158        mNavigationBarView.getBackButton().setLongClickable(true);
1159        mNavigationBarView.getBackButton().setOnLongClickListener(mLongPressBackRecentsListener);
1160        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeActionListener);
1161        updateSearchPanel();
1162    }
1163
1164    // For small-screen devices (read: phones) that lack hardware navigation buttons
1165    private void addNavigationBar() {
1166        if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
1167        if (mNavigationBarView == null) return;
1168
1169        prepareNavigationBarView();
1170
1171        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
1172    }
1173
1174    private void repositionNavigationBar() {
1175        if (mNavigationBarView == null || !mNavigationBarView.isAttachedToWindow()) return;
1176
1177        prepareNavigationBarView();
1178
1179        mWindowManager.updateViewLayout(mNavigationBarView, getNavigationBarLayoutParams());
1180    }
1181
1182    private void notifyNavigationBarScreenOn(boolean screenOn) {
1183        if (mNavigationBarView == null) return;
1184        mNavigationBarView.notifyScreenOn(screenOn);
1185    }
1186
1187    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
1188        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1189                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
1190                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
1191                    0
1192                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1193                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1194                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1195                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
1196                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1197                PixelFormat.TRANSLUCENT);
1198        // this will allow the navbar to run in an overlay on devices that support this
1199        if (ActivityManager.isHighEndGfx()) {
1200            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1201        }
1202
1203        lp.setTitle("NavigationBar");
1204        lp.windowAnimations = 0;
1205        return lp;
1206    }
1207
1208    private void addHeadsUpView() {
1209        int headsUpHeight = mContext.getResources()
1210                .getDimensionPixelSize(R.dimen.heads_up_window_height);
1211        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1212                LayoutParams.MATCH_PARENT, headsUpHeight,
1213                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, // above the status bar!
1214                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1215                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1216                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1217                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1218                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
1219                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1220                PixelFormat.TRANSLUCENT);
1221        lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1222        lp.gravity = Gravity.TOP;
1223        lp.setTitle("Heads Up");
1224        lp.packageName = mContext.getPackageName();
1225        lp.windowAnimations = R.style.Animation_StatusBar_HeadsUp;
1226
1227        mWindowManager.addView(mHeadsUpNotificationView, lp);
1228    }
1229
1230    private void removeHeadsUpView() {
1231        mWindowManager.removeView(mHeadsUpNotificationView);
1232    }
1233
1234    public void refreshAllStatusBarIcons() {
1235        refreshAllIconsForLayout(mStatusIcons);
1236        refreshAllIconsForLayout(mStatusIconsKeyguard);
1237        refreshAllIconsForLayout(mNotificationIcons);
1238    }
1239
1240    private void refreshAllIconsForLayout(LinearLayout ll) {
1241        final int count = ll.getChildCount();
1242        for (int n = 0; n < count; n++) {
1243            View child = ll.getChildAt(n);
1244            if (child instanceof StatusBarIconView) {
1245                ((StatusBarIconView) child).updateDrawable();
1246            }
1247        }
1248    }
1249
1250    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
1251        if (SPEW) Log.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
1252                + " icon=" + icon);
1253        StatusBarIconView view = new StatusBarIconView(mContext, slot, null);
1254        view.set(icon);
1255        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(
1256                LayoutParams.WRAP_CONTENT, mIconSize));
1257        view = new StatusBarIconView(mContext, slot, null);
1258        view.set(icon);
1259        mStatusIconsKeyguard.addView(view, viewIndex, new LinearLayout.LayoutParams(
1260                LayoutParams.WRAP_CONTENT, mIconSize));
1261    }
1262
1263    public void updateIcon(String slot, int index, int viewIndex,
1264            StatusBarIcon old, StatusBarIcon icon) {
1265        if (SPEW) Log.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
1266                + " old=" + old + " icon=" + icon);
1267        StatusBarIconView view = (StatusBarIconView) mStatusIcons.getChildAt(viewIndex);
1268        view.set(icon);
1269        view = (StatusBarIconView) mStatusIconsKeyguard.getChildAt(viewIndex);
1270        view.set(icon);
1271    }
1272
1273    public void removeIcon(String slot, int index, int viewIndex) {
1274        if (SPEW) Log.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
1275        mStatusIcons.removeViewAt(viewIndex);
1276        mStatusIconsKeyguard.removeViewAt(viewIndex);
1277    }
1278
1279    public UserHandle getCurrentUserHandle() {
1280        return new UserHandle(mCurrentUserId);
1281    }
1282
1283    @Override
1284    public void addNotification(StatusBarNotification notification, RankingMap ranking) {
1285        if (DEBUG) Log.d(TAG, "addNotification key=" + notification.getKey());
1286        if (mUseHeadsUp && shouldInterrupt(notification)) {
1287            if (DEBUG) Log.d(TAG, "launching notification in heads up mode");
1288            Entry interruptionCandidate = new Entry(notification, null);
1289            ViewGroup holder = mHeadsUpNotificationView.getHolder();
1290            if (inflateViewsForHeadsUp(interruptionCandidate, holder)) {
1291                // 1. Populate mHeadsUpNotificationView
1292                mHeadsUpNotificationView.showNotification(interruptionCandidate);
1293
1294                // do not show the notification in the shade, yet.
1295                return;
1296            }
1297        }
1298
1299        Entry shadeEntry = createNotificationViews(notification);
1300        if (shadeEntry == null) {
1301            return;
1302        }
1303
1304        if (notification.getNotification().fullScreenIntent != null) {
1305            // Stop screensaver if the notification has a full-screen intent.
1306            // (like an incoming phone call)
1307            awakenDreams();
1308
1309            // not immersive & a full-screen alert should be shown
1310            if (DEBUG) Log.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
1311            try {
1312                notification.getNotification().fullScreenIntent.send();
1313            } catch (PendingIntent.CanceledException e) {
1314            }
1315        } else {
1316            // usual case: status bar visible & not immersive
1317
1318            // show the ticker if there isn't already a heads up
1319            if (mHeadsUpNotificationView.getEntry() == null) {
1320                tick(notification, true);
1321            }
1322        }
1323        addNotificationViews(shadeEntry, ranking);
1324        // Recalculate the position of the sliding windows and the titles.
1325        setAreThereNotifications();
1326        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1327    }
1328
1329    public void displayNotificationFromHeadsUp(StatusBarNotification notification) {
1330        NotificationData.Entry shadeEntry = createNotificationViews(notification);
1331        if (shadeEntry == null) {
1332            return;
1333        }
1334        shadeEntry.setInterruption();
1335
1336        addNotificationViews(shadeEntry, null);
1337        // Recalculate the position of the sliding windows and the titles.
1338        setAreThereNotifications();
1339        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1340    }
1341
1342    @Override
1343    public void resetHeadsUpDecayTimer() {
1344        mHandler.removeMessages(MSG_DECAY_HEADS_UP);
1345        if (mUseHeadsUp && mHeadsUpNotificationDecay > 0
1346                && mHeadsUpNotificationView.isClearable()) {
1347            mHandler.sendEmptyMessageDelayed(MSG_DECAY_HEADS_UP, mHeadsUpNotificationDecay);
1348        }
1349    }
1350
1351    @Override
1352    public void scheduleHeadsUpOpen() {
1353        mHandler.sendEmptyMessage(MSG_SHOW_HEADS_UP);
1354    }
1355
1356    @Override
1357    public void scheduleHeadsUpClose() {
1358        mHandler.sendEmptyMessage(MSG_HIDE_HEADS_UP);
1359    }
1360
1361    @Override
1362    public void scheduleHeadsUpEscalation() {
1363        mHandler.sendEmptyMessage(MSG_ESCALATE_HEADS_UP);
1364    }
1365
1366    @Override
1367    protected void updateNotificationRanking(RankingMap ranking) {
1368        mNotificationData.updateRanking(ranking);
1369        updateNotifications();
1370    }
1371
1372    @Override
1373    public void removeNotification(String key, RankingMap ranking) {
1374        if (ENABLE_HEADS_UP && mHeadsUpNotificationView.getEntry() != null
1375                && key.equals(mHeadsUpNotificationView.getEntry().notification.getKey())) {
1376            mHeadsUpNotificationView.clear();
1377        }
1378
1379        StatusBarNotification old = removeNotificationViews(key, ranking);
1380        if (SPEW) Log.d(TAG, "removeNotification key=" + key + " old=" + old);
1381
1382        if (old != null) {
1383            // Cancel the ticker if it's still running
1384            if (mTickerEnabled) {
1385                mTicker.removeEntry(old);
1386            }
1387
1388            // Recalculate the position of the sliding windows and the titles.
1389            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1390
1391            if (CLOSE_PANEL_WHEN_EMPTIED && !hasActiveNotifications()
1392                    && !mNotificationPanel.isTracking() && !mNotificationPanel.isQsExpanded()) {
1393                if (mState == StatusBarState.SHADE) {
1394                    animateCollapsePanels();
1395                } else if (mState == StatusBarState.SHADE_LOCKED) {
1396                    goToKeyguard();
1397                }
1398            }
1399        }
1400        setAreThereNotifications();
1401    }
1402
1403    @Override
1404    protected void refreshLayout(int layoutDirection) {
1405        if (mNavigationBarView != null) {
1406            mNavigationBarView.setLayoutDirection(layoutDirection);
1407        }
1408        refreshAllStatusBarIcons();
1409    }
1410
1411    private void updateShowSearchHoldoff() {
1412        mShowSearchHoldoff = mContext.getResources().getInteger(
1413            R.integer.config_show_search_delay);
1414    }
1415
1416    private void updateNotificationShade() {
1417        if (mStackScroller == null) return;
1418
1419        // Do not modify the notifications during collapse.
1420        if (isCollapsing()) {
1421            addPostCollapseAction(new Runnable() {
1422                @Override
1423                public void run() {
1424                    updateNotificationShade();
1425                }
1426            });
1427            return;
1428        }
1429
1430        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1431        ArrayList<ExpandableNotificationRow> toShow = new ArrayList<>(activeNotifications.size());
1432        final int N = activeNotifications.size();
1433        for (int i=0; i<N; i++) {
1434            Entry ent = activeNotifications.get(i);
1435            int vis = ent.notification.getNotification().visibility;
1436
1437            // Display public version of the notification if we need to redact.
1438            final boolean hideSensitive =
1439                    !userAllowsPrivateNotificationsInPublic(ent.notification.getUserId());
1440            boolean sensitiveNote = vis == Notification.VISIBILITY_PRIVATE;
1441            boolean sensitivePackage = packageHasVisibilityOverride(ent.notification.getKey());
1442            boolean sensitive = (sensitiveNote && hideSensitive) || sensitivePackage;
1443            boolean showingPublic = sensitive && isLockscreenPublicMode();
1444            ent.row.setSensitive(sensitive);
1445            if (ent.autoRedacted && ent.legacy) {
1446                // TODO: Also fade this? Or, maybe easier (and better), provide a dark redacted form
1447                // for legacy auto redacted notifications.
1448                if (showingPublic) {
1449                    ent.row.setShowingLegacyBackground(false);
1450                } else {
1451                    ent.row.setShowingLegacyBackground(true);
1452                }
1453            }
1454            toShow.add(ent.row);
1455        }
1456
1457        ArrayList<View> toRemove = new ArrayList<View>();
1458        for (int i=0; i< mStackScroller.getChildCount(); i++) {
1459            View child = mStackScroller.getChildAt(i);
1460            if (!toShow.contains(child) && child instanceof ExpandableNotificationRow) {
1461                toRemove.add(child);
1462            }
1463        }
1464
1465        for (View remove : toRemove) {
1466            mStackScroller.removeView(remove);
1467        }
1468        for (int i=0; i<toShow.size(); i++) {
1469            View v = toShow.get(i);
1470            if (v.getParent() == null) {
1471                mStackScroller.addView(v);
1472            }
1473        }
1474
1475        // So after all this work notifications still aren't sorted correctly.
1476        // Let's do that now by advancing through toShow and mStackScroller in
1477        // lock-step, making sure mStackScroller matches what we see in toShow.
1478        int j = 0;
1479        for (int i = 0; i < mStackScroller.getChildCount(); i++) {
1480            View child = mStackScroller.getChildAt(i);
1481            if (!(child instanceof ExpandableNotificationRow)) {
1482                // We don't care about non-notification views.
1483                continue;
1484            }
1485
1486            if (child == toShow.get(j)) {
1487                // Everything is well, advance both lists.
1488                j++;
1489                continue;
1490            }
1491
1492            // Oops, wrong notification at this position. Put the right one
1493            // here and advance both lists.
1494            mStackScroller.changeViewPosition(toShow.get(j), i);
1495            j++;
1496        }
1497        updateRowStates();
1498        updateSpeedbump();
1499        updateClearAll();
1500        updateEmptyShadeView();
1501
1502        // Disable QS if device not provisioned.
1503        // If the user switcher is simple then disable QS during setup because
1504        // the user intends to use the lock screen user switcher, QS in not needed.
1505        mNotificationPanel.setQsExpansionEnabled(isDeviceProvisioned()
1506                && (!mUserSwitcherController.isSimpleUserSwitcher() || mUserSetup));
1507        mShadeUpdates.check();
1508    }
1509
1510    private boolean packageHasVisibilityOverride(String key) {
1511        return mNotificationData.getVisibilityOverride(key)
1512                != NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE;
1513    }
1514
1515    private void updateClearAll() {
1516        boolean showDismissView =
1517                mState != StatusBarState.KEYGUARD &&
1518                mNotificationData.hasActiveClearableNotifications();
1519        mStackScroller.updateDismissView(showDismissView);
1520    }
1521
1522    private void updateEmptyShadeView() {
1523        boolean showEmptyShade =
1524                mState != StatusBarState.KEYGUARD &&
1525                        mNotificationData.getActiveNotifications().size() == 0;
1526        mNotificationPanel.setShadeEmpty(showEmptyShade);
1527    }
1528
1529    private void updateSpeedbump() {
1530        int speedbumpIndex = -1;
1531        int currentIndex = 0;
1532        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1533        final int N = activeNotifications.size();
1534        for (int i = 0; i < N; i++) {
1535            Entry entry = activeNotifications.get(i);
1536            if (entry.row.getVisibility() != View.GONE &&
1537                    mNotificationData.isAmbient(entry.key)) {
1538                speedbumpIndex = currentIndex;
1539                break;
1540            }
1541            currentIndex++;
1542        }
1543        mStackScroller.updateSpeedBumpIndex(speedbumpIndex);
1544    }
1545
1546    @Override
1547    protected void updateNotifications() {
1548        // TODO: Move this into updateNotificationIcons()?
1549        if (mNotificationIcons == null) return;
1550
1551        mNotificationData.filterAndSort();
1552
1553        updateNotificationShade();
1554        updateNotificationIcons();
1555    }
1556
1557    private void updateNotificationIcons() {
1558        final LinearLayout.LayoutParams params
1559            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
1560
1561        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1562        final int N = activeNotifications.size();
1563        ArrayList<StatusBarIconView> toShow = new ArrayList<>(N);
1564
1565        // Filter out notifications with low scores.
1566        for (int i = 0; i < N; i++) {
1567            Entry ent = activeNotifications.get(i);
1568            if (ent.notification.getScore() < HIDE_ICONS_BELOW_SCORE &&
1569                    !NotificationData.showNotificationEvenIfUnprovisioned(ent.notification)) {
1570                continue;
1571            }
1572            toShow.add(ent.icon);
1573        }
1574
1575        if (DEBUG) {
1576            Log.d(TAG, "refreshing icons: " + toShow.size() +
1577                    " notifications, mNotificationIcons=" + mNotificationIcons);
1578        }
1579
1580        ArrayList<View> toRemove = new ArrayList<View>();
1581        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
1582            View child = mNotificationIcons.getChildAt(i);
1583            if (!toShow.contains(child)) {
1584                toRemove.add(child);
1585            }
1586        }
1587
1588        final int toRemoveCount = toRemove.size();
1589        for (int i = 0; i < toRemoveCount; i++) {
1590            mNotificationIcons.removeView(toRemove.get(i));
1591        }
1592
1593        for (int i=0; i<toShow.size(); i++) {
1594            View v = toShow.get(i);
1595            if (v.getParent() == null) {
1596                mNotificationIcons.addView(v, i, params);
1597            }
1598        }
1599
1600        // Resort notification icons
1601        final int childCount = mNotificationIcons.getChildCount();
1602        for (int i = 0; i < childCount; i++) {
1603            View actual = mNotificationIcons.getChildAt(i);
1604            StatusBarIconView expected = toShow.get(i);
1605            if (actual == expected) {
1606                continue;
1607            }
1608            mNotificationIcons.removeView(expected);
1609            mNotificationIcons.addView(expected, i);
1610        }
1611    }
1612
1613    @Override
1614    protected void updateRowStates() {
1615        super.updateRowStates();
1616        mNotificationPanel.notifyVisibleChildrenChanged();
1617    }
1618
1619    protected void updateCarrierLabelVisibility(boolean force) {
1620        // TODO: Handle this for the notification stack scroller as well
1621        if (!mShowCarrierInPanel) return;
1622        // The idea here is to only show the carrier label when there is enough room to see it,
1623        // i.e. when there aren't enough notifications to fill the panel.
1624        if (SPEW) {
1625            Log.d(TAG, String.format("stackScrollerh=%d scrollh=%d carrierh=%d",
1626                    mStackScroller.getHeight(), mStackScroller.getHeight(),
1627                    mCarrierLabelHeight));
1628        }
1629
1630        // Emergency calls only is shown in the expanded header now.
1631        final boolean emergencyCallsShownElsewhere = true;
1632        final boolean makeVisible =
1633            !(emergencyCallsShownElsewhere && mNetworkController.isEmergencyOnly())
1634            && mStackScroller.getHeight() < (mNotificationPanel.getHeight()
1635                    - mCarrierLabelHeight - mStatusBarHeaderHeight)
1636            && mStackScroller.getVisibility() == View.VISIBLE
1637            && mState != StatusBarState.KEYGUARD;
1638
1639        if (force || mCarrierLabelVisible != makeVisible) {
1640            mCarrierLabelVisible = makeVisible;
1641            if (DEBUG) {
1642                Log.d(TAG, "making carrier label " + (makeVisible?"visible":"invisible"));
1643            }
1644            mCarrierLabel.animate().cancel();
1645            if (makeVisible) {
1646                mCarrierLabel.setVisibility(View.VISIBLE);
1647            }
1648            mCarrierLabel.animate()
1649                .alpha(makeVisible ? 1f : 0f)
1650                //.setStartDelay(makeVisible ? 500 : 0)
1651                //.setDuration(makeVisible ? 750 : 100)
1652                .setDuration(150)
1653                .setListener(makeVisible ? null : new AnimatorListenerAdapter() {
1654                    @Override
1655                    public void onAnimationEnd(Animator animation) {
1656                        if (!mCarrierLabelVisible) { // race
1657                            mCarrierLabel.setVisibility(View.INVISIBLE);
1658                            mCarrierLabel.setAlpha(0f);
1659                        }
1660                    }
1661                })
1662                .start();
1663        }
1664    }
1665
1666    @Override
1667    protected void setAreThereNotifications() {
1668
1669        if (SPEW) {
1670            final boolean clearable = hasActiveNotifications() &&
1671                    mNotificationData.hasActiveClearableNotifications();
1672            Log.d(TAG, "setAreThereNotifications: N=" +
1673                    mNotificationData.getActiveNotifications().size() + " any=" +
1674                    hasActiveNotifications() + " clearable=" + clearable);
1675        }
1676
1677        final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
1678        final boolean showDot = hasActiveNotifications() && !areLightsOn();
1679        if (showDot != (nlo.getAlpha() == 1.0f)) {
1680            if (showDot) {
1681                nlo.setAlpha(0f);
1682                nlo.setVisibility(View.VISIBLE);
1683            }
1684            nlo.animate()
1685                .alpha(showDot?1:0)
1686                .setDuration(showDot?750:250)
1687                .setInterpolator(new AccelerateInterpolator(2.0f))
1688                .setListener(showDot ? null : new AnimatorListenerAdapter() {
1689                    @Override
1690                    public void onAnimationEnd(Animator _a) {
1691                        nlo.setVisibility(View.GONE);
1692                    }
1693                })
1694                .start();
1695        }
1696
1697        findAndUpdateMediaNotifications();
1698
1699        updateCarrierLabelVisibility(false);
1700    }
1701
1702    public void findAndUpdateMediaNotifications() {
1703        boolean metaDataChanged = false;
1704
1705        synchronized (mNotificationData) {
1706            ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
1707            final int N = activeNotifications.size();
1708            Entry mediaNotification = null;
1709            MediaController controller = null;
1710            for (int i = 0; i < N; i++) {
1711                final Entry entry = activeNotifications.get(i);
1712                if (isMediaNotification(entry)) {
1713                    final MediaSession.Token token = entry.notification.getNotification().extras
1714                            .getParcelable(Notification.EXTRA_MEDIA_SESSION);
1715                    if (token != null) {
1716                        controller = new MediaController(mContext, token);
1717                        if (controller != null) {
1718                            // we've got a live one, here
1719                            mediaNotification = entry;
1720                        }
1721                    }
1722                }
1723            }
1724
1725            if (mediaNotification == null) {
1726                // Still nothing? OK, let's just look for live media sessions and see if they match
1727                // one of our notifications. This will catch apps that aren't (yet!) using media
1728                // notifications.
1729
1730                if (mMediaSessionManager != null) {
1731                    final List<MediaController> sessions
1732                            = mMediaSessionManager.getActiveSessionsForUser(
1733                                    null,
1734                                    UserHandle.USER_ALL);
1735
1736                    for (MediaController aController : sessions) {
1737                        if (aController == null) continue;
1738                        final PlaybackState state = aController.getPlaybackState();
1739                        if (state == null) continue;
1740                        switch (state.getState()) {
1741                            case PlaybackState.STATE_STOPPED:
1742                            case PlaybackState.STATE_ERROR:
1743                                continue;
1744                            default:
1745                                // now to see if we have one like this
1746                                final String pkg = aController.getPackageName();
1747
1748                                for (int i = 0; i < N; i++) {
1749                                    final Entry entry = activeNotifications.get(i);
1750                                    if (entry.notification.getPackageName().equals(pkg)) {
1751                                        if (DEBUG_MEDIA) {
1752                                            Log.v(TAG, "DEBUG_MEDIA: found controller matching "
1753                                                + entry.notification.getKey());
1754                                        }
1755                                        controller = aController;
1756                                        mediaNotification = entry;
1757                                        break;
1758                                    }
1759                                }
1760                        }
1761                    }
1762                }
1763            }
1764
1765            if (!sameSessions(mMediaController, controller)) {
1766                // We have a new media session
1767
1768                if (mMediaController != null) {
1769                    // something old was playing
1770                    Log.v(TAG, "DEBUG_MEDIA: Disconnecting from old controller: "
1771                            + mMediaController);
1772                    mMediaController.unregisterCallback(mMediaListener);
1773                }
1774                mMediaController = controller;
1775
1776                if (mMediaController != null) {
1777                    mMediaController.registerCallback(mMediaListener);
1778                    mMediaMetadata = mMediaController.getMetadata();
1779                    if (DEBUG_MEDIA) {
1780                        Log.v(TAG, "DEBUG_MEDIA: insert listener, receive metadata: "
1781                                + mMediaMetadata);
1782                    }
1783
1784                    final String notificationKey = mediaNotification == null
1785                            ? null
1786                            : mediaNotification.notification.getKey();
1787
1788                    if (notificationKey == null || !notificationKey.equals(mMediaNotificationKey)) {
1789                        // we have a new notification!
1790                        if (DEBUG_MEDIA) {
1791                            Log.v(TAG, "DEBUG_MEDIA: Found new media notification: key="
1792                                    + notificationKey + " controller=" + controller);
1793                        }
1794                        mMediaNotificationKey = notificationKey;
1795                    }
1796                } else {
1797                    mMediaMetadata = null;
1798                    mMediaNotificationKey = null;
1799                }
1800
1801                metaDataChanged = true;
1802            } else {
1803                // Media session unchanged
1804
1805                if (DEBUG_MEDIA) {
1806                    Log.v(TAG, "DEBUG_MEDIA: Continuing media notification: key=" + mMediaNotificationKey);
1807                }
1808            }
1809        }
1810
1811        updateMediaMetaData(metaDataChanged);
1812    }
1813
1814    private boolean sameSessions(MediaController a, MediaController b) {
1815        if (a == b) return true;
1816        if (a == null) return false;
1817        return a.controlsSameSession(b);
1818    }
1819
1820    /**
1821     * Hide the album artwork that is fading out and release its bitmap.
1822     */
1823    private Runnable mHideBackdropFront = new Runnable() {
1824        @Override
1825        public void run() {
1826            if (DEBUG_MEDIA) {
1827                Log.v(TAG, "DEBUG_MEDIA: removing fade layer");
1828            }
1829            mBackdropFront.setVisibility(View.INVISIBLE);
1830            mBackdropFront.animate().cancel();
1831            mBackdropFront.setImageDrawable(null);
1832        }
1833    };
1834
1835    /**
1836     * Refresh or remove lockscreen artwork from media metadata.
1837     */
1838    public void updateMediaMetaData(boolean metaDataChanged) {
1839        if (!SHOW_LOCKSCREEN_MEDIA_ARTWORK) return;
1840
1841        if (mBackdrop == null) return; // called too early
1842
1843        if (DEBUG_MEDIA) {
1844            Log.v(TAG, "DEBUG_MEDIA: updating album art for notification " + mMediaNotificationKey
1845                + " metadata=" + mMediaMetadata
1846                + " metaDataChanged=" + metaDataChanged
1847                + " state=" + mState);
1848        }
1849
1850        Bitmap artworkBitmap = null;
1851        if (mMediaMetadata != null) {
1852            artworkBitmap = mMediaMetadata.getBitmap(MediaMetadata.METADATA_KEY_ART);
1853            if (artworkBitmap == null) {
1854                artworkBitmap = mMediaMetadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
1855                // might still be null
1856            }
1857        }
1858
1859        final boolean hasArtwork = artworkBitmap != null;
1860
1861        if ((hasArtwork || DEBUG_MEDIA_FAKE_ARTWORK)
1862                && (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED)) {
1863            // time to show some art!
1864            if (mBackdrop.getVisibility() != View.VISIBLE) {
1865                mBackdrop.setVisibility(View.VISIBLE);
1866                mBackdrop.animate().alpha(1f);
1867                metaDataChanged = true;
1868                if (DEBUG_MEDIA) {
1869                    Log.v(TAG, "DEBUG_MEDIA: Fading in album artwork");
1870                }
1871            }
1872            if (metaDataChanged) {
1873                if (mBackdropBack.getDrawable() != null) {
1874                    Drawable drawable = mBackdropBack.getDrawable();
1875                    mBackdropFront.setImageDrawable(drawable);
1876                    if (mScrimSrcModeEnabled) {
1877                        mBackdropFront.getDrawable().mutate().setXfermode(mSrcOverXferMode);
1878                    }
1879                    mBackdropFront.setAlpha(1f);
1880                    mBackdropFront.setVisibility(View.VISIBLE);
1881                } else {
1882                    mBackdropFront.setVisibility(View.INVISIBLE);
1883                }
1884
1885                if (DEBUG_MEDIA_FAKE_ARTWORK) {
1886                    final int c = 0xFF000000 | (int)(Math.random() * 0xFFFFFF);
1887                    Log.v(TAG, String.format("DEBUG_MEDIA: setting new color: 0x%08x", c));
1888                    mBackdropBack.setBackgroundColor(0xFFFFFFFF);
1889                    mBackdropBack.setImageDrawable(new ColorDrawable(c));
1890                } else {
1891                    mBackdropBack.setImageBitmap(artworkBitmap);
1892                }
1893                if (mScrimSrcModeEnabled) {
1894                    mBackdropBack.getDrawable().mutate().setXfermode(mSrcXferMode);
1895                }
1896
1897                if (mBackdropFront.getVisibility() == View.VISIBLE) {
1898                    if (DEBUG_MEDIA) {
1899                        Log.v(TAG, "DEBUG_MEDIA: Crossfading album artwork from "
1900                                + mBackdropFront.getDrawable()
1901                                + " to "
1902                                + mBackdropBack.getDrawable());
1903                    }
1904                    mBackdropFront.animate()
1905                            .setDuration(250)
1906                            .alpha(0f).withEndAction(mHideBackdropFront);
1907                }
1908            }
1909        } else {
1910            // need to hide the album art, either because we are unlocked or because
1911            // the metadata isn't there to support it
1912            if (mBackdrop.getVisibility() != View.GONE) {
1913                if (DEBUG_MEDIA) {
1914                    Log.v(TAG, "DEBUG_MEDIA: Fading out album artwork");
1915                }
1916                mBackdrop.animate()
1917                        .alpha(0f)
1918                        .setInterpolator(mBackdropInterpolator)
1919                        .setDuration(300)
1920                        .setStartDelay(0)
1921                        .withEndAction(new Runnable() {
1922                            @Override
1923                            public void run() {
1924                                mBackdrop.setVisibility(View.GONE);
1925                                mBackdropFront.animate().cancel();
1926                                mBackdropBack.animate().cancel();
1927                                mHandler.post(mHideBackdropFront);
1928                            }
1929                        });
1930                if (mKeyguardFadingAway) {
1931                    mBackdrop.animate()
1932
1933                            // Make it disappear faster, as the focus should be on the activity behind.
1934                            .setDuration(mKeyguardFadingAwayDuration / 2)
1935                            .setStartDelay(mKeyguardFadingAwayDelay)
1936                            .setInterpolator(mLinearInterpolator)
1937                            .start();
1938                }
1939            }
1940        }
1941    }
1942
1943    public void showClock(boolean show) {
1944        if (mStatusBarView == null) return;
1945        View clock = mStatusBarView.findViewById(R.id.clock);
1946        if (clock != null) {
1947            clock.setVisibility(show ? View.VISIBLE : View.GONE);
1948        }
1949    }
1950
1951    private int adjustDisableFlags(int state) {
1952        if (!mLaunchTransitionFadingAway
1953                && (mExpandedVisible || mBouncerShowing || mWaitingForKeyguardExit)) {
1954            state |= StatusBarManager.DISABLE_NOTIFICATION_ICONS;
1955            state |= StatusBarManager.DISABLE_SYSTEM_INFO;
1956        }
1957        return state;
1958    }
1959
1960    /**
1961     * State is one or more of the DISABLE constants from StatusBarManager.
1962     */
1963    public void disable(int state, boolean animate) {
1964        mDisabledUnmodified = state;
1965        state = adjustDisableFlags(state);
1966        final int old = mDisabled;
1967        final int diff = state ^ old;
1968        mDisabled = state;
1969
1970        if (DEBUG) {
1971            Log.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
1972                old, state, diff));
1973        }
1974
1975        StringBuilder flagdbg = new StringBuilder();
1976        flagdbg.append("disable: < ");
1977        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
1978        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
1979        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
1980        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
1981        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
1982        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
1983        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
1984        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
1985        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
1986        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
1987        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
1988        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
1989        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
1990        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
1991        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
1992        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
1993        flagdbg.append(((state & StatusBarManager.DISABLE_SEARCH) != 0) ? "SEARCH" : "search");
1994        flagdbg.append(((diff  & StatusBarManager.DISABLE_SEARCH) != 0) ? "* " : " ");
1995        flagdbg.append(">");
1996        Log.d(TAG, flagdbg.toString());
1997
1998        if ((diff & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1999            mSystemIconArea.animate().cancel();
2000            if ((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
2001                animateStatusBarHide(mSystemIconArea, animate);
2002            } else {
2003                animateStatusBarShow(mSystemIconArea, animate);
2004            }
2005        }
2006
2007        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
2008            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
2009            showClock(show);
2010        }
2011        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
2012            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
2013                animateCollapsePanels();
2014            }
2015        }
2016
2017        if ((diff & (StatusBarManager.DISABLE_HOME
2018                        | StatusBarManager.DISABLE_RECENT
2019                        | StatusBarManager.DISABLE_BACK
2020                        | StatusBarManager.DISABLE_SEARCH)) != 0) {
2021            // the nav bar will take care of these
2022            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
2023
2024            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
2025                // close recents if it's visible
2026                mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
2027                mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
2028            }
2029        }
2030
2031        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2032            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2033                if (mTicking) {
2034                    haltTicker();
2035                }
2036                animateStatusBarHide(mNotificationIconArea, animate);
2037            } else {
2038                animateStatusBarShow(mNotificationIconArea, animate);
2039            }
2040        }
2041
2042        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
2043            mDisableNotificationAlerts =
2044                    (state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0;
2045            mHeadsUpObserver.onChange(true);
2046        }
2047    }
2048
2049    /**
2050     * Animates {@code v}, a view that is part of the status bar, out.
2051     */
2052    private void animateStatusBarHide(final View v, boolean animate) {
2053        v.animate().cancel();
2054        if (!animate) {
2055            v.setAlpha(0f);
2056            v.setVisibility(View.INVISIBLE);
2057            return;
2058        }
2059        v.animate()
2060                .alpha(0f)
2061                .setDuration(160)
2062                .setStartDelay(0)
2063                .setInterpolator(ALPHA_OUT)
2064                .withEndAction(new Runnable() {
2065                    @Override
2066                    public void run() {
2067                        v.setVisibility(View.INVISIBLE);
2068                    }
2069                });
2070    }
2071
2072    /**
2073     * Animates {@code v}, a view that is part of the status bar, in.
2074     */
2075    private void animateStatusBarShow(View v, boolean animate) {
2076        v.animate().cancel();
2077        v.setVisibility(View.VISIBLE);
2078        if (!animate) {
2079            v.setAlpha(1f);
2080            return;
2081        }
2082        v.animate()
2083                .alpha(1f)
2084                .setDuration(320)
2085                .setInterpolator(ALPHA_IN)
2086                .setStartDelay(50)
2087
2088                // We need to clean up any pending end action from animateStatusBarHide if we call
2089                // both hide and show in the same frame before the animation actually gets started.
2090                // cancel() doesn't really remove the end action.
2091                .withEndAction(null);
2092
2093        // Synchronize the motion with the Keyguard fading if necessary.
2094        if (mKeyguardFadingAway) {
2095            v.animate()
2096                    .setDuration(mKeyguardFadingAwayDuration)
2097                    .setInterpolator(mLinearOutSlowIn)
2098                    .setStartDelay(mKeyguardFadingAwayDelay)
2099                    .start();
2100        }
2101    }
2102
2103    @Override
2104    protected BaseStatusBar.H createHandler() {
2105        return new PhoneStatusBar.H();
2106    }
2107
2108    @Override
2109    public void startActivity(Intent intent, boolean dismissShade) {
2110        startActivityDismissingKeyguard(intent, false, dismissShade);
2111    }
2112
2113    public ScrimController getScrimController() {
2114        return mScrimController;
2115    }
2116
2117    public void setQsExpanded(boolean expanded) {
2118        mStatusBarWindowManager.setQsExpanded(expanded);
2119    }
2120
2121    public boolean isGoingToNotificationShade() {
2122        return mLeaveOpenOnKeyguardHide;
2123    }
2124
2125    public boolean isQsExpanded() {
2126        return mNotificationPanel.isQsExpanded();
2127    }
2128
2129    public boolean isScreenOnComingFromTouch() {
2130        return mScreenOnComingFromTouch;
2131    }
2132
2133    public boolean isFalsingThresholdNeeded() {
2134        boolean onKeyguard = getBarState() == StatusBarState.KEYGUARD;
2135        boolean isMethodInsecure = mUnlockMethodCache.isMethodInsecure();
2136        return onKeyguard && (isMethodInsecure || mDozing || mScreenOnComingFromTouch);
2137    }
2138
2139    @Override  // NotificationData.Environment
2140    public String getCurrentMediaNotificationKey() {
2141        return mMediaNotificationKey;
2142    }
2143
2144    public boolean isScrimSrcModeEnabled() {
2145        return mScrimSrcModeEnabled;
2146    }
2147
2148    /**
2149     * All changes to the status bar and notifications funnel through here and are batched.
2150     */
2151    private class H extends BaseStatusBar.H {
2152        public void handleMessage(Message m) {
2153            super.handleMessage(m);
2154            switch (m.what) {
2155                case MSG_OPEN_NOTIFICATION_PANEL:
2156                    animateExpandNotificationsPanel();
2157                    break;
2158                case MSG_OPEN_SETTINGS_PANEL:
2159                    animateExpandSettingsPanel();
2160                    break;
2161                case MSG_CLOSE_PANELS:
2162                    animateCollapsePanels();
2163                    break;
2164                case MSG_SHOW_HEADS_UP:
2165                    setHeadsUpVisibility(true);
2166                    break;
2167                case MSG_DECAY_HEADS_UP:
2168                    mHeadsUpNotificationView.release();
2169                    setHeadsUpVisibility(false);
2170                    break;
2171                case MSG_HIDE_HEADS_UP:
2172                    mHeadsUpNotificationView.release();
2173                    setHeadsUpVisibility(false);
2174                    break;
2175                case MSG_ESCALATE_HEADS_UP:
2176                    escalateHeadsUp();
2177                    setHeadsUpVisibility(false);
2178                    break;
2179            }
2180        }
2181    }
2182
2183    /**  if the interrupting notification had a fullscreen intent, fire it now.  */
2184    private void escalateHeadsUp() {
2185        if (mHeadsUpNotificationView.getEntry() != null) {
2186            final StatusBarNotification sbn = mHeadsUpNotificationView.getEntry().notification;
2187            mHeadsUpNotificationView.release();
2188            final Notification notification = sbn.getNotification();
2189            if (notification.fullScreenIntent != null) {
2190                if (DEBUG)
2191                    Log.d(TAG, "converting a heads up to fullScreen");
2192                try {
2193                    notification.fullScreenIntent.send();
2194                } catch (PendingIntent.CanceledException e) {
2195                }
2196            }
2197        }
2198    }
2199
2200    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
2201        public void onFocusChange(View v, boolean hasFocus) {
2202            // Because 'v' is a ViewGroup, all its children will be (un)selected
2203            // too, which allows marqueeing to work.
2204            v.setSelected(hasFocus);
2205        }
2206    };
2207
2208    boolean panelsEnabled() {
2209        return (mDisabled & StatusBarManager.DISABLE_EXPAND) == 0;
2210    }
2211
2212    void makeExpandedVisible(boolean force) {
2213        if (SPEW) Log.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
2214        if (!force && (mExpandedVisible || !panelsEnabled())) {
2215            return;
2216        }
2217
2218        mExpandedVisible = true;
2219        if (mNavigationBarView != null)
2220            mNavigationBarView.setSlippery(true);
2221
2222        updateCarrierLabelVisibility(true);
2223
2224        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
2225
2226        // Expand the window to encompass the full screen in anticipation of the drag.
2227        // This is only possible to do atomically because the status bar is at the top of the screen!
2228        mStatusBarWindowManager.setStatusBarExpanded(true);
2229        mStatusBarView.setFocusable(false);
2230
2231        visibilityChanged(true);
2232        mWaitingForKeyguardExit = false;
2233        disable(mDisabledUnmodified, !force /* animate */);
2234        setInteracting(StatusBarManager.WINDOW_STATUS_BAR, true);
2235    }
2236
2237    public void animateCollapsePanels() {
2238        animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
2239    }
2240
2241    private final Runnable mAnimateCollapsePanels = new Runnable() {
2242        @Override
2243        public void run() {
2244            animateCollapsePanels();
2245        }
2246    };
2247
2248    public void postAnimateCollapsePanels() {
2249        mHandler.post(mAnimateCollapsePanels);
2250    }
2251
2252    public void animateCollapsePanels(int flags) {
2253        animateCollapsePanels(flags, false /* force */);
2254    }
2255
2256    public void animateCollapsePanels(int flags, boolean force) {
2257        if (!force &&
2258                (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED)) {
2259            runPostCollapseRunnables();
2260            return;
2261        }
2262        if (SPEW) {
2263            Log.d(TAG, "animateCollapse():"
2264                    + " mExpandedVisible=" + mExpandedVisible
2265                    + " flags=" + flags);
2266        }
2267
2268        if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
2269            if (!mHandler.hasMessages(MSG_HIDE_RECENT_APPS)) {
2270                mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
2271                mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
2272            }
2273        }
2274
2275        if ((flags & CommandQueue.FLAG_EXCLUDE_SEARCH_PANEL) == 0) {
2276            mHandler.removeMessages(MSG_CLOSE_SEARCH_PANEL);
2277            mHandler.sendEmptyMessage(MSG_CLOSE_SEARCH_PANEL);
2278        }
2279
2280        if (mStatusBarWindow != null) {
2281            // release focus immediately to kick off focus change transition
2282            mStatusBarWindowManager.setStatusBarFocusable(false);
2283
2284            mStatusBarWindow.cancelExpandHelper();
2285            if (DEBUG_EMPTY_KEYGUARD) {
2286                Log.i(TAG, "Collapsing panel from animateCollapsePanels:"
2287                        + " force=" + force
2288                        + " mState=" + mState);
2289            }
2290            mStatusBarView.collapseAllPanels(true);
2291        }
2292    }
2293
2294    private void runPostCollapseRunnables() {
2295        int size = mPostCollapseRunnables.size();
2296        for (int i = 0; i < size; i++) {
2297            mPostCollapseRunnables.get(i).run();
2298        }
2299        mPostCollapseRunnables.clear();
2300    }
2301
2302    public ViewPropertyAnimator setVisibilityWhenDone(
2303            final ViewPropertyAnimator a, final View v, final int vis) {
2304        a.setListener(new AnimatorListenerAdapter() {
2305            @Override
2306            public void onAnimationEnd(Animator animation) {
2307                v.setVisibility(vis);
2308                a.setListener(null); // oneshot
2309            }
2310        });
2311        return a;
2312    }
2313
2314    public Animator setVisibilityWhenDone(
2315            final Animator a, final View v, final int vis) {
2316        a.addListener(new AnimatorListenerAdapter() {
2317            @Override
2318            public void onAnimationEnd(Animator animation) {
2319                v.setVisibility(vis);
2320            }
2321        });
2322        return a;
2323    }
2324
2325    public Animator interpolator(TimeInterpolator ti, Animator a) {
2326        a.setInterpolator(ti);
2327        return a;
2328    }
2329
2330    public Animator startDelay(int d, Animator a) {
2331        a.setStartDelay(d);
2332        return a;
2333    }
2334
2335    public Animator start(Animator a) {
2336        a.start();
2337        return a;
2338    }
2339
2340    final TimeInterpolator mAccelerateInterpolator = new AccelerateInterpolator();
2341    final TimeInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
2342    final int FLIP_DURATION_OUT = 125;
2343    final int FLIP_DURATION_IN = 225;
2344    final int FLIP_DURATION = (FLIP_DURATION_IN + FLIP_DURATION_OUT);
2345
2346    Animator mScrollViewAnim, mClearButtonAnim;
2347
2348    @Override
2349    public void animateExpandNotificationsPanel() {
2350        if (SPEW) Log.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
2351        if (!panelsEnabled()) {
2352            return ;
2353        }
2354
2355        mNotificationPanel.expand();
2356
2357        if (false) postStartTracing();
2358    }
2359
2360    @Override
2361    public void animateExpandSettingsPanel() {
2362        if (SPEW) Log.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
2363        if (!panelsEnabled()) {
2364            return;
2365        }
2366
2367        // Settings are not available in setup
2368        if (!mUserSetup) return;
2369
2370        mNotificationPanel.expand();
2371        mNotificationPanel.openQs();
2372
2373        if (false) postStartTracing();
2374    }
2375
2376    public void animateCollapseQuickSettings() {
2377        if (DEBUG_EMPTY_KEYGUARD) {
2378            Log.i(TAG, "Collapsing panel from animateCollapseQuickSettings");
2379        }
2380        mStatusBarView.collapseAllPanels(true);
2381    }
2382
2383    void makeExpandedInvisible() {
2384        if (SPEW) Log.d(TAG, "makeExpandedInvisible: mExpandedVisible=" + mExpandedVisible
2385                + " mExpandedVisible=" + mExpandedVisible);
2386
2387        if (!mExpandedVisible || mStatusBarWindow == null) {
2388            return;
2389        }
2390
2391        // Ensure the panel is fully collapsed (just in case; bug 6765842, 7260868)
2392        if (DEBUG_EMPTY_KEYGUARD) {
2393            Log.i(TAG, "Collapsing panel from makeExpandedInvisible");
2394        }
2395        mStatusBarView.collapseAllPanels(/*animate=*/ false);
2396
2397        // reset things to their proper state
2398        if (mScrollViewAnim != null) mScrollViewAnim.cancel();
2399        if (mClearButtonAnim != null) mClearButtonAnim.cancel();
2400
2401        mStackScroller.setVisibility(View.VISIBLE);
2402        mNotificationPanel.setVisibility(View.GONE);
2403
2404        mNotificationPanel.closeQs();
2405
2406        mExpandedVisible = false;
2407        if (mNavigationBarView != null)
2408            mNavigationBarView.setSlippery(false);
2409        visibilityChanged(false);
2410
2411        // Shrink the window to the size of the status bar only
2412        mStatusBarWindowManager.setStatusBarExpanded(false);
2413        mStatusBarView.setFocusable(true);
2414
2415        // Close any "App info" popups that might have snuck on-screen
2416        dismissPopups();
2417
2418        runPostCollapseRunnables();
2419        setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
2420        showBouncer();
2421        disable(mDisabledUnmodified, true /* animate */);
2422    }
2423
2424    public boolean interceptTouchEvent(MotionEvent event) {
2425        if (DEBUG_GESTURES) {
2426            if (event.getActionMasked() != MotionEvent.ACTION_MOVE) {
2427                EventLog.writeEvent(EventLogTags.SYSUI_STATUSBAR_TOUCH,
2428                        event.getActionMasked(), (int) event.getX(), (int) event.getY(), mDisabled);
2429            }
2430
2431        }
2432
2433        if (SPEW) {
2434            Log.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
2435                + mDisabled + " mTracking=" + mTracking);
2436        } else if (CHATTY) {
2437            if (event.getAction() != MotionEvent.ACTION_MOVE) {
2438                Log.d(TAG, String.format(
2439                            "panel: %s at (%f, %f) mDisabled=0x%08x",
2440                            MotionEvent.actionToString(event.getAction()),
2441                            event.getRawX(), event.getRawY(), mDisabled));
2442            }
2443        }
2444
2445        if (DEBUG_GESTURES) {
2446            mGestureRec.add(event);
2447        }
2448
2449        if (mStatusBarWindowState == WINDOW_STATE_SHOWING) {
2450            final boolean upOrCancel =
2451                    event.getAction() == MotionEvent.ACTION_UP ||
2452                    event.getAction() == MotionEvent.ACTION_CANCEL;
2453            if (upOrCancel && !mExpandedVisible) {
2454                setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
2455            } else {
2456                setInteracting(StatusBarManager.WINDOW_STATUS_BAR, true);
2457            }
2458        }
2459        return false;
2460    }
2461
2462    public GestureRecorder getGestureRecorder() {
2463        return mGestureRec;
2464    }
2465
2466    private void setNavigationIconHints(int hints) {
2467        if (hints == mNavigationIconHints) return;
2468
2469        mNavigationIconHints = hints;
2470
2471        if (mNavigationBarView != null) {
2472            mNavigationBarView.setNavigationIconHints(hints);
2473        }
2474        checkBarModes();
2475    }
2476
2477    @Override // CommandQueue
2478    public void setWindowState(int window, int state) {
2479        boolean showing = state == WINDOW_STATE_SHOWING;
2480        if (mStatusBarWindow != null
2481                && window == StatusBarManager.WINDOW_STATUS_BAR
2482                && mStatusBarWindowState != state) {
2483            mStatusBarWindowState = state;
2484            if (DEBUG_WINDOW_STATE) Log.d(TAG, "Status bar " + windowStateToString(state));
2485            if (!showing) {
2486                if (DEBUG_EMPTY_KEYGUARD) {
2487                    Log.i(TAG, "Collapsing panel from setWindowState");
2488                }
2489                mStatusBarView.collapseAllPanels(false);
2490            }
2491        }
2492        if (mNavigationBarView != null
2493                && window == StatusBarManager.WINDOW_NAVIGATION_BAR
2494                && mNavigationBarWindowState != state) {
2495            mNavigationBarWindowState = state;
2496            if (DEBUG_WINDOW_STATE) Log.d(TAG, "Navigation bar " + windowStateToString(state));
2497        }
2498    }
2499
2500    @Override // CommandQueue
2501    public void buzzBeepBlinked() {
2502        if (mDozeServiceHost != null) {
2503            mDozeServiceHost.fireBuzzBeepBlinked();
2504        }
2505    }
2506
2507    @Override
2508    public void notificationLightOff() {
2509        if (mDozeServiceHost != null) {
2510            mDozeServiceHost.fireNotificationLight(false);
2511        }
2512    }
2513
2514    @Override
2515    public void notificationLightPulse(int argb, int onMillis, int offMillis) {
2516        if (mDozeServiceHost != null) {
2517            mDozeServiceHost.fireNotificationLight(true);
2518        }
2519    }
2520
2521    @Override // CommandQueue
2522    public void setSystemUiVisibility(int vis, int mask) {
2523        final int oldVal = mSystemUiVisibility;
2524        final int newVal = (oldVal&~mask) | (vis&mask);
2525        final int diff = newVal ^ oldVal;
2526        if (DEBUG) Log.d(TAG, String.format(
2527                "setSystemUiVisibility vis=%s mask=%s oldVal=%s newVal=%s diff=%s",
2528                Integer.toHexString(vis), Integer.toHexString(mask),
2529                Integer.toHexString(oldVal), Integer.toHexString(newVal),
2530                Integer.toHexString(diff)));
2531        if (diff != 0) {
2532            // we never set the recents bit via this method, so save the prior state to prevent
2533            // clobbering the bit below
2534            final boolean wasRecentsVisible = (mSystemUiVisibility & View.RECENT_APPS_VISIBLE) > 0;
2535
2536            mSystemUiVisibility = newVal;
2537
2538            // update low profile
2539            if ((diff & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
2540                final boolean lightsOut = (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0;
2541                if (lightsOut) {
2542                    animateCollapsePanels();
2543                    if (mTicking) {
2544                        haltTicker();
2545                    }
2546                }
2547
2548                setAreThereNotifications();
2549            }
2550
2551            // update status bar mode
2552            final int sbMode = computeBarMode(oldVal, newVal, mStatusBarView.getBarTransitions(),
2553                    View.STATUS_BAR_TRANSIENT, View.STATUS_BAR_TRANSLUCENT);
2554
2555            // update navigation bar mode
2556            final int nbMode = mNavigationBarView == null ? -1 : computeBarMode(
2557                    oldVal, newVal, mNavigationBarView.getBarTransitions(),
2558                    View.NAVIGATION_BAR_TRANSIENT, View.NAVIGATION_BAR_TRANSLUCENT);
2559            final boolean sbModeChanged = sbMode != -1;
2560            final boolean nbModeChanged = nbMode != -1;
2561            boolean checkBarModes = false;
2562            if (sbModeChanged && sbMode != mStatusBarMode) {
2563                mStatusBarMode = sbMode;
2564                checkBarModes = true;
2565            }
2566            if (nbModeChanged && nbMode != mNavigationBarMode) {
2567                mNavigationBarMode = nbMode;
2568                checkBarModes = true;
2569            }
2570            if (checkBarModes) {
2571                checkBarModes();
2572            }
2573            if (sbModeChanged || nbModeChanged) {
2574                // update transient bar autohide
2575                if (mStatusBarMode == MODE_SEMI_TRANSPARENT || mNavigationBarMode == MODE_SEMI_TRANSPARENT) {
2576                    scheduleAutohide();
2577                } else {
2578                    cancelAutohide();
2579                }
2580            }
2581
2582            // ready to unhide
2583            if ((vis & View.STATUS_BAR_UNHIDE) != 0) {
2584                mSystemUiVisibility &= ~View.STATUS_BAR_UNHIDE;
2585            }
2586            if ((vis & View.NAVIGATION_BAR_UNHIDE) != 0) {
2587                mSystemUiVisibility &= ~View.NAVIGATION_BAR_UNHIDE;
2588            }
2589
2590            // restore the recents bit
2591            if (wasRecentsVisible) {
2592                mSystemUiVisibility |= View.RECENT_APPS_VISIBLE;
2593            }
2594
2595            // send updated sysui visibility to window manager
2596            notifyUiVisibilityChanged(mSystemUiVisibility);
2597        }
2598    }
2599
2600    private int computeBarMode(int oldVis, int newVis, BarTransitions transitions,
2601            int transientFlag, int translucentFlag) {
2602        final int oldMode = barMode(oldVis, transientFlag, translucentFlag);
2603        final int newMode = barMode(newVis, transientFlag, translucentFlag);
2604        if (oldMode == newMode) {
2605            return -1; // no mode change
2606        }
2607        return newMode;
2608    }
2609
2610    private int barMode(int vis, int transientFlag, int translucentFlag) {
2611        return (vis & transientFlag) != 0 ? MODE_SEMI_TRANSPARENT
2612                : (vis & translucentFlag) != 0 ? MODE_TRANSLUCENT
2613                : (vis & View.SYSTEM_UI_TRANSPARENT) != 0 ? MODE_TRANSPARENT
2614                : (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0 ? MODE_LIGHTS_OUT
2615                : MODE_OPAQUE;
2616    }
2617
2618    private void checkBarModes() {
2619        if (mDemoMode) return;
2620        checkBarMode(mStatusBarMode, mStatusBarWindowState, mStatusBarView.getBarTransitions());
2621        if (mNavigationBarView != null) {
2622            checkBarMode(mNavigationBarMode,
2623                    mNavigationBarWindowState, mNavigationBarView.getBarTransitions());
2624        }
2625    }
2626
2627    private void checkBarMode(int mode, int windowState, BarTransitions transitions) {
2628        final boolean powerSave = mBatteryController.isPowerSave();
2629        final boolean anim = (mScreenOn == null || mScreenOn) && windowState != WINDOW_STATE_HIDDEN
2630                && !powerSave;
2631        if (powerSave && getBarState() == StatusBarState.SHADE) {
2632            mode = MODE_WARNING;
2633        }
2634        transitions.transitionTo(mode, anim);
2635    }
2636
2637    private void finishBarAnimations() {
2638        mStatusBarView.getBarTransitions().finishAnimations();
2639        if (mNavigationBarView != null) {
2640            mNavigationBarView.getBarTransitions().finishAnimations();
2641        }
2642    }
2643
2644    private final Runnable mCheckBarModes = new Runnable() {
2645        @Override
2646        public void run() {
2647            checkBarModes();
2648        }
2649    };
2650
2651    @Override
2652    public void setInteracting(int barWindow, boolean interacting) {
2653        mInteractingWindows = interacting
2654                ? (mInteractingWindows | barWindow)
2655                : (mInteractingWindows & ~barWindow);
2656        if (mInteractingWindows != 0) {
2657            suspendAutohide();
2658        } else {
2659            resumeSuspendedAutohide();
2660        }
2661        checkBarModes();
2662    }
2663
2664    private void resumeSuspendedAutohide() {
2665        if (mAutohideSuspended) {
2666            scheduleAutohide();
2667            mHandler.postDelayed(mCheckBarModes, 500); // longer than home -> launcher
2668        }
2669    }
2670
2671    private void suspendAutohide() {
2672        mHandler.removeCallbacks(mAutohide);
2673        mHandler.removeCallbacks(mCheckBarModes);
2674        mAutohideSuspended = (mSystemUiVisibility & STATUS_OR_NAV_TRANSIENT) != 0;
2675    }
2676
2677    private void cancelAutohide() {
2678        mAutohideSuspended = false;
2679        mHandler.removeCallbacks(mAutohide);
2680    }
2681
2682    private void scheduleAutohide() {
2683        cancelAutohide();
2684        mHandler.postDelayed(mAutohide, AUTOHIDE_TIMEOUT_MS);
2685    }
2686
2687    private void checkUserAutohide(View v, MotionEvent event) {
2688        if ((mSystemUiVisibility & STATUS_OR_NAV_TRANSIENT) != 0  // a transient bar is revealed
2689                && event.getAction() == MotionEvent.ACTION_OUTSIDE // touch outside the source bar
2690                && event.getX() == 0 && event.getY() == 0  // a touch outside both bars
2691                ) {
2692            userAutohide();
2693        }
2694    }
2695
2696    private void userAutohide() {
2697        cancelAutohide();
2698        mHandler.postDelayed(mAutohide, 350); // longer than app gesture -> flag clear
2699    }
2700
2701    private boolean areLightsOn() {
2702        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
2703    }
2704
2705    public void setLightsOn(boolean on) {
2706        Log.v(TAG, "setLightsOn(" + on + ")");
2707        if (on) {
2708            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
2709        } else {
2710            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
2711        }
2712    }
2713
2714    private void notifyUiVisibilityChanged(int vis) {
2715        try {
2716            mWindowManagerService.statusBarVisibilityChanged(vis);
2717        } catch (RemoteException ex) {
2718        }
2719    }
2720
2721    public void topAppWindowChanged(boolean showMenu) {
2722        if (DEBUG) {
2723            Log.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
2724        }
2725        if (mNavigationBarView != null) {
2726            mNavigationBarView.setMenuVisibility(showMenu);
2727        }
2728
2729        // See above re: lights-out policy for legacy apps.
2730        if (showMenu) setLightsOn(true);
2731    }
2732
2733    @Override
2734    public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
2735            boolean showImeSwitcher) {
2736        boolean imeShown = (vis & InputMethodService.IME_VISIBLE) != 0;
2737        int flags = mNavigationIconHints;
2738        if ((backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS) || imeShown) {
2739            flags |= NAVIGATION_HINT_BACK_ALT;
2740        } else {
2741            flags &= ~NAVIGATION_HINT_BACK_ALT;
2742        }
2743        if (showImeSwitcher) {
2744            flags |= NAVIGATION_HINT_IME_SHOWN;
2745        } else {
2746            flags &= ~NAVIGATION_HINT_IME_SHOWN;
2747        }
2748
2749        setNavigationIconHints(flags);
2750    }
2751
2752    @Override
2753    protected void tick(StatusBarNotification n, boolean firstTime) {
2754        if (!mTickerEnabled) return;
2755
2756        // no ticking in lights-out mode
2757        if (!areLightsOn()) return;
2758
2759        // no ticking in Setup
2760        if (!isDeviceProvisioned()) return;
2761
2762        // not for you
2763        if (!isNotificationForCurrentProfiles(n)) return;
2764
2765        // Show the ticker if one is requested. Also don't do this
2766        // until status bar window is attached to the window manager,
2767        // because...  well, what's the point otherwise?  And trying to
2768        // run a ticker without being attached will crash!
2769        if (n.getNotification().tickerText != null && mStatusBarWindow != null
2770                && mStatusBarWindow.getWindowToken() != null) {
2771            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
2772                    | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
2773                mTicker.addEntry(n);
2774            }
2775        }
2776    }
2777
2778    private class MyTicker extends Ticker {
2779        MyTicker(Context context, View sb) {
2780            super(context, sb);
2781            if (!mTickerEnabled) {
2782                Log.w(TAG, "MyTicker instantiated with mTickerEnabled=false", new Throwable());
2783            }
2784        }
2785
2786        @Override
2787        public void tickerStarting() {
2788            if (!mTickerEnabled) return;
2789            mTicking = true;
2790            mStatusBarContents.setVisibility(View.GONE);
2791            mTickerView.setVisibility(View.VISIBLE);
2792            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
2793            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
2794        }
2795
2796        @Override
2797        public void tickerDone() {
2798            if (!mTickerEnabled) return;
2799            mStatusBarContents.setVisibility(View.VISIBLE);
2800            mTickerView.setVisibility(View.GONE);
2801            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
2802            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
2803                        mTickingDoneListener));
2804        }
2805
2806        public void tickerHalting() {
2807            if (!mTickerEnabled) return;
2808            if (mStatusBarContents.getVisibility() != View.VISIBLE) {
2809                mStatusBarContents.setVisibility(View.VISIBLE);
2810                mStatusBarContents
2811                        .startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
2812            }
2813            mTickerView.setVisibility(View.GONE);
2814            // we do not animate the ticker away at this point, just get rid of it (b/6992707)
2815        }
2816    }
2817
2818    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
2819        public void onAnimationEnd(Animation animation) {
2820            mTicking = false;
2821        }
2822        public void onAnimationRepeat(Animation animation) {
2823        }
2824        public void onAnimationStart(Animation animation) {
2825        }
2826    };
2827
2828    private Animation loadAnim(int id, Animation.AnimationListener listener) {
2829        Animation anim = AnimationUtils.loadAnimation(mContext, id);
2830        if (listener != null) {
2831            anim.setAnimationListener(listener);
2832        }
2833        return anim;
2834    }
2835
2836    public static String viewInfo(View v) {
2837        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
2838                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
2839    }
2840
2841    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2842        synchronized (mQueueLock) {
2843            pw.println("Current Status Bar state:");
2844            pw.println("  mExpandedVisible=" + mExpandedVisible
2845                    + ", mTrackingPosition=" + mTrackingPosition);
2846            pw.println("  mTickerEnabled=" + mTickerEnabled);
2847            if (mTickerEnabled) {
2848                pw.println("  mTicking=" + mTicking);
2849                pw.println("  mTickerView: " + viewInfo(mTickerView));
2850            }
2851            pw.println("  mTracking=" + mTracking);
2852            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
2853            pw.println("  mStackScroller: " + viewInfo(mStackScroller));
2854            pw.println("  mStackScroller: " + viewInfo(mStackScroller)
2855                    + " scroll " + mStackScroller.getScrollX()
2856                    + "," + mStackScroller.getScrollY());
2857        }
2858
2859        pw.print("  mInteractingWindows="); pw.println(mInteractingWindows);
2860        pw.print("  mStatusBarWindowState=");
2861        pw.println(windowStateToString(mStatusBarWindowState));
2862        pw.print("  mStatusBarMode=");
2863        pw.println(BarTransitions.modeToString(mStatusBarMode));
2864        pw.print("  mDozing="); pw.println(mDozing);
2865        pw.print("  mZenMode=");
2866        pw.println(Settings.Global.zenModeToString(mZenMode));
2867        pw.print("  mUseHeadsUp=");
2868        pw.println(mUseHeadsUp);
2869        pw.print("  interrupting package: ");
2870        pw.println(hunStateToString(mHeadsUpNotificationView.getEntry()));
2871        dumpBarTransitions(pw, "mStatusBarView", mStatusBarView.getBarTransitions());
2872        if (mNavigationBarView != null) {
2873            pw.print("  mNavigationBarWindowState=");
2874            pw.println(windowStateToString(mNavigationBarWindowState));
2875            pw.print("  mNavigationBarMode=");
2876            pw.println(BarTransitions.modeToString(mNavigationBarMode));
2877            dumpBarTransitions(pw, "mNavigationBarView", mNavigationBarView.getBarTransitions());
2878        }
2879
2880        pw.print("  mNavigationBarView=");
2881        if (mNavigationBarView == null) {
2882            pw.println("null");
2883        } else {
2884            mNavigationBarView.dump(fd, pw, args);
2885        }
2886
2887        pw.print("  mMediaSessionManager=");
2888        pw.println(mMediaSessionManager);
2889        pw.print("  mMediaNotificationKey=");
2890        pw.println(mMediaNotificationKey);
2891        pw.print("  mMediaController=");
2892        pw.print(mMediaController);
2893        if (mMediaController != null) {
2894            pw.print(" state=" + mMediaController.getPlaybackState());
2895        }
2896        pw.println();
2897        pw.print("  mMediaMetadata=");
2898        pw.print(mMediaMetadata);
2899        if (mMediaMetadata != null) {
2900            pw.print(" title=" + mMediaMetadata.getText(MediaMetadata.METADATA_KEY_TITLE));
2901        }
2902        pw.println();
2903
2904        pw.println("  Panels: ");
2905        if (mNotificationPanel != null) {
2906            pw.println("    mNotificationPanel=" +
2907                mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""));
2908            pw.print  ("      ");
2909            mNotificationPanel.dump(fd, pw, args);
2910        }
2911
2912        DozeLog.dump(pw);
2913
2914        if (DUMPTRUCK) {
2915            synchronized (mNotificationData) {
2916                mNotificationData.dump(pw, "  ");
2917            }
2918
2919            int N = mStatusIcons.getChildCount();
2920            pw.println("  system icons: " + N);
2921            for (int i=0; i<N; i++) {
2922                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
2923                pw.println("    [" + i + "] icon=" + ic);
2924            }
2925
2926            if (false) {
2927                pw.println("see the logcat for a dump of the views we have created.");
2928                // must happen on ui thread
2929                mHandler.post(new Runnable() {
2930                        public void run() {
2931                            mStatusBarView.getLocationOnScreen(mAbsPos);
2932                            Log.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
2933                                    + ") " + mStatusBarView.getWidth() + "x"
2934                                    + getStatusBarHeight());
2935                            mStatusBarView.debug();
2936                        }
2937                    });
2938            }
2939        }
2940
2941        if (DEBUG_GESTURES) {
2942            pw.print("  status bar gestures: ");
2943            mGestureRec.dump(fd, pw, args);
2944        }
2945
2946        if (mNetworkController != null) {
2947            mNetworkController.dump(fd, pw, args);
2948        }
2949        if (mBluetoothController != null) {
2950            mBluetoothController.dump(fd, pw, args);
2951        }
2952        if (mCastController != null) {
2953            mCastController.dump(fd, pw, args);
2954        }
2955        if (mUserSwitcherController != null) {
2956            mUserSwitcherController.dump(fd, pw, args);
2957        }
2958        if (mBatteryController != null) {
2959            mBatteryController.dump(fd, pw, args);
2960        }
2961        if (mNextAlarmController != null) {
2962            mNextAlarmController.dump(fd, pw, args);
2963        }
2964        if (mSecurityController != null) {
2965            mSecurityController.dump(fd, pw, args);
2966        }
2967    }
2968
2969    private String hunStateToString(Entry entry) {
2970        if (entry == null) return "null";
2971        if (entry.notification == null) return "corrupt";
2972        return entry.notification.getPackageName();
2973    }
2974
2975    private static void dumpBarTransitions(PrintWriter pw, String var, BarTransitions transitions) {
2976        pw.print("  "); pw.print(var); pw.print(".BarTransitions.mMode=");
2977        pw.println(BarTransitions.modeToString(transitions.getMode()));
2978    }
2979
2980    @Override
2981    public void createAndAddWindows() {
2982        addStatusBarWindow();
2983    }
2984
2985    private void addStatusBarWindow() {
2986        makeStatusBarView();
2987        mStatusBarWindowManager = new StatusBarWindowManager(mContext);
2988        mStatusBarWindowManager.add(mStatusBarWindow, getStatusBarHeight());
2989    }
2990
2991    static final float saturate(float a) {
2992        return a < 0f ? 0f : (a > 1f ? 1f : a);
2993    }
2994
2995    @Override
2996    public void updateExpandedViewPos(int thingy) {
2997        if (SPEW) Log.v(TAG, "updateExpandedViewPos");
2998
2999        // on larger devices, the notification panel is propped open a bit
3000        mNotificationPanel.setMinimumHeight(
3001                (int)(mNotificationPanelMinHeightFrac * mCurrentDisplaySize.y));
3002
3003        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mNotificationPanel.getLayoutParams();
3004        lp.gravity = mNotificationPanelGravity;
3005        mNotificationPanel.setLayoutParams(lp);
3006
3007        updateCarrierLabelVisibility(false);
3008    }
3009
3010    // called by makeStatusbar and also by PhoneStatusBarView
3011    void updateDisplaySize() {
3012        mDisplay.getMetrics(mDisplayMetrics);
3013        mDisplay.getSize(mCurrentDisplaySize);
3014        if (DEBUG_GESTURES) {
3015            mGestureRec.tag("display",
3016                    String.format("%dx%d", mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels));
3017        }
3018    }
3019
3020    public void startActivityDismissingKeyguard(final Intent intent, boolean onlyProvisioned,
3021            final boolean dismissShade) {
3022        if (onlyProvisioned && !isDeviceProvisioned()) return;
3023
3024        final boolean afterKeyguardGone = PreviewInflater.wouldLaunchResolverActivity(
3025                mContext, intent, mCurrentUserId);
3026        final boolean keyguardShowing = mStatusBarKeyguardViewManager.isShowing();
3027        dismissKeyguardThenExecute(new OnDismissAction() {
3028            @Override
3029            public boolean onDismiss() {
3030                AsyncTask.execute(new Runnable() {
3031                    public void run() {
3032                        try {
3033                            if (keyguardShowing && !afterKeyguardGone) {
3034                                ActivityManagerNative.getDefault()
3035                                        .keyguardWaitingForActivityDrawn();
3036                            }
3037                            intent.setFlags(
3038                                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
3039                            mContext.startActivityAsUser(
3040                                    intent, new UserHandle(UserHandle.USER_CURRENT));
3041                            overrideActivityPendingAppTransition(
3042                                    keyguardShowing && !afterKeyguardGone);
3043                        } catch (RemoteException e) {
3044                        }
3045                    }
3046                });
3047                if (dismissShade) {
3048                    if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
3049                        Log.i(TAG, "Collapsing panel startActivityDismissKeyguard after keyguard"
3050                                + "dismiss");
3051                    }
3052                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
3053                }
3054                return true;
3055            }
3056        }, afterKeyguardGone);
3057    }
3058
3059    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
3060        public void onReceive(Context context, Intent intent) {
3061            if (DEBUG) Log.v(TAG, "onReceive: " + intent);
3062            String action = intent.getAction();
3063            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
3064                int flags = CommandQueue.FLAG_EXCLUDE_NONE;
3065                String reason = intent.getStringExtra("reason");
3066                if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
3067                    flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
3068                }
3069                animateCollapsePanels(flags);
3070            }
3071            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
3072                mScreenOn = false;
3073                notifyNavigationBarScreenOn(false);
3074                notifyHeadsUpScreenOn(false);
3075                finishBarAnimations();
3076                stopNotificationLogging();
3077                resetUserExpandedStates();
3078            }
3079            else if (Intent.ACTION_SCREEN_ON.equals(action)) {
3080                mScreenOn = true;
3081                // work around problem where mDisplay.getRotation() is not stable while screen is off (bug 7086018)
3082                repositionNavigationBar();
3083                notifyNavigationBarScreenOn(true);
3084                startNotificationLoggingIfScreenOnAndVisible();
3085            }
3086            else if (ACTION_DEMO.equals(action)) {
3087                Bundle bundle = intent.getExtras();
3088                if (bundle != null) {
3089                    String command = bundle.getString("command", "").trim().toLowerCase();
3090                    if (command.length() > 0) {
3091                        try {
3092                            dispatchDemoCommand(command, bundle);
3093                        } catch (Throwable t) {
3094                            Log.w(TAG, "Error running demo command, intent=" + intent, t);
3095                        }
3096                    }
3097                }
3098            } else if ("fake_artwork".equals(action)) {
3099                if (DEBUG_MEDIA_FAKE_ARTWORK) {
3100                    updateMediaMetaData(true);
3101                }
3102            }
3103        }
3104    };
3105
3106    private void resetUserExpandedStates() {
3107        ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
3108        final int notificationCount = activeNotifications.size();
3109        for (int i = 0; i < notificationCount; i++) {
3110            NotificationData.Entry entry = activeNotifications.get(i);
3111            if (entry.row != null) {
3112                entry.row.resetUserExpansion();
3113            }
3114        }
3115    }
3116
3117    @Override
3118    protected void dismissKeyguardThenExecute(final OnDismissAction action,
3119            boolean afterKeyguardGone) {
3120        if (mStatusBarKeyguardViewManager.isShowing()) {
3121            if (UnlockMethodCache.getInstance(mContext).isMethodInsecure()
3122                    && mNotificationPanel.isLaunchTransitionRunning() && !afterKeyguardGone) {
3123                action.onDismiss();
3124                mNotificationPanel.setLaunchTransitionEndRunnable(new Runnable() {
3125                    @Override
3126                    public void run() {
3127                        mStatusBarKeyguardViewManager.dismiss();
3128                    }
3129                });
3130            } else {
3131                mStatusBarKeyguardViewManager.dismissWithAction(action, afterKeyguardGone);
3132            }
3133        } else {
3134            action.onDismiss();
3135        }
3136    }
3137
3138    // SystemUIService notifies SystemBars of configuration changes, which then calls down here
3139    @Override
3140    protected void onConfigurationChanged(Configuration newConfig) {
3141        super.onConfigurationChanged(newConfig); // calls refreshLayout
3142
3143        if (DEBUG) {
3144            Log.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
3145        }
3146        updateDisplaySize(); // populates mDisplayMetrics
3147
3148        updateResources();
3149        updateClockSize();
3150        repositionNavigationBar();
3151        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
3152        updateShowSearchHoldoff();
3153        updateRowStates();
3154    }
3155
3156    @Override
3157    public void userSwitched(int newUserId) {
3158        if (MULTIUSER_DEBUG) mNotificationPanelDebugText.setText("USER " + newUserId);
3159        animateCollapsePanels();
3160        updateNotifications();
3161        resetUserSetupObserver();
3162        setControllerUsers();
3163    }
3164
3165    private void setControllerUsers() {
3166        if (mZenModeController != null) {
3167            mZenModeController.setUserId(mCurrentUserId);
3168        }
3169    }
3170
3171    private void resetUserSetupObserver() {
3172        mContext.getContentResolver().unregisterContentObserver(mUserSetupObserver);
3173        mUserSetupObserver.onChange(false);
3174        mContext.getContentResolver().registerContentObserver(
3175                Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), true,
3176                mUserSetupObserver,
3177                mCurrentUserId);
3178    }
3179
3180    private void setHeadsUpVisibility(boolean vis) {
3181        if (!ENABLE_HEADS_UP) return;
3182        if (DEBUG) Log.v(TAG, (vis ? "showing" : "hiding") + " heads up window");
3183        EventLog.writeEvent(EventLogTags.SYSUI_HEADS_UP_STATUS,
3184                vis ? mHeadsUpNotificationView.getKey() : "",
3185                vis ? 1 : 0);
3186        mHeadsUpNotificationView.setVisibility(vis ? View.VISIBLE : View.GONE);
3187    }
3188
3189    public void onHeadsUpDismissed() {
3190        mHeadsUpNotificationView.dismiss();
3191    }
3192
3193    /**
3194     * Reload some of our resources when the configuration changes.
3195     *
3196     * We don't reload everything when the configuration changes -- we probably
3197     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
3198     * meantime, just update the things that we know change.
3199     */
3200    void updateResources() {
3201        // Update the quick setting tiles
3202        if (mQSPanel != null) {
3203            mQSPanel.updateResources();
3204        }
3205
3206        loadDimens();
3207        mLinearOutSlowIn = AnimationUtils.loadInterpolator(
3208                mContext, android.R.interpolator.linear_out_slow_in);
3209
3210        if (mNotificationPanel != null) {
3211            mNotificationPanel.updateResources();
3212        }
3213        if (mHeadsUpNotificationView != null) {
3214            mHeadsUpNotificationView.updateResources();
3215        }
3216        if (mBrightnessMirrorController != null) {
3217            mBrightnessMirrorController.updateResources();
3218        }
3219    }
3220
3221    private void updateClockSize() {
3222        if (mStatusBarView == null) return;
3223        TextView clock = (TextView) mStatusBarView.findViewById(R.id.clock);
3224        if (clock != null) {
3225            FontSizeUtils.updateFontSize(clock, R.dimen.status_bar_clock_size);
3226        }
3227    }
3228    protected void loadDimens() {
3229        final Resources res = mContext.getResources();
3230
3231        mNaturalBarHeight = res.getDimensionPixelSize(
3232                com.android.internal.R.dimen.status_bar_height);
3233
3234        int newIconSize = res.getDimensionPixelSize(
3235            com.android.internal.R.dimen.status_bar_icon_size);
3236        int newIconHPadding = res.getDimensionPixelSize(
3237            R.dimen.status_bar_icon_padding);
3238
3239        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
3240//            Log.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
3241            mIconHPadding = newIconHPadding;
3242            mIconSize = newIconSize;
3243            //reloadAllNotificationIcons(); // reload the tray
3244        }
3245
3246        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
3247
3248        mNotificationPanelGravity = res.getInteger(R.integer.notification_panel_layout_gravity);
3249        if (mNotificationPanelGravity <= 0) {
3250            mNotificationPanelGravity = Gravity.START | Gravity.TOP;
3251        }
3252
3253        mCarrierLabelHeight = res.getDimensionPixelSize(R.dimen.carrier_label_height);
3254        mStatusBarHeaderHeight = res.getDimensionPixelSize(R.dimen.status_bar_header_height);
3255
3256        mNotificationPanelMinHeightFrac = res.getFraction(R.dimen.notification_panel_min_height_frac, 1, 1);
3257        if (mNotificationPanelMinHeightFrac < 0f || mNotificationPanelMinHeightFrac > 1f) {
3258            mNotificationPanelMinHeightFrac = 0f;
3259        }
3260
3261        mHeadsUpNotificationDecay = res.getInteger(R.integer.heads_up_notification_decay);
3262        mRowMinHeight =  res.getDimensionPixelSize(R.dimen.notification_min_height);
3263        mRowMaxHeight =  res.getDimensionPixelSize(R.dimen.notification_max_height);
3264
3265        mKeyguardMaxNotificationCount = res.getInteger(R.integer.keyguard_max_notification_count);
3266
3267        if (DEBUG) Log.v(TAG, "updateResources");
3268    }
3269
3270    // Visibility reporting
3271
3272    @Override
3273    protected void visibilityChanged(boolean visible) {
3274        mVisible = visible;
3275        if (visible) {
3276            startNotificationLoggingIfScreenOnAndVisible();
3277        } else {
3278            stopNotificationLogging();
3279        }
3280        super.visibilityChanged(visible);
3281    }
3282
3283    private void stopNotificationLogging() {
3284        // Report all notifications as invisible and turn down the
3285        // reporter.
3286        if (!mCurrentlyVisibleNotifications.isEmpty()) {
3287            logNotificationVisibilityChanges(
3288                    Collections.<String>emptyList(), mCurrentlyVisibleNotifications);
3289            mCurrentlyVisibleNotifications.clear();
3290        }
3291        mHandler.removeCallbacks(mVisibilityReporter);
3292        mStackScroller.setChildLocationsChangedListener(null);
3293    }
3294
3295    private void startNotificationLoggingIfScreenOnAndVisible() {
3296        if (mVisible && mScreenOn) {
3297            mStackScroller.setChildLocationsChangedListener(mNotificationLocationsChangedListener);
3298            // Some transitions like mScreenOn=false -> mScreenOn=true don't
3299            // cause the scroller to emit child location events. Hence generate
3300            // one ourselves to guarantee that we're reporting visible
3301            // notifications.
3302            // (Note that in cases where the scroller does emit events, this
3303            // additional event doesn't break anything.)
3304            mNotificationLocationsChangedListener.onChildLocationsChanged(mStackScroller);
3305        }
3306    }
3307
3308    private void logNotificationVisibilityChanges(
3309            Collection<String> newlyVisible, Collection<String> noLongerVisible) {
3310        if (newlyVisible.isEmpty() && noLongerVisible.isEmpty()) {
3311            return;
3312        }
3313        String[] newlyVisibleAr = newlyVisible.toArray(new String[newlyVisible.size()]);
3314        String[] noLongerVisibleAr = noLongerVisible.toArray(new String[noLongerVisible.size()]);
3315        try {
3316            mBarService.onNotificationVisibilityChanged(newlyVisibleAr, noLongerVisibleAr);
3317        } catch (RemoteException e) {
3318            // Ignore.
3319        }
3320    }
3321
3322    //
3323    // tracing
3324    //
3325
3326    void postStartTracing() {
3327        mHandler.postDelayed(mStartTracing, 3000);
3328    }
3329
3330    void vibrate() {
3331        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
3332                Context.VIBRATOR_SERVICE);
3333        vib.vibrate(250, VIBRATION_ATTRIBUTES);
3334    }
3335
3336    Runnable mStartTracing = new Runnable() {
3337        public void run() {
3338            vibrate();
3339            SystemClock.sleep(250);
3340            Log.d(TAG, "startTracing");
3341            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
3342            mHandler.postDelayed(mStopTracing, 10000);
3343        }
3344    };
3345
3346    Runnable mStopTracing = new Runnable() {
3347        public void run() {
3348            android.os.Debug.stopMethodTracing();
3349            Log.d(TAG, "stopTracing");
3350            vibrate();
3351        }
3352    };
3353
3354    @Override
3355    protected void haltTicker() {
3356        if (mTickerEnabled) {
3357            mTicker.halt();
3358        }
3359    }
3360
3361    @Override
3362    protected boolean shouldDisableNavbarGestures() {
3363        return !isDeviceProvisioned()
3364                || mExpandedVisible
3365                || (mDisabled & StatusBarManager.DISABLE_SEARCH) != 0;
3366    }
3367
3368    public void postStartSettingsActivity(final Intent intent, int delay) {
3369        mHandler.postDelayed(new Runnable() {
3370            @Override
3371            public void run() {
3372                handleStartSettingsActivity(intent, true /*onlyProvisioned*/);
3373            }
3374        }, delay);
3375    }
3376
3377    private void handleStartSettingsActivity(Intent intent, boolean onlyProvisioned) {
3378        startActivityDismissingKeyguard(intent, onlyProvisioned, true /* dismissShade */);
3379    }
3380
3381    private static class FastColorDrawable extends Drawable {
3382        private final int mColor;
3383
3384        public FastColorDrawable(int color) {
3385            mColor = 0xff000000 | color;
3386        }
3387
3388        @Override
3389        public void draw(Canvas canvas) {
3390            canvas.drawColor(mColor, PorterDuff.Mode.SRC);
3391        }
3392
3393        @Override
3394        public void setAlpha(int alpha) {
3395        }
3396
3397        @Override
3398        public void setColorFilter(ColorFilter cf) {
3399        }
3400
3401        @Override
3402        public int getOpacity() {
3403            return PixelFormat.OPAQUE;
3404        }
3405
3406        @Override
3407        public void setBounds(int left, int top, int right, int bottom) {
3408        }
3409
3410        @Override
3411        public void setBounds(Rect bounds) {
3412        }
3413    }
3414
3415    @Override
3416    public void destroy() {
3417        super.destroy();
3418        if (mStatusBarWindow != null) {
3419            mWindowManager.removeViewImmediate(mStatusBarWindow);
3420            mStatusBarWindow = null;
3421        }
3422        if (mNavigationBarView != null) {
3423            mWindowManager.removeViewImmediate(mNavigationBarView);
3424            mNavigationBarView = null;
3425        }
3426        mContext.unregisterReceiver(mBroadcastReceiver);
3427    }
3428
3429    private boolean mDemoModeAllowed;
3430    private boolean mDemoMode;
3431    private DemoStatusIcons mDemoStatusIcons;
3432
3433    @Override
3434    public void dispatchDemoCommand(String command, Bundle args) {
3435        if (!mDemoModeAllowed) {
3436            mDemoModeAllowed = Settings.Global.getInt(mContext.getContentResolver(),
3437                    "sysui_demo_allowed", 0) != 0;
3438        }
3439        if (!mDemoModeAllowed) return;
3440        if (command.equals(COMMAND_ENTER)) {
3441            mDemoMode = true;
3442        } else if (command.equals(COMMAND_EXIT)) {
3443            mDemoMode = false;
3444            checkBarModes();
3445        } else if (!mDemoMode) {
3446            // automatically enter demo mode on first demo command
3447            dispatchDemoCommand(COMMAND_ENTER, new Bundle());
3448        }
3449        boolean modeChange = command.equals(COMMAND_ENTER) || command.equals(COMMAND_EXIT);
3450        if (modeChange || command.equals(COMMAND_CLOCK)) {
3451            dispatchDemoCommandToView(command, args, R.id.clock);
3452        }
3453        if (modeChange || command.equals(COMMAND_BATTERY)) {
3454            dispatchDemoCommandToView(command, args, R.id.battery);
3455        }
3456        if (modeChange || command.equals(COMMAND_STATUS)) {
3457            if (mDemoStatusIcons == null) {
3458                mDemoStatusIcons = new DemoStatusIcons(mStatusIcons, mIconSize);
3459            }
3460            mDemoStatusIcons.dispatchDemoCommand(command, args);
3461        }
3462        if (mNetworkController != null && (modeChange || command.equals(COMMAND_NETWORK))) {
3463            mNetworkController.dispatchDemoCommand(command, args);
3464        }
3465        if (modeChange || command.equals(COMMAND_NOTIFICATIONS)) {
3466            View notifications = mStatusBarView == null ? null
3467                    : mStatusBarView.findViewById(R.id.notification_icon_area);
3468            if (notifications != null) {
3469                String visible = args.getString("visible");
3470                int vis = mDemoMode && "false".equals(visible) ? View.INVISIBLE : View.VISIBLE;
3471                notifications.setVisibility(vis);
3472            }
3473        }
3474        if (command.equals(COMMAND_BARS)) {
3475            String mode = args.getString("mode");
3476            int barMode = "opaque".equals(mode) ? MODE_OPAQUE :
3477                    "translucent".equals(mode) ? MODE_TRANSLUCENT :
3478                    "semi-transparent".equals(mode) ? MODE_SEMI_TRANSPARENT :
3479                    "transparent".equals(mode) ? MODE_TRANSPARENT :
3480                    "warning".equals(mode) ? MODE_WARNING :
3481                    -1;
3482            if (barMode != -1) {
3483                boolean animate = true;
3484                if (mStatusBarView != null) {
3485                    mStatusBarView.getBarTransitions().transitionTo(barMode, animate);
3486                }
3487                if (mNavigationBarView != null) {
3488                    mNavigationBarView.getBarTransitions().transitionTo(barMode, animate);
3489                }
3490            }
3491        }
3492    }
3493
3494    private void dispatchDemoCommandToView(String command, Bundle args, int id) {
3495        if (mStatusBarView == null) return;
3496        View v = mStatusBarView.findViewById(id);
3497        if (v instanceof DemoMode) {
3498            ((DemoMode)v).dispatchDemoCommand(command, args);
3499        }
3500    }
3501
3502    /**
3503     * @return The {@link StatusBarState} the status bar is in.
3504     */
3505    public int getBarState() {
3506        return mState;
3507    }
3508
3509    public void showKeyguard() {
3510        setBarState(StatusBarState.KEYGUARD);
3511        updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
3512        if (!mScreenOnFromKeyguard) {
3513
3514            // If the screen is off already, we need to disable touch events because these might
3515            // collapse the panel after we expanded it, and thus we would end up with a blank
3516            // Keyguard.
3517            mNotificationPanel.setTouchDisabled(true);
3518        }
3519        instantExpandNotificationsPanel();
3520        mLeaveOpenOnKeyguardHide = false;
3521        if (mDraggedDownRow != null) {
3522            mDraggedDownRow.setUserLocked(false);
3523            mDraggedDownRow.notifyHeightChanged();
3524            mDraggedDownRow = null;
3525        }
3526    }
3527
3528    public boolean isCollapsing() {
3529        return mNotificationPanel.isCollapsing();
3530    }
3531
3532    public void addPostCollapseAction(Runnable r) {
3533        mPostCollapseRunnables.add(r);
3534    }
3535
3536    public boolean isInLaunchTransition() {
3537        return mNotificationPanel.isLaunchTransitionRunning()
3538                || mNotificationPanel.isLaunchTransitionFinished();
3539    }
3540
3541    /**
3542     * Fades the content of the keyguard away after the launch transition is done.
3543     *
3544     * @param beforeFading the runnable to be run when the circle is fully expanded and the fading
3545     *                     starts
3546     * @param endRunnable the runnable to be run when the transition is done
3547     */
3548    public void fadeKeyguardAfterLaunchTransition(final Runnable beforeFading,
3549            final Runnable endRunnable) {
3550        Runnable hideRunnable = new Runnable() {
3551            @Override
3552            public void run() {
3553                mLaunchTransitionFadingAway = true;
3554                if (beforeFading != null) {
3555                    beforeFading.run();
3556                }
3557                mNotificationPanel.setAlpha(1);
3558                mNotificationPanel.animate()
3559                        .alpha(0)
3560                        .setStartDelay(FADE_KEYGUARD_START_DELAY)
3561                        .setDuration(FADE_KEYGUARD_DURATION)
3562                        .withLayer()
3563                        .withEndAction(new Runnable() {
3564                            @Override
3565                            public void run() {
3566                                mNotificationPanel.setAlpha(1);
3567                                if (endRunnable != null) {
3568                                    endRunnable.run();
3569                                }
3570                                mLaunchTransitionFadingAway = false;
3571                            }
3572                        });
3573            }
3574        };
3575        if (mNotificationPanel.isLaunchTransitionRunning()) {
3576            mNotificationPanel.setLaunchTransitionEndRunnable(hideRunnable);
3577        } else {
3578            hideRunnable.run();
3579        }
3580    }
3581
3582    /**
3583     * @return true if we would like to stay in the shade, false if it should go away entirely
3584     */
3585    public boolean hideKeyguard() {
3586        boolean staying = mLeaveOpenOnKeyguardHide;
3587        setBarState(StatusBarState.SHADE);
3588        if (mLeaveOpenOnKeyguardHide) {
3589            mLeaveOpenOnKeyguardHide = false;
3590            mNotificationPanel.animateToFullShade(calculateGoingToFullShadeDelay());
3591            if (mDraggedDownRow != null) {
3592                mDraggedDownRow.setUserLocked(false);
3593                mDraggedDownRow = null;
3594            }
3595        } else {
3596            instantCollapseNotificationPanel();
3597        }
3598        updateKeyguardState(staying, false /* fromShadeLocked */);
3599        return staying;
3600    }
3601
3602    public long calculateGoingToFullShadeDelay() {
3603        return mKeyguardFadingAwayDelay + mKeyguardFadingAwayDuration;
3604    }
3605
3606    /**
3607     * Notifies the status bar the Keyguard is fading away with the specified timings.
3608     *
3609     * @param delay the animation delay in miliseconds
3610     * @param fadeoutDuration the duration of the exit animation, in milliseconds
3611     */
3612    public void setKeyguardFadingAway(long delay, long fadeoutDuration) {
3613        mKeyguardFadingAway = true;
3614        mKeyguardFadingAwayDelay = delay;
3615        mKeyguardFadingAwayDuration = fadeoutDuration;
3616        mWaitingForKeyguardExit = false;
3617        disable(mDisabledUnmodified, true /* animate */);
3618    }
3619
3620    public boolean isKeyguardFadingAway() {
3621        return mKeyguardFadingAway;
3622    }
3623
3624    /**
3625     * Notifies that the Keyguard fading away animation is done.
3626     */
3627    public void finishKeyguardFadingAway() {
3628        mKeyguardFadingAway = false;
3629    }
3630
3631    private void updatePublicMode() {
3632        setLockscreenPublicMode(
3633                (mStatusBarKeyguardViewManager.isShowing() ||
3634                        mStatusBarKeyguardViewManager.isOccluded())
3635                && mStatusBarKeyguardViewManager.isSecure());
3636    }
3637
3638    private void updateKeyguardState(boolean goingToFullShade, boolean fromShadeLocked) {
3639        if (mState == StatusBarState.KEYGUARD) {
3640            mKeyguardIndicationController.setVisible(true);
3641            mNotificationPanel.resetViews();
3642            mKeyguardUserSwitcher.setKeyguard(true, fromShadeLocked);
3643        } else {
3644            mKeyguardIndicationController.setVisible(false);
3645            mKeyguardUserSwitcher.setKeyguard(false,
3646                    goingToFullShade || mState == StatusBarState.SHADE_LOCKED || fromShadeLocked);
3647        }
3648        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
3649            mScrimController.setKeyguardShowing(true);
3650        } else {
3651            mScrimController.setKeyguardShowing(false);
3652        }
3653        mNotificationPanel.setBarState(mState, mKeyguardFadingAway, goingToFullShade);
3654        updateDozingState();
3655        updatePublicMode();
3656        updateStackScrollerState(goingToFullShade);
3657        updateNotifications();
3658        checkBarModes();
3659        updateCarrierLabelVisibility(false);
3660        updateMediaMetaData(false);
3661        mKeyguardMonitor.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
3662                mStatusBarKeyguardViewManager.isSecure());
3663    }
3664
3665    private void updateDozingState() {
3666        if (mState != StatusBarState.KEYGUARD && !mNotificationPanel.isDozing()) {
3667            return;
3668        }
3669        mNotificationPanel.setDozing(mDozing);
3670        if (mDozing) {
3671            mKeyguardBottomArea.setVisibility(View.INVISIBLE);
3672            mStackScroller.setDark(true, false /*animate*/);
3673        } else {
3674            mKeyguardBottomArea.setVisibility(View.VISIBLE);
3675            mStackScroller.setDark(false, false /*animate*/);
3676        }
3677        mScrimController.setDozing(mDozing);
3678    }
3679
3680    public void updateStackScrollerState(boolean goingToFullShade) {
3681        if (mStackScroller == null) return;
3682        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
3683        mStackScroller.setHideSensitive(isLockscreenPublicMode(), goingToFullShade);
3684        mStackScroller.setDimmed(onKeyguard, false /* animate */);
3685        mStackScroller.setExpandingEnabled(!onKeyguard);
3686        ActivatableNotificationView activatedChild = mStackScroller.getActivatedChild();
3687        mStackScroller.setActivatedChild(null);
3688        if (activatedChild != null) {
3689            activatedChild.makeInactive(false /* animate */);
3690        }
3691    }
3692
3693    public void userActivity() {
3694        if (mState == StatusBarState.KEYGUARD) {
3695            mKeyguardViewMediatorCallback.userActivity();
3696        }
3697    }
3698
3699    public boolean interceptMediaKey(KeyEvent event) {
3700        return mState == StatusBarState.KEYGUARD
3701                && mStatusBarKeyguardViewManager.interceptMediaKey(event);
3702    }
3703
3704    public boolean onMenuPressed() {
3705        return mState == StatusBarState.KEYGUARD && mStatusBarKeyguardViewManager.onMenuPressed();
3706    }
3707
3708    public boolean onBackPressed() {
3709        if (mStatusBarKeyguardViewManager.onBackPressed()) {
3710            return true;
3711        }
3712        if (mNotificationPanel.isQsExpanded()) {
3713            if (mNotificationPanel.isQsDetailShowing()) {
3714                mNotificationPanel.closeQsDetail();
3715            } else {
3716                mNotificationPanel.animateCloseQs();
3717            }
3718            return true;
3719        }
3720        if (mState != StatusBarState.KEYGUARD && mState != StatusBarState.SHADE_LOCKED) {
3721            animateCollapsePanels();
3722            return true;
3723        }
3724        return false;
3725    }
3726
3727    public boolean onSpacePressed() {
3728        if (mScreenOn != null && mScreenOn
3729                && (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED)) {
3730            if (PhoneStatusBar.DEBUG_EMPTY_KEYGUARD) {
3731                Log.i(TAG, "Collapsing panel from onSpacePressed");
3732            }
3733            animateCollapsePanels(0 /* flags */, true /* force */);
3734            return true;
3735        }
3736        return false;
3737    }
3738
3739    private void showBouncer() {
3740        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
3741            mWaitingForKeyguardExit = mStatusBarKeyguardViewManager.isShowing();
3742            mStatusBarKeyguardViewManager.dismiss();
3743        }
3744    }
3745
3746    private void instantExpandNotificationsPanel() {
3747
3748        // Make our window larger and the panel expanded.
3749        makeExpandedVisible(true);
3750        mNotificationPanel.instantExpand();
3751    }
3752
3753    private void instantCollapseNotificationPanel() {
3754        mNotificationPanel.setExpandedFraction(0);
3755    }
3756
3757    @Override
3758    public void onActivated(ActivatableNotificationView view) {
3759        mKeyguardIndicationController.showTransientIndication(R.string.notification_tap_again);
3760        ActivatableNotificationView previousView = mStackScroller.getActivatedChild();
3761        if (previousView != null) {
3762            previousView.makeInactive(true /* animate */);
3763        }
3764        mStackScroller.setActivatedChild(view);
3765    }
3766
3767    /**
3768     * @param state The {@link StatusBarState} to set.
3769     */
3770    public void setBarState(int state) {
3771        mState = state;
3772        mStatusBarWindowManager.setStatusBarState(state);
3773    }
3774
3775    @Override
3776    public void onActivationReset(ActivatableNotificationView view) {
3777        if (view == mStackScroller.getActivatedChild()) {
3778            mKeyguardIndicationController.hideTransientIndication();
3779            mStackScroller.setActivatedChild(null);
3780        }
3781    }
3782
3783    public void onTrackingStarted() {
3784        runPostCollapseRunnables();
3785    }
3786
3787    public void onUnlockHintStarted() {
3788        mKeyguardIndicationController.showTransientIndication(R.string.keyguard_unlock);
3789    }
3790
3791    public void onHintFinished() {
3792        // Delay the reset a bit so the user can read the text.
3793        mKeyguardIndicationController.hideTransientIndicationDelayed(HINT_RESET_DELAY_MS);
3794    }
3795
3796    public void onCameraHintStarted() {
3797        mKeyguardIndicationController.showTransientIndication(R.string.camera_hint);
3798    }
3799
3800    public void onPhoneHintStarted() {
3801        mKeyguardIndicationController.showTransientIndication(R.string.phone_hint);
3802    }
3803
3804    public void onTrackingStopped(boolean expand) {
3805        if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
3806            if (!expand && !mUnlockMethodCache.isMethodInsecure()) {
3807                showBouncer();
3808            }
3809        }
3810    }
3811
3812    @Override
3813    protected int getMaxKeyguardNotifications() {
3814        return mKeyguardMaxNotificationCount;
3815    }
3816
3817    public NavigationBarView getNavigationBarView() {
3818        return mNavigationBarView;
3819    }
3820
3821    // ---------------------- DragDownHelper.OnDragDownListener ------------------------------------
3822
3823    @Override
3824    public boolean onDraggedDown(View startingChild) {
3825        if (hasActiveNotifications()) {
3826
3827            // We have notifications, go to locked shade.
3828            goToLockedShade(startingChild);
3829            return true;
3830        } else {
3831
3832            // No notifications - abort gesture.
3833            return false;
3834        }
3835    }
3836
3837    @Override
3838    public void onDragDownReset() {
3839        mStackScroller.setDimmed(true /* dimmed */, true /* animated */);
3840    }
3841
3842    @Override
3843    public void onThresholdReached() {
3844        mStackScroller.setDimmed(false /* dimmed */, true /* animate */);
3845    }
3846
3847    @Override
3848    public void onTouchSlopExceeded() {
3849        mStackScroller.removeLongPressCallback();
3850    }
3851
3852    @Override
3853    public void setEmptyDragAmount(float amount) {
3854        mNotificationPanel.setEmptyDragAmount(amount);
3855    }
3856
3857    /**
3858     * If secure with redaction: Show bouncer, go to unlocked shade.
3859     *
3860     * <p>If secure without redaction or no security: Go to {@link StatusBarState#SHADE_LOCKED}.</p>
3861     *
3862     * @param expandView The view to expand after going to the shade.
3863     */
3864    public void goToLockedShade(View expandView) {
3865        ExpandableNotificationRow row = null;
3866        if (expandView instanceof ExpandableNotificationRow) {
3867            row = (ExpandableNotificationRow) expandView;
3868            row.setUserExpanded(true);
3869        }
3870        boolean fullShadeNeedsBouncer = !userAllowsPrivateNotificationsInPublic(mCurrentUserId)
3871                || !mShowLockscreenNotifications;
3872        if (isLockscreenPublicMode() && fullShadeNeedsBouncer) {
3873            mLeaveOpenOnKeyguardHide = true;
3874            showBouncer();
3875            mDraggedDownRow = row;
3876        } else {
3877            mNotificationPanel.animateToFullShade(0 /* delay */);
3878            setBarState(StatusBarState.SHADE_LOCKED);
3879            updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
3880            if (row != null) {
3881                row.setUserLocked(false);
3882            }
3883        }
3884    }
3885
3886    /**
3887     * Goes back to the keyguard after hanging around in {@link StatusBarState#SHADE_LOCKED}.
3888     */
3889    public void goToKeyguard() {
3890        if (mState == StatusBarState.SHADE_LOCKED) {
3891            mStackScroller.onGoToKeyguard();
3892            setBarState(StatusBarState.KEYGUARD);
3893            updateKeyguardState(false /* goingToFullShade */, true /* fromShadeLocked*/);
3894        }
3895    }
3896
3897    /**
3898     * @return a ViewGroup that spans the entire panel which contains the quick settings
3899     */
3900    public ViewGroup getQuickSettingsOverlayParent() {
3901        return mNotificationPanel;
3902    }
3903
3904    public long getKeyguardFadingAwayDelay() {
3905        return mKeyguardFadingAwayDelay;
3906    }
3907
3908    public long getKeyguardFadingAwayDuration() {
3909        return mKeyguardFadingAwayDuration;
3910    }
3911
3912    public LinearLayout getSystemIcons() {
3913        return mSystemIcons;
3914    }
3915
3916    public LinearLayout getSystemIconArea() {
3917        return mSystemIconArea;
3918    }
3919
3920    @Override
3921    public void setBouncerShowing(boolean bouncerShowing) {
3922        super.setBouncerShowing(bouncerShowing);
3923        disable(mDisabledUnmodified, true /* animate */);
3924    }
3925
3926    public void onScreenTurnedOff() {
3927        mScreenOnFromKeyguard = false;
3928        mScreenOnComingFromTouch = false;
3929        mStackScroller.setAnimationsEnabled(false);
3930    }
3931
3932    public void onScreenTurnedOn() {
3933        mScreenOnFromKeyguard = true;
3934        mStackScroller.setAnimationsEnabled(true);
3935        mNotificationPanel.onScreenTurnedOn();
3936        mNotificationPanel.setTouchDisabled(false);
3937    }
3938
3939    /**
3940     * This handles long-press of both back and recents.  They are
3941     * handled together to capture them both being long-pressed
3942     * at the same time to exit screen pinning (lock task).
3943     *
3944     * When accessibility mode is on, only a long-press from recents
3945     * is required to exit.
3946     *
3947     * In all other circumstances we try to pass through long-press events
3948     * for Back, so that apps can still use it.  Which can be from two things.
3949     * 1) Not currently in screen pinning (lock task).
3950     * 2) Back is long-pressed without recents.
3951     */
3952    private void handleLongPressBackRecents(View v) {
3953        try {
3954            boolean sendBackLongPress = false;
3955            IActivityManager activityManager = ActivityManagerNative.getDefault();
3956            boolean isAccessiblityEnabled = mAccessibilityManager.isEnabled();
3957            if (activityManager.isInLockTaskMode() && !isAccessiblityEnabled) {
3958                long time = System.currentTimeMillis();
3959                // If we recently long-pressed the other button then they were
3960                // long-pressed 'together'
3961                if ((time - mLastLockToAppLongPress) < LOCK_TO_APP_GESTURE_TOLERENCE) {
3962                    activityManager.stopLockTaskModeOnCurrent();
3963                } else if ((v.getId() == R.id.back)
3964                        && !mNavigationBarView.getRecentsButton().isPressed()) {
3965                    // If we aren't pressing recents right now then they presses
3966                    // won't be together, so send the standard long-press action.
3967                    sendBackLongPress = true;
3968                }
3969                mLastLockToAppLongPress = time;
3970            } else {
3971                // If this is back still need to handle sending the long-press event.
3972                if (v.getId() == R.id.back) {
3973                    sendBackLongPress = true;
3974                } else if (isAccessiblityEnabled && activityManager.isInLockTaskMode()) {
3975                    // When in accessibility mode a long press that is recents (not back)
3976                    // should stop lock task.
3977                    activityManager.stopLockTaskModeOnCurrent();
3978                }
3979            }
3980            if (sendBackLongPress) {
3981                KeyButtonView keyButtonView = (KeyButtonView) v;
3982                keyButtonView.sendEvent(KeyEvent.ACTION_DOWN, KeyEvent.FLAG_LONG_PRESS);
3983                keyButtonView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3984            }
3985        } catch (RemoteException e) {
3986            Log.d(TAG, "Unable to reach activity manager", e);
3987        }
3988    }
3989
3990    // Recents
3991
3992    @Override
3993    protected void showRecents(boolean triggeredFromAltTab) {
3994        // Set the recents visibility flag
3995        mSystemUiVisibility |= View.RECENT_APPS_VISIBLE;
3996        notifyUiVisibilityChanged(mSystemUiVisibility);
3997        super.showRecents(triggeredFromAltTab);
3998    }
3999
4000    @Override
4001    protected void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) {
4002        // Unset the recents visibility flag
4003        mSystemUiVisibility &= ~View.RECENT_APPS_VISIBLE;
4004        notifyUiVisibilityChanged(mSystemUiVisibility);
4005        super.hideRecents(triggeredFromAltTab, triggeredFromHomeKey);
4006    }
4007
4008    @Override
4009    protected void toggleRecents() {
4010        // Toggle the recents visibility flag
4011        mSystemUiVisibility ^= View.RECENT_APPS_VISIBLE;
4012        notifyUiVisibilityChanged(mSystemUiVisibility);
4013        super.toggleRecents();
4014    }
4015
4016    @Override
4017    public void onVisibilityChanged(boolean visible) {
4018        // Update the recents visibility flag
4019        if (visible) {
4020            mSystemUiVisibility |= View.RECENT_APPS_VISIBLE;
4021        } else {
4022            mSystemUiVisibility &= ~View.RECENT_APPS_VISIBLE;
4023        }
4024        notifyUiVisibilityChanged(mSystemUiVisibility);
4025    }
4026
4027    public boolean hasActiveNotifications() {
4028        return !mNotificationData.getActiveNotifications().isEmpty();
4029    }
4030
4031    public void wakeUpIfDozing(long time, boolean fromTouch) {
4032        if (mDozing && mScrimController.isPulsing()) {
4033            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
4034            pm.wakeUp(time);
4035            if (fromTouch) {
4036                mScreenOnComingFromTouch = true;
4037            }
4038        }
4039    }
4040
4041    private final class ShadeUpdates {
4042        private final ArraySet<String> mVisibleNotifications = new ArraySet<String>();
4043        private final ArraySet<String> mNewVisibleNotifications = new ArraySet<String>();
4044
4045        public void check() {
4046            mNewVisibleNotifications.clear();
4047            ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
4048            for (int i = 0; i < activeNotifications.size(); i++) {
4049                final Entry entry = activeNotifications.get(i);
4050                final boolean visible = entry.row != null
4051                        && entry.row.getVisibility() == View.VISIBLE;
4052                if (visible) {
4053                    mNewVisibleNotifications.add(entry.key + entry.notification.getPostTime());
4054                }
4055            }
4056            final boolean updates = !mVisibleNotifications.containsAll(mNewVisibleNotifications);
4057            mVisibleNotifications.clear();
4058            mVisibleNotifications.addAll(mNewVisibleNotifications);
4059
4060            // We have new notifications
4061            if (updates && mDozeServiceHost != null) {
4062                mDozeServiceHost.fireNewNotifications();
4063            }
4064        }
4065    }
4066
4067    private final class DozeServiceHost implements DozeHost {
4068        // Amount of time to allow to update the time shown on the screen before releasing
4069        // the wakelock.  This timeout is design to compensate for the fact that we don't
4070        // currently have a way to know when time display contents have actually been
4071        // refreshed once we've finished rendering a new frame.
4072        private static final long PROCESSING_TIME = 500;
4073
4074        private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
4075        private final H mHandler = new H();
4076
4077        @Override
4078        public String toString() {
4079            return "PSB.DozeServiceHost[mCallbacks=" + mCallbacks.size() + "]";
4080        }
4081
4082        public void firePowerSaveChanged(boolean active) {
4083            for (Callback callback : mCallbacks) {
4084                callback.onPowerSaveChanged(active);
4085            }
4086        }
4087
4088        public void fireBuzzBeepBlinked() {
4089            for (Callback callback : mCallbacks) {
4090                callback.onBuzzBeepBlinked();
4091            }
4092        }
4093
4094        public void fireNotificationLight(boolean on) {
4095            for (Callback callback : mCallbacks) {
4096                callback.onNotificationLight(on);
4097            }
4098        }
4099
4100        public void fireNewNotifications() {
4101            for (Callback callback : mCallbacks) {
4102                callback.onNewNotifications();
4103            }
4104        }
4105
4106        @Override
4107        public void addCallback(@NonNull Callback callback) {
4108            mCallbacks.add(callback);
4109        }
4110
4111        @Override
4112        public void removeCallback(@NonNull Callback callback) {
4113            mCallbacks.remove(callback);
4114        }
4115
4116        @Override
4117        public void startDozing(@NonNull Runnable ready) {
4118            mHandler.obtainMessage(H.MSG_START_DOZING, ready).sendToTarget();
4119        }
4120
4121        @Override
4122        public void pulseWhileDozing(@NonNull PulseCallback callback) {
4123            mHandler.obtainMessage(H.MSG_PULSE_WHILE_DOZING, callback).sendToTarget();
4124        }
4125
4126        @Override
4127        public void stopDozing() {
4128            mHandler.obtainMessage(H.MSG_STOP_DOZING).sendToTarget();
4129        }
4130
4131        @Override
4132        public boolean isPowerSaveActive() {
4133            return mBatteryController != null && mBatteryController.isPowerSave();
4134        }
4135
4136        private void handleStartDozing(@NonNull Runnable ready) {
4137            if (!mDozing) {
4138                mDozing = true;
4139                DozeLog.traceDozing(mContext, mDozing);
4140                updateDozingState();
4141            }
4142            ready.run();
4143        }
4144
4145        private void handlePulseWhileDozing(@NonNull PulseCallback callback) {
4146            mScrimController.pulse(callback);
4147        }
4148
4149        private void handleStopDozing() {
4150            if (mDozing) {
4151                mDozing = false;
4152                DozeLog.traceDozing(mContext, mDozing);
4153                updateDozingState();
4154            }
4155        }
4156
4157        private final class H extends Handler {
4158            private static final int MSG_START_DOZING = 1;
4159            private static final int MSG_PULSE_WHILE_DOZING = 2;
4160            private static final int MSG_STOP_DOZING = 3;
4161
4162            @Override
4163            public void handleMessage(Message msg) {
4164                switch (msg.what) {
4165                    case MSG_START_DOZING:
4166                        handleStartDozing((Runnable) msg.obj);
4167                        break;
4168                    case MSG_PULSE_WHILE_DOZING:
4169                        handlePulseWhileDozing((PulseCallback) msg.obj);
4170                        break;
4171                    case MSG_STOP_DOZING:
4172                        handleStopDozing();
4173                        break;
4174                }
4175            }
4176        }
4177    }
4178}
4179