PhoneStatusBar.java revision f249efcf3709b0feace01b9e3875cfd64b4d061e
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
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
24import android.app.ActivityManager;
25import android.app.ActivityManagerNative;
26import android.app.Notification;
27import android.app.PendingIntent;
28import android.app.StatusBarManager;
29import android.content.BroadcastReceiver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.SharedPreferences;
34import android.content.res.Resources;
35import android.database.ContentObserver;
36import android.graphics.Canvas;
37import android.graphics.ColorFilter;
38import android.graphics.PixelFormat;
39import android.graphics.Point;
40import android.graphics.PorterDuff;
41import android.graphics.Rect;
42import android.graphics.drawable.Drawable;
43import android.graphics.drawable.NinePatchDrawable;
44import android.inputmethodservice.InputMethodService;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.RemoteException;
49import android.os.ServiceManager;
50import android.os.SystemClock;
51import android.os.UserHandle;
52import android.provider.Settings;
53import android.service.dreams.DreamService;
54import android.service.dreams.IDreamManager;
55import android.util.DisplayMetrics;
56import android.util.Log;
57import android.util.Slog;
58import android.view.Display;
59import android.view.Gravity;
60import android.view.MotionEvent;
61import android.view.VelocityTracker;
62import android.view.View;
63import android.view.ViewGroup;
64import android.view.ViewGroup.LayoutParams;
65import android.view.ViewPropertyAnimator;
66import android.view.ViewStub;
67import android.view.WindowManager;
68import android.view.animation.AccelerateInterpolator;
69import android.view.animation.Animation;
70import android.view.animation.AnimationUtils;
71import android.view.animation.DecelerateInterpolator;
72import android.widget.FrameLayout;
73import android.widget.ImageView;
74import android.widget.LinearLayout;
75import android.widget.ScrollView;
76import android.widget.TextView;
77
78import com.android.internal.statusbar.StatusBarIcon;
79import com.android.internal.statusbar.StatusBarNotification;
80import com.android.systemui.R;
81import com.android.systemui.statusbar.BaseStatusBar;
82import com.android.systemui.statusbar.CommandQueue;
83import com.android.systemui.statusbar.GestureRecorder;
84import com.android.systemui.statusbar.NotificationData;
85import com.android.systemui.statusbar.NotificationData.Entry;
86import com.android.systemui.statusbar.SignalClusterView;
87import com.android.systemui.statusbar.StatusBarIconView;
88import com.android.systemui.statusbar.policy.BatteryController;
89import com.android.systemui.statusbar.policy.BluetoothController;
90import com.android.systemui.statusbar.policy.DateView;
91import com.android.systemui.statusbar.policy.IntruderAlertView;
92import com.android.systemui.statusbar.policy.LocationController;
93import com.android.systemui.statusbar.policy.NetworkController;
94import com.android.systemui.statusbar.policy.NotificationRowLayout;
95import com.android.systemui.statusbar.policy.OnSizeChangedListener;
96import com.android.systemui.statusbar.policy.Prefs;
97
98import java.io.FileDescriptor;
99import java.io.PrintWriter;
100import java.util.ArrayList;
101
102public class PhoneStatusBar extends BaseStatusBar {
103    static final String TAG = "PhoneStatusBar";
104    public static final boolean DEBUG = BaseStatusBar.DEBUG;
105    public static final boolean SPEW = DEBUG;
106    public static final boolean DUMPTRUCK = true; // extra dumpsys info
107    public static final boolean DEBUG_GESTURES = false;
108
109    public static final boolean DEBUG_CLINGS = false;
110
111    public static final boolean ENABLE_NOTIFICATION_PANEL_CLING = false;
112
113    public static final boolean SETTINGS_DRAG_SHORTCUT = true;
114
115    // additional instrumentation for testing purposes; intended to be left on during development
116    public static final boolean CHATTY = DEBUG;
117
118    public static final String ACTION_STATUSBAR_START
119            = "com.android.internal.policy.statusbar.START";
120
121    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
122    private static final int MSG_CLOSE_PANELS = 1001;
123    private static final int MSG_OPEN_SETTINGS_PANEL = 1002;
124    // 1020-1030 reserved for BaseStatusBar
125
126    // will likely move to a resource or other tunable param at some point
127    private static final int INTRUDER_ALERT_DECAY_MS = 0; // disabled, was 10000;
128
129    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
130
131    private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10; // see NotificationManagerService
132    private static final int HIDE_ICONS_BELOW_SCORE = Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
133
134    // fling gesture tuning parameters, scaled to display density
135    private float mSelfExpandVelocityPx; // classic value: 2000px/s
136    private float mSelfCollapseVelocityPx; // classic value: 2000px/s (will be negated to collapse "up")
137    private float mFlingExpandMinVelocityPx; // classic value: 200px/s
138    private float mFlingCollapseMinVelocityPx; // classic value: 200px/s
139    private float mCollapseMinDisplayFraction; // classic value: 0.08 (25px/min(320px,480px) on G1)
140    private float mExpandMinDisplayFraction; // classic value: 0.5 (drag open halfway to expand)
141    private float mFlingGestureMaxXVelocityPx; // classic value: 150px/s
142
143    private float mExpandAccelPx; // classic value: 2000px/s/s
144    private float mCollapseAccelPx; // classic value: 2000px/s/s (will be negated to collapse "up")
145
146    private float mFlingGestureMaxOutputVelocityPx; // how fast can it really go? (should be a little
147                                                    // faster than mSelfCollapseVelocityPx)
148
149    PhoneStatusBarPolicy mIconPolicy;
150
151    // These are no longer handled by the policy, because we need custom strategies for them
152    BluetoothController mBluetoothController;
153    BatteryController mBatteryController;
154    LocationController mLocationController;
155    NetworkController mNetworkController;
156
157    int mNaturalBarHeight = -1;
158    int mIconSize = -1;
159    int mIconHPadding = -1;
160    Display mDisplay;
161    Point mCurrentDisplaySize = new Point();
162
163    IDreamManager mDreamManager;
164
165    StatusBarWindowView mStatusBarWindow;
166    PhoneStatusBarView mStatusBarView;
167
168    int mPixelFormat;
169    Object mQueueLock = new Object();
170
171    // viewgroup containing the normal contents of the statusbar
172    LinearLayout mStatusBarContents;
173
174    // right-hand icons
175    LinearLayout mSystemIconArea;
176
177    // left-hand icons
178    LinearLayout mStatusIcons;
179    // the icons themselves
180    IconMerger mNotificationIcons;
181    // [+>
182    View mMoreIcon;
183
184    // expanded notifications
185    NotificationPanelView mNotificationPanel; // the sliding/resizing panel within the notification window
186    ScrollView mScrollView;
187    View mExpandedContents;
188    int mNotificationPanelGravity;
189    int mNotificationPanelMarginBottomPx, mNotificationPanelMarginPx;
190    float mNotificationPanelMinHeightFrac;
191    boolean mNotificationPanelIsFullScreenWidth;
192    TextView mNotificationPanelDebugText;
193
194    // settings
195    QuickSettings mQS;
196    boolean mHasSettingsPanel, mHasFlipSettings;
197    SettingsPanelView mSettingsPanel;
198    View mFlipSettingsView;
199    QuickSettingsContainerView mSettingsContainer;
200    int mSettingsPanelGravity;
201
202    // top bar
203    View mNotificationPanelHeader;
204    View mDateTimeView;
205    View mClearButton;
206    ImageView mSettingsButton, mNotificationButton;
207
208    // carrier/wifi label
209    private TextView mCarrierLabel;
210    private boolean mCarrierLabelVisible = false;
211    private int mCarrierLabelHeight;
212    private TextView mEmergencyCallLabel;
213    private int mNotificationHeaderHeight;
214
215    private boolean mShowCarrierInPanel = false;
216
217    // position
218    int[] mPositionTmp = new int[2];
219    boolean mExpandedVisible;
220
221    // the date view
222    DateView mDateView;
223
224    // for immersive activities
225    private IntruderAlertView mIntruderAlertView;
226
227    // on-screen navigation buttons
228    private NavigationBarView mNavigationBarView = null;
229
230    // the tracker view
231    int mTrackingPosition; // the position of the top of the tracking view.
232
233    // ticker
234    private Ticker mTicker;
235    private View mTickerView;
236    private boolean mTicking;
237
238    // Tracking finger for opening/closing.
239    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
240    boolean mTracking;
241    VelocityTracker mVelocityTracker;
242
243    // help screen
244    private boolean mClingShown;
245    private ViewGroup mCling;
246    private boolean mSuppressStatusBarDrags; // while a cling is up, briefly deaden the bar to give things time to settle
247
248    boolean mAnimating;
249    boolean mClosing; // only valid when mAnimating; indicates the initial acceleration
250    float mAnimY;
251    float mAnimVel;
252    float mAnimAccel;
253    long mAnimLastTimeNanos;
254    boolean mAnimatingReveal = false;
255    int mViewDelta;
256    float mFlingVelocity;
257    int mFlingY;
258    int[] mAbsPos = new int[2];
259    Runnable mPostCollapseCleanup = null;
260
261    private Animator mLightsOutAnimation;
262    private Animator mLightsOnAnimation;
263
264    // for disabling the status bar
265    int mDisabled = 0;
266
267    // tracking calls to View.setSystemUiVisibility()
268    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
269
270    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
271
272    // XXX: gesture research
273    private final GestureRecorder mGestureRec = DEBUG_GESTURES
274        ? new GestureRecorder("/sdcard/statusbar_gestures.dat")
275        : null;
276
277    private int mNavigationIconHints = 0;
278    private final Animator.AnimatorListener mMakeIconsInvisible = new AnimatorListenerAdapter() {
279        @Override
280        public void onAnimationEnd(Animator animation) {
281            // double-check to avoid races
282            if (mStatusBarContents.getAlpha() == 0) {
283                Slog.d(TAG, "makeIconsInvisible");
284                mStatusBarContents.setVisibility(View.INVISIBLE);
285            }
286        }
287    };
288
289    // ensure quick settings is disabled until the current user makes it through the setup wizard
290    private boolean mUserSetup = false;
291    private ContentObserver mUserSetupObserver = new ContentObserver(new Handler()) {
292        @Override
293        public void onChange(boolean selfChange) {
294            final boolean userSetup = 0 != Settings.Secure.getIntForUser(
295                    mContext.getContentResolver(),
296                    Settings.Secure.USER_SETUP_COMPLETE,
297                    0 /*default */,
298                    mCurrentUserId);
299            if (MULTIUSER_DEBUG) Slog.d(TAG, String.format("User setup changed: " +
300                    "selfChange=%s userSetup=%s mUserSetup=%s",
301                    selfChange, userSetup, mUserSetup));
302            if (mSettingsButton != null && !mHasSettingsPanel) {
303                mSettingsButton.setVisibility(userSetup ? View.VISIBLE : View.INVISIBLE);
304            }
305            if (mSettingsPanel != null) {
306                mSettingsPanel.setEnabled(userSetup);
307            }
308            if (userSetup != mUserSetup) {
309                mUserSetup = userSetup;
310                if (!mUserSetup && mStatusBarView != null)
311                    animateCollapseQuickSettings();
312            }
313        }
314    };
315
316    @Override
317    public void start() {
318        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
319                .getDefaultDisplay();
320
321        mDreamManager = IDreamManager.Stub.asInterface(
322                ServiceManager.checkService(DreamService.DREAM_SERVICE));
323
324        super.start(); // calls createAndAddWindows()
325
326        addNavigationBar();
327
328        if (ENABLE_INTRUDERS) addIntruderView();
329
330        // Lastly, call to the icon policy to install/update all the icons.
331        mIconPolicy = new PhoneStatusBarPolicy(mContext);
332    }
333
334    // ================================================================================
335    // Constructing the view
336    // ================================================================================
337    protected PhoneStatusBarView makeStatusBarView() {
338        final Context context = mContext;
339
340        Resources res = context.getResources();
341
342        updateDisplaySize(); // populates mDisplayMetrics
343        loadDimens();
344
345        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
346
347        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
348                R.layout.super_status_bar, null);
349        mStatusBarWindow.mService = this;
350        mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {
351            @Override
352            public boolean onTouch(View v, MotionEvent event) {
353                if (event.getAction() == MotionEvent.ACTION_DOWN) {
354                    if (mExpandedVisible && !mAnimating) {
355                        animateCollapsePanels();
356                    }
357                }
358                return mStatusBarWindow.onTouchEvent(event);
359            }});
360
361        mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
362        mStatusBarView.setBar(this);
363
364
365        PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
366        mStatusBarView.setPanelHolder(holder);
367
368        mNotificationPanel = (NotificationPanelView) mStatusBarWindow.findViewById(R.id.notification_panel);
369        mNotificationPanel.setStatusBar(this);
370        mNotificationPanelIsFullScreenWidth =
371            (mNotificationPanel.getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT);
372
373        // make the header non-responsive to clicks
374        mNotificationPanel.findViewById(R.id.header).setOnTouchListener(
375                new View.OnTouchListener() {
376                    @Override
377                    public boolean onTouch(View v, MotionEvent event) {
378                        return true; // e eats everything
379                    }
380                });
381
382        if (!ActivityManager.isHighEndGfx()) {
383            mStatusBarWindow.setBackground(null);
384            mNotificationPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
385                    R.color.notification_panel_solid_background)));
386        }
387        if (ENABLE_INTRUDERS) {
388            mIntruderAlertView = (IntruderAlertView) View.inflate(context, R.layout.intruder_alert, null);
389            mIntruderAlertView.setVisibility(View.GONE);
390            mIntruderAlertView.setBar(this);
391        }
392        if (MULTIUSER_DEBUG) {
393            mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(R.id.header_debug_info);
394            mNotificationPanelDebugText.setVisibility(View.VISIBLE);
395        }
396
397        updateShowSearchHoldoff();
398
399        try {
400            boolean showNav = mWindowManagerService.hasNavigationBar();
401            if (DEBUG) Slog.v(TAG, "hasNavigationBar=" + showNav);
402            if (showNav) {
403                mNavigationBarView =
404                    (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
405
406                mNavigationBarView.setDisabledFlags(mDisabled);
407                mNavigationBarView.setBar(this);
408            }
409        } catch (RemoteException ex) {
410            // no window manager? good luck with that
411        }
412
413        // figure out which pixel-format to use for the status bar.
414        mPixelFormat = PixelFormat.OPAQUE;
415
416        mSystemIconArea = (LinearLayout) mStatusBarView.findViewById(R.id.system_icon_area);
417        mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
418        mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
419        mNotificationIcons.setOverflowIndicator(mMoreIcon);
420        mStatusBarContents = (LinearLayout)mStatusBarView.findViewById(R.id.status_bar_contents);
421        mTickerView = mStatusBarView.findViewById(R.id.ticker);
422
423        mPile = (NotificationRowLayout)mStatusBarWindow.findViewById(R.id.latestItems);
424        mPile.setLayoutTransitionsEnabled(false);
425        mPile.setLongPressListener(getNotificationLongClicker());
426        mExpandedContents = mPile; // was: expanded.findViewById(R.id.notificationLinearLayout);
427
428        mNotificationPanelHeader = mStatusBarWindow.findViewById(R.id.header);
429
430        mClearButton = mStatusBarWindow.findViewById(R.id.clear_all_button);
431        mClearButton.setOnClickListener(mClearButtonListener);
432        mClearButton.setAlpha(0f);
433        mClearButton.setVisibility(View.INVISIBLE);
434        mClearButton.setEnabled(false);
435        mDateView = (DateView)mStatusBarWindow.findViewById(R.id.date);
436
437        mHasSettingsPanel = res.getBoolean(R.bool.config_hasSettingsPanel);
438        mHasFlipSettings = res.getBoolean(R.bool.config_hasFlipSettingsPanel);
439
440        mDateTimeView = mNotificationPanelHeader.findViewById(R.id.datetime);
441        if (mHasFlipSettings) {
442            mDateTimeView.setOnClickListener(mClockClickListener);
443            mDateTimeView.setEnabled(true);
444        }
445
446        mSettingsButton = (ImageView) mStatusBarWindow.findViewById(R.id.settings_button);
447        if (mSettingsButton != null) {
448            mSettingsButton.setOnClickListener(mSettingsButtonListener);
449            if (mHasSettingsPanel) {
450                if (mStatusBarView.hasFullWidthNotifications()) {
451                    // the settings panel is hiding behind this button
452                    mSettingsButton.setImageResource(R.drawable.ic_notify_quicksettings);
453                    mSettingsButton.setVisibility(View.VISIBLE);
454                } else {
455                    // there is a settings panel, but it's on the other side of the (large) screen
456                    mSettingsButton.setVisibility(View.GONE);
457                }
458            } else {
459                // no settings panel, go straight to settings
460                mSettingsButton.setVisibility(View.VISIBLE);
461                mSettingsButton.setImageResource(R.drawable.ic_notify_settings);
462            }
463        }
464        if (mHasFlipSettings) {
465            mNotificationButton = (ImageView) mStatusBarWindow.findViewById(R.id.notification_button);
466            if (mNotificationButton != null) {
467                mNotificationButton.setOnClickListener(mNotificationButtonListener);
468            }
469        }
470
471        mScrollView = (ScrollView)mStatusBarWindow.findViewById(R.id.scroll);
472        mScrollView.setVerticalScrollBarEnabled(false); // less drawing during pulldowns
473        if (!mNotificationPanelIsFullScreenWidth) {
474            mScrollView.setSystemUiVisibility(
475                    View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER |
476                    View.STATUS_BAR_DISABLE_NOTIFICATION_ICONS |
477                    View.STATUS_BAR_DISABLE_CLOCK);
478        }
479
480        mTicker = new MyTicker(context, mStatusBarView);
481
482        TickerView tickerView = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
483        tickerView.mTicker = mTicker;
484
485        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
486
487        // set the inital view visibility
488        setAreThereNotifications();
489
490        // Other icons
491        mLocationController = new LocationController(mContext); // will post a notification
492        mBatteryController = new BatteryController(mContext);
493        mBatteryController.addIconView((ImageView)mStatusBarView.findViewById(R.id.battery));
494        mNetworkController = new NetworkController(mContext);
495        mBluetoothController = new BluetoothController(mContext);
496        final SignalClusterView signalCluster =
497                (SignalClusterView)mStatusBarView.findViewById(R.id.signal_cluster);
498
499
500        mNetworkController.addSignalCluster(signalCluster);
501        signalCluster.setNetworkController(mNetworkController);
502
503        mEmergencyCallLabel = (TextView)mStatusBarWindow.findViewById(R.id.emergency_calls_only);
504        if (mEmergencyCallLabel != null) {
505            mNetworkController.addEmergencyLabelView(mEmergencyCallLabel);
506            mEmergencyCallLabel.setOnClickListener(new View.OnClickListener() {
507                public void onClick(View v) { }});
508            mEmergencyCallLabel.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
509                @Override
510                public void onLayoutChange(View v, int left, int top, int right, int bottom,
511                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
512                    updateCarrierLabelVisibility(false);
513                }});
514        }
515
516        mCarrierLabel = (TextView)mStatusBarWindow.findViewById(R.id.carrier_label);
517        mShowCarrierInPanel = (mCarrierLabel != null);
518        Slog.v(TAG, "carrierlabel=" + mCarrierLabel + " show=" + mShowCarrierInPanel);
519        if (mShowCarrierInPanel) {
520            mCarrierLabel.setVisibility(mCarrierLabelVisible ? View.VISIBLE : View.INVISIBLE);
521
522            // for mobile devices, we always show mobile connection info here (SPN/PLMN)
523            // for other devices, we show whatever network is connected
524            if (mNetworkController.hasMobileDataFeature()) {
525                mNetworkController.addMobileLabelView(mCarrierLabel);
526            } else {
527                mNetworkController.addCombinedLabelView(mCarrierLabel);
528            }
529
530            // set up the dynamic hide/show of the label
531            mPile.setOnSizeChangedListener(new OnSizeChangedListener() {
532                @Override
533                public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {
534                    updateCarrierLabelVisibility(false);
535                }
536            });
537        }
538
539        // Quick Settings (where available, some restrictions apply)
540        if (mHasSettingsPanel) {
541            // first, figure out where quick settings should be inflated
542            final View settings_stub;
543            if (mHasFlipSettings) {
544                // a version of quick settings that flips around behind the notifications
545                settings_stub = mStatusBarWindow.findViewById(R.id.flip_settings_stub);
546                if (settings_stub != null) {
547                    mFlipSettingsView = ((ViewStub)settings_stub).inflate();
548                    mFlipSettingsView.setVisibility(View.GONE);
549                    mFlipSettingsView.setVerticalScrollBarEnabled(false);
550                }
551            } else {
552                // full quick settings panel
553                settings_stub = mStatusBarWindow.findViewById(R.id.quick_settings_stub);
554                if (settings_stub != null) {
555                    mSettingsPanel = (SettingsPanelView) ((ViewStub)settings_stub).inflate();
556                } else {
557                    mSettingsPanel = (SettingsPanelView) mStatusBarWindow.findViewById(R.id.settings_panel);
558                }
559
560                if (mSettingsPanel != null) {
561                    if (!ActivityManager.isHighEndGfx()) {
562                        mSettingsPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
563                                R.color.notification_panel_solid_background)));
564                    }
565                }
566            }
567
568            // wherever you find it, Quick Settings needs a container to survive
569            mSettingsContainer = (QuickSettingsContainerView)
570                    mStatusBarWindow.findViewById(R.id.quick_settings_container);
571            if (mSettingsContainer != null) {
572                mQS = new QuickSettings(mContext, mSettingsContainer);
573                if (!mNotificationPanelIsFullScreenWidth) {
574                    mSettingsContainer.setSystemUiVisibility(
575                            View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER
576                            | View.STATUS_BAR_DISABLE_SYSTEM_INFO);
577                }
578                if (mSettingsPanel != null) {
579                    mSettingsPanel.setQuickSettings(mQS);
580                }
581                mQS.setService(this);
582                mQS.setBar(mStatusBarView);
583                mQS.setup(mNetworkController, mBluetoothController, mBatteryController,
584                        mLocationController);
585            } else {
586                mQS = null; // fly away, be free
587            }
588        }
589
590        mClingShown = ! (DEBUG_CLINGS
591            || !Prefs.read(mContext).getBoolean(Prefs.SHOWN_QUICK_SETTINGS_HELP, false));
592
593        if (!ENABLE_NOTIFICATION_PANEL_CLING || ActivityManager.isRunningInTestHarness()) {
594            mClingShown = true;
595        }
596
597//        final ImageView wimaxRSSI =
598//                (ImageView)sb.findViewById(R.id.wimax_signal);
599//        if (wimaxRSSI != null) {
600//            mNetworkController.addWimaxIconView(wimaxRSSI);
601//        }
602
603        // receive broadcasts
604        IntentFilter filter = new IntentFilter();
605        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
606        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
607        filter.addAction(Intent.ACTION_SCREEN_OFF);
608        filter.addAction(Intent.ACTION_SCREEN_ON);
609        context.registerReceiver(mBroadcastReceiver, filter);
610
611        // listen for USER_SETUP_COMPLETE setting (per-user)
612        resetUserSetupObserver();
613
614        return mStatusBarView;
615    }
616
617    @Override
618    protected View getStatusBarView() {
619        return mStatusBarView;
620    }
621
622    @Override
623    protected WindowManager.LayoutParams getRecentsLayoutParams(LayoutParams layoutParams) {
624        boolean opaque = false;
625        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
626                layoutParams.width,
627                layoutParams.height,
628                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
629                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
630                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
631                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
632                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
633        if (ActivityManager.isHighEndGfx()) {
634            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
635        } else {
636            lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
637            lp.dimAmount = 0.75f;
638        }
639        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
640        lp.setTitle("RecentsPanel");
641        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
642        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
643        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
644        return lp;
645    }
646
647    @Override
648    protected WindowManager.LayoutParams getSearchLayoutParams(LayoutParams layoutParams) {
649        boolean opaque = false;
650        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
651                LayoutParams.MATCH_PARENT,
652                LayoutParams.MATCH_PARENT,
653                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
654                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
655                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
656                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
657                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
658        if (ActivityManager.isHighEndGfx()) {
659            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
660        }
661        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
662        lp.setTitle("SearchPanel");
663        // TODO: Define custom animation for Search panel
664        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
665        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
666        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
667        return lp;
668    }
669
670    @Override
671    protected void updateSearchPanel() {
672        super.updateSearchPanel();
673        mSearchPanelView.setStatusBarView(mNavigationBarView);
674        mNavigationBarView.setDelegateView(mSearchPanelView);
675    }
676
677    @Override
678    public void showSearchPanel() {
679        super.showSearchPanel();
680        WindowManager.LayoutParams lp =
681            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
682        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
683        mWindowManager.updateViewLayout(mNavigationBarView, lp);
684    }
685
686    @Override
687    public void hideSearchPanel() {
688        super.hideSearchPanel();
689        WindowManager.LayoutParams lp =
690            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
691        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
692        mWindowManager.updateViewLayout(mNavigationBarView, lp);
693    }
694
695    protected int getStatusBarGravity() {
696        return Gravity.TOP | Gravity.FILL_HORIZONTAL;
697    }
698
699    public int getStatusBarHeight() {
700        if (mNaturalBarHeight < 0) {
701            final Resources res = mContext.getResources();
702            mNaturalBarHeight =
703                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
704        }
705        return mNaturalBarHeight;
706    }
707
708    private View.OnClickListener mRecentsClickListener = new View.OnClickListener() {
709        public void onClick(View v) {
710            toggleRecentApps();
711        }
712    };
713
714    private int mShowSearchHoldoff = 0;
715    private Runnable mShowSearchPanel = new Runnable() {
716        public void run() {
717            showSearchPanel();
718            awakenDreams();
719        }
720    };
721
722    View.OnTouchListener mHomeSearchActionListener = new View.OnTouchListener() {
723        public boolean onTouch(View v, MotionEvent event) {
724            switch(event.getAction()) {
725            case MotionEvent.ACTION_DOWN:
726                if (!shouldDisableNavbarGestures() && !inKeyguardRestrictedInputMode()) {
727                    mHandler.removeCallbacks(mShowSearchPanel);
728                    mHandler.postDelayed(mShowSearchPanel, mShowSearchHoldoff);
729                }
730            break;
731
732            case MotionEvent.ACTION_UP:
733            case MotionEvent.ACTION_CANCEL:
734                mHandler.removeCallbacks(mShowSearchPanel);
735                awakenDreams();
736            break;
737        }
738        return false;
739        }
740    };
741
742    private void awakenDreams() {
743        if (mDreamManager != null) {
744            try {
745                mDreamManager.awaken();
746            } catch (RemoteException e) {
747                // fine, stay asleep then
748            }
749        }
750    }
751
752    private void prepareNavigationBarView() {
753        mNavigationBarView.reorient();
754
755        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
756        mNavigationBarView.getRecentsButton().setOnTouchListener(getRecentTasksLoader());
757        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeSearchActionListener);
758        updateSearchPanel();
759    }
760
761    // For small-screen devices (read: phones) that lack hardware navigation buttons
762    private void addNavigationBar() {
763        if (DEBUG) Slog.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
764        if (mNavigationBarView == null) return;
765
766        prepareNavigationBarView();
767
768        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
769    }
770
771    private void repositionNavigationBar() {
772        if (mNavigationBarView == null) return;
773
774        prepareNavigationBarView();
775
776        mWindowManager.updateViewLayout(mNavigationBarView, getNavigationBarLayoutParams());
777    }
778
779    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
780        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
781                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
782                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
783                    0
784                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
785                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
786                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
787                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
788                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
789                PixelFormat.OPAQUE);
790        // this will allow the navbar to run in an overlay on devices that support this
791        if (ActivityManager.isHighEndGfx()) {
792            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
793        }
794
795        lp.setTitle("NavigationBar");
796        lp.windowAnimations = 0;
797        return lp;
798    }
799
800    private void addIntruderView() {
801        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
802                ViewGroup.LayoutParams.MATCH_PARENT,
803                ViewGroup.LayoutParams.WRAP_CONTENT,
804                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, // above the status bar!
805                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
806                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
807                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
808                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
809                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
810                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
811                PixelFormat.TRANSLUCENT);
812        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
813        //lp.y += height * 1.5; // FIXME
814        lp.setTitle("IntruderAlert");
815        lp.packageName = mContext.getPackageName();
816        lp.windowAnimations = R.style.Animation_StatusBar_IntruderAlert;
817
818        mWindowManager.addView(mIntruderAlertView, lp);
819    }
820
821    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
822        if (SPEW) Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
823                + " icon=" + icon);
824        StatusBarIconView view = new StatusBarIconView(mContext, slot, null);
825        view.set(icon);
826        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
827    }
828
829    public void updateIcon(String slot, int index, int viewIndex,
830            StatusBarIcon old, StatusBarIcon icon) {
831        if (SPEW) Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
832                + " old=" + old + " icon=" + icon);
833        StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
834        view.set(icon);
835    }
836
837    public void removeIcon(String slot, int index, int viewIndex) {
838        if (SPEW) Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
839        mStatusIcons.removeViewAt(viewIndex);
840    }
841
842    public void addNotification(IBinder key, StatusBarNotification notification) {
843        /* if (DEBUG) */ Slog.d(TAG, "addNotification score=" + notification.score);
844        StatusBarIconView iconView = addNotificationViews(key, notification);
845        if (iconView == null) return;
846
847        boolean immersive = false;
848        try {
849            immersive = ActivityManagerNative.getDefault().isTopActivityImmersive();
850            if (DEBUG) {
851                Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
852            }
853        } catch (RemoteException ex) {
854        }
855
856        /*
857         * DISABLED due to missing API
858        if (ENABLE_INTRUDERS && (
859                   // TODO(dsandler): Only if the screen is on
860                notification.notification.intruderView != null)) {
861            Slog.d(TAG, "Presenting high-priority notification");
862            // special new transient ticker mode
863            // 1. Populate mIntruderAlertView
864
865            if (notification.notification.intruderView == null) {
866                Slog.e(TAG, notification.notification.toString() + " wanted to intrude but intruderView was null");
867                return;
868            }
869
870            // bind the click event to the content area
871            PendingIntent contentIntent = notification.notification.contentIntent;
872            final View.OnClickListener listener = (contentIntent != null)
873                    ? new NotificationClicker(contentIntent,
874                            notification.pkg, notification.tag, notification.id)
875                    : null;
876
877            mIntruderAlertView.applyIntruderContent(notification.notification.intruderView, listener);
878
879            mCurrentlyIntrudingNotification = notification;
880
881            // 2. Animate mIntruderAlertView in
882            mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
883
884            // 3. Set alarm to age the notification off (TODO)
885            mHandler.removeMessages(MSG_HIDE_INTRUDER);
886            if (INTRUDER_ALERT_DECAY_MS > 0) {
887                mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, INTRUDER_ALERT_DECAY_MS);
888            }
889        } else
890         */
891
892        if (notification.notification.fullScreenIntent != null) {
893            // Stop screensaver if the notification has a full-screen intent.
894            // (like an incoming phone call)
895            awakenDreams();
896
897            // not immersive & a full-screen alert should be shown
898            Slog.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
899            try {
900                notification.notification.fullScreenIntent.send();
901            } catch (PendingIntent.CanceledException e) {
902            }
903        } else {
904            // usual case: status bar visible & not immersive
905
906            // show the ticker if there isn't an intruder too
907            if (mCurrentlyIntrudingNotification == null) {
908                tick(null, notification, true);
909            }
910        }
911
912        // Recalculate the position of the sliding windows and the titles.
913        setAreThereNotifications();
914        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
915    }
916
917    public void removeNotification(IBinder key) {
918        StatusBarNotification old = removeNotificationViews(key);
919        if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
920
921        if (old != null) {
922            // Cancel the ticker if it's still running
923            mTicker.removeEntry(old);
924
925            // Recalculate the position of the sliding windows and the titles.
926            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
927
928            if (ENABLE_INTRUDERS && old == mCurrentlyIntrudingNotification) {
929                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
930            }
931
932            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
933                animateCollapsePanels();
934            }
935        }
936
937        setAreThereNotifications();
938    }
939
940    private void updateShowSearchHoldoff() {
941        mShowSearchHoldoff = mContext.getResources().getInteger(
942            R.integer.config_show_search_delay);
943    }
944
945    private void loadNotificationShade() {
946        if (mPile == null) return;
947
948        int N = mNotificationData.size();
949
950        ArrayList<View> toShow = new ArrayList<View>();
951
952        final boolean provisioned = isDeviceProvisioned();
953        // If the device hasn't been through Setup, we only show system notifications
954        for (int i=0; i<N; i++) {
955            Entry ent = mNotificationData.get(N-i-1);
956            if (!(provisioned || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
957            if (!notificationIsForCurrentUser(ent.notification)) continue;
958            toShow.add(ent.row);
959        }
960
961        ArrayList<View> toRemove = new ArrayList<View>();
962        for (int i=0; i<mPile.getChildCount(); i++) {
963            View child = mPile.getChildAt(i);
964            if (!toShow.contains(child)) {
965                toRemove.add(child);
966            }
967        }
968
969        for (View remove : toRemove) {
970            mPile.removeView(remove);
971        }
972
973        for (int i=0; i<toShow.size(); i++) {
974            View v = toShow.get(i);
975            if (v.getParent() == null) {
976                mPile.addView(v, i);
977            }
978        }
979
980        if (mSettingsButton != null) {
981            mSettingsButton.setEnabled(isDeviceProvisioned());
982        }
983    }
984
985    @Override
986    protected void updateNotificationIcons() {
987        if (mNotificationIcons == null) return;
988
989        loadNotificationShade();
990
991        final LinearLayout.LayoutParams params
992            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
993
994        int N = mNotificationData.size();
995
996        if (DEBUG) {
997            Slog.d(TAG, "refreshing icons: " + N + " notifications, mNotificationIcons=" + mNotificationIcons);
998        }
999
1000        ArrayList<View> toShow = new ArrayList<View>();
1001
1002        final boolean provisioned = isDeviceProvisioned();
1003        // If the device hasn't been through Setup, we only show system notifications
1004        for (int i=0; i<N; i++) {
1005            Entry ent = mNotificationData.get(N-i-1);
1006            if (!((provisioned && ent.notification.score >= HIDE_ICONS_BELOW_SCORE)
1007                    || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
1008            if (!notificationIsForCurrentUser(ent.notification)) continue;
1009            toShow.add(ent.icon);
1010        }
1011
1012        ArrayList<View> toRemove = new ArrayList<View>();
1013        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
1014            View child = mNotificationIcons.getChildAt(i);
1015            if (!toShow.contains(child)) {
1016                toRemove.add(child);
1017            }
1018        }
1019
1020        for (View remove : toRemove) {
1021            mNotificationIcons.removeView(remove);
1022        }
1023
1024        for (int i=0; i<toShow.size(); i++) {
1025            View v = toShow.get(i);
1026            if (v.getParent() == null) {
1027                mNotificationIcons.addView(v, i, params);
1028            }
1029        }
1030    }
1031
1032    protected void updateCarrierLabelVisibility(boolean force) {
1033        if (!mShowCarrierInPanel) return;
1034        // The idea here is to only show the carrier label when there is enough room to see it,
1035        // i.e. when there aren't enough notifications to fill the panel.
1036        if (DEBUG) {
1037            Slog.d(TAG, String.format("pileh=%d scrollh=%d carrierh=%d",
1038                    mPile.getHeight(), mScrollView.getHeight(), mCarrierLabelHeight));
1039        }
1040
1041        final boolean emergencyCallsShownElsewhere = mEmergencyCallLabel != null;
1042        final boolean makeVisible =
1043            !(emergencyCallsShownElsewhere && mNetworkController.isEmergencyOnly())
1044            && mPile.getHeight() < (mNotificationPanel.getHeight() - mCarrierLabelHeight - mNotificationHeaderHeight)
1045            && mScrollView.getVisibility() == View.VISIBLE;
1046
1047        if (force || mCarrierLabelVisible != makeVisible) {
1048            mCarrierLabelVisible = makeVisible;
1049            if (DEBUG) {
1050                Slog.d(TAG, "making carrier label " + (makeVisible?"visible":"invisible"));
1051            }
1052            mCarrierLabel.animate().cancel();
1053            if (makeVisible) {
1054                mCarrierLabel.setVisibility(View.VISIBLE);
1055            }
1056            mCarrierLabel.animate()
1057                .alpha(makeVisible ? 1f : 0f)
1058                //.setStartDelay(makeVisible ? 500 : 0)
1059                //.setDuration(makeVisible ? 750 : 100)
1060                .setDuration(150)
1061                .setListener(makeVisible ? null : new AnimatorListenerAdapter() {
1062                    @Override
1063                    public void onAnimationEnd(Animator animation) {
1064                        if (!mCarrierLabelVisible) { // race
1065                            mCarrierLabel.setVisibility(View.INVISIBLE);
1066                            mCarrierLabel.setAlpha(0f);
1067                        }
1068                    }
1069                })
1070                .start();
1071        }
1072    }
1073
1074    @Override
1075    protected void setAreThereNotifications() {
1076        final boolean any = mNotificationData.size() > 0;
1077
1078        final boolean clearable = any && mNotificationData.hasClearableItems();
1079
1080        if (DEBUG) {
1081            Slog.d(TAG, "setAreThereNotifications: N=" + mNotificationData.size()
1082                    + " any=" + any + " clearable=" + clearable);
1083        }
1084
1085        if (mHasFlipSettings
1086                && mFlipSettingsView != null
1087                && mFlipSettingsView.getVisibility() == View.VISIBLE
1088                && mScrollView.getVisibility() != View.VISIBLE) {
1089            // the flip settings panel is unequivocally showing; we should not be shown
1090            mClearButton.setVisibility(View.INVISIBLE);
1091        } else if (mClearButton.isShown()) {
1092            if (clearable != (mClearButton.getAlpha() == 1.0f)) {
1093                ObjectAnimator clearAnimation = ObjectAnimator.ofFloat(
1094                        mClearButton, "alpha", clearable ? 1.0f : 0.0f).setDuration(250);
1095                clearAnimation.addListener(new AnimatorListenerAdapter() {
1096                    @Override
1097                    public void onAnimationEnd(Animator animation) {
1098                        if (mClearButton.getAlpha() <= 0.0f) {
1099                            mClearButton.setVisibility(View.INVISIBLE);
1100                        }
1101                    }
1102
1103                    @Override
1104                    public void onAnimationStart(Animator animation) {
1105                        if (mClearButton.getAlpha() <= 0.0f) {
1106                            mClearButton.setVisibility(View.VISIBLE);
1107                        }
1108                    }
1109                });
1110                clearAnimation.start();
1111            }
1112        } else {
1113            mClearButton.setAlpha(clearable ? 1.0f : 0.0f);
1114            mClearButton.setVisibility(clearable ? View.VISIBLE : View.INVISIBLE);
1115        }
1116        mClearButton.setEnabled(clearable);
1117
1118        final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
1119        final boolean showDot = (any&&!areLightsOn());
1120        if (showDot != (nlo.getAlpha() == 1.0f)) {
1121            if (showDot) {
1122                nlo.setAlpha(0f);
1123                nlo.setVisibility(View.VISIBLE);
1124            }
1125            nlo.animate()
1126                .alpha(showDot?1:0)
1127                .setDuration(showDot?750:250)
1128                .setInterpolator(new AccelerateInterpolator(2.0f))
1129                .setListener(showDot ? null : new AnimatorListenerAdapter() {
1130                    @Override
1131                    public void onAnimationEnd(Animator _a) {
1132                        nlo.setVisibility(View.GONE);
1133                    }
1134                })
1135                .start();
1136        }
1137
1138        updateCarrierLabelVisibility(false);
1139    }
1140
1141    public void showClock(boolean show) {
1142        if (mStatusBarView == null) return;
1143        View clock = mStatusBarView.findViewById(R.id.clock);
1144        if (clock != null) {
1145            clock.setVisibility(show ? View.VISIBLE : View.GONE);
1146        }
1147    }
1148
1149    /**
1150     * State is one or more of the DISABLE constants from StatusBarManager.
1151     */
1152    public void disable(int state) {
1153        final int old = mDisabled;
1154        final int diff = state ^ old;
1155        mDisabled = state;
1156
1157        if (DEBUG) {
1158            Slog.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
1159                old, state, diff));
1160        }
1161
1162        StringBuilder flagdbg = new StringBuilder();
1163        flagdbg.append("disable: < ");
1164        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
1165        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
1166        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
1167        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
1168        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
1169        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
1170        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "TICKER" : "ticker");
1171        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
1172        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
1173        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
1174        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
1175        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
1176        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
1177        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
1178        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
1179        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
1180        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
1181        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
1182        flagdbg.append(">");
1183        Slog.d(TAG, flagdbg.toString());
1184
1185        if ((diff & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1186            mSystemIconArea.animate().cancel();
1187            if ((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1188                mSystemIconArea.animate()
1189                    .alpha(0f)
1190                    .translationY(mNaturalBarHeight*0.5f)
1191                    .setDuration(175)
1192                    .setInterpolator(new DecelerateInterpolator(1.5f))
1193                    .setListener(mMakeIconsInvisible)
1194                    .start();
1195            } else {
1196                mSystemIconArea.setVisibility(View.VISIBLE);
1197                mSystemIconArea.animate()
1198                    .alpha(1f)
1199                    .translationY(0)
1200                    .setStartDelay(0)
1201                    .setInterpolator(new DecelerateInterpolator(1.5f))
1202                    .setDuration(175)
1203                    .start();
1204            }
1205        }
1206
1207        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
1208            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
1209            showClock(show);
1210        }
1211        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1212            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
1213                animateCollapsePanels();
1214            }
1215        }
1216
1217        if ((diff & (StatusBarManager.DISABLE_HOME
1218                        | StatusBarManager.DISABLE_RECENT
1219                        | StatusBarManager.DISABLE_BACK)) != 0) {
1220            // the nav bar will take care of these
1221            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
1222
1223            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
1224                // close recents if it's visible
1225                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1226                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1227            }
1228        }
1229
1230        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1231            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1232                if (mTicking) {
1233                    haltTicker();
1234                }
1235
1236                mNotificationIcons.animate()
1237                    .alpha(0f)
1238                    .translationY(mNaturalBarHeight*0.5f)
1239                    .setDuration(175)
1240                    .setInterpolator(new DecelerateInterpolator(1.5f))
1241                    .setListener(mMakeIconsInvisible)
1242                    .start();
1243            } else {
1244                mNotificationIcons.setVisibility(View.VISIBLE);
1245                mNotificationIcons.animate()
1246                    .alpha(1f)
1247                    .translationY(0)
1248                    .setStartDelay(0)
1249                    .setInterpolator(new DecelerateInterpolator(1.5f))
1250                    .setDuration(175)
1251                    .start();
1252            }
1253        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1254            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1255                haltTicker();
1256            }
1257        }
1258    }
1259
1260    @Override
1261    protected BaseStatusBar.H createHandler() {
1262        return new PhoneStatusBar.H();
1263    }
1264
1265    /**
1266     * All changes to the status bar and notifications funnel through here and are batched.
1267     */
1268    private class H extends BaseStatusBar.H {
1269        public void handleMessage(Message m) {
1270            super.handleMessage(m);
1271            switch (m.what) {
1272                case MSG_OPEN_NOTIFICATION_PANEL:
1273                    animateExpandNotificationsPanel();
1274                    break;
1275                case MSG_OPEN_SETTINGS_PANEL:
1276                    animateExpandSettingsPanel();
1277                    break;
1278                case MSG_CLOSE_PANELS:
1279                    animateCollapsePanels();
1280                    break;
1281                case MSG_SHOW_INTRUDER:
1282                    setIntruderAlertVisibility(true);
1283                    break;
1284                case MSG_HIDE_INTRUDER:
1285                    setIntruderAlertVisibility(false);
1286                    mCurrentlyIntrudingNotification = null;
1287                    break;
1288            }
1289        }
1290    }
1291
1292    public Handler getHandler() {
1293        return mHandler;
1294    }
1295
1296    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1297        public void onFocusChange(View v, boolean hasFocus) {
1298            // Because 'v' is a ViewGroup, all its children will be (un)selected
1299            // too, which allows marqueeing to work.
1300            v.setSelected(hasFocus);
1301        }
1302    };
1303
1304    void makeExpandedVisible(boolean revealAfterDraw) {
1305        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1306        if (mExpandedVisible) {
1307            return;
1308        }
1309
1310        mExpandedVisible = true;
1311        mPile.setLayoutTransitionsEnabled(true);
1312        if (mNavigationBarView != null)
1313            mNavigationBarView.setSlippery(true);
1314
1315        updateCarrierLabelVisibility(true);
1316
1317        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1318
1319        // Expand the window to encompass the full screen in anticipation of the drag.
1320        // This is only possible to do atomically because the status bar is at the top of the screen!
1321        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1322        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1323        lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1324        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
1325        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1326
1327        // Updating the window layout will force an expensive traversal/redraw.
1328        // Kick off the reveal animation after this is complete to avoid animation latency.
1329        if (revealAfterDraw) {
1330//            mHandler.post(mStartRevealAnimation);
1331        }
1332
1333        visibilityChanged(true);
1334    }
1335
1336    public void animateCollapsePanels() {
1337        animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1338    }
1339
1340    public void animateCollapsePanels(int flags) {
1341        if (SPEW) {
1342            Slog.d(TAG, "animateCollapse():"
1343                    + " mExpandedVisible=" + mExpandedVisible
1344                    + " mAnimating=" + mAnimating
1345                    + " mAnimatingReveal=" + mAnimatingReveal
1346                    + " mAnimY=" + mAnimY
1347                    + " mAnimVel=" + mAnimVel
1348                    + " flags=" + flags);
1349        }
1350
1351        if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
1352            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1353            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1354        }
1355
1356        if ((flags & CommandQueue.FLAG_EXCLUDE_SEARCH_PANEL) == 0) {
1357            mHandler.removeMessages(MSG_CLOSE_SEARCH_PANEL);
1358            mHandler.sendEmptyMessage(MSG_CLOSE_SEARCH_PANEL);
1359        }
1360
1361        mStatusBarView.collapseAllPanels(true);
1362    }
1363
1364    public ViewPropertyAnimator setVisibilityWhenDone(
1365            final ViewPropertyAnimator a, final View v, final int vis) {
1366        a.setListener(new AnimatorListenerAdapter() {
1367            @Override
1368            public void onAnimationEnd(Animator animation) {
1369                v.setVisibility(vis);
1370                a.setListener(null); // oneshot
1371            }
1372        });
1373        return a;
1374    }
1375
1376    public Animator setVisibilityWhenDone(
1377            final Animator a, final View v, final int vis) {
1378        a.addListener(new AnimatorListenerAdapter() {
1379            @Override
1380            public void onAnimationEnd(Animator animation) {
1381                v.setVisibility(vis);
1382            }
1383        });
1384        return a;
1385    }
1386
1387    public Animator interpolator(TimeInterpolator ti, Animator a) {
1388        a.setInterpolator(ti);
1389        return a;
1390    }
1391
1392    public Animator startDelay(int d, Animator a) {
1393        a.setStartDelay(d);
1394        return a;
1395    }
1396
1397    public Animator start(Animator a) {
1398        a.start();
1399        return a;
1400    }
1401
1402    final TimeInterpolator mAccelerateInterpolator = new AccelerateInterpolator();
1403    final TimeInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
1404    final int FLIP_DURATION_OUT = 125;
1405    final int FLIP_DURATION_IN = 225;
1406    final int FLIP_DURATION = (FLIP_DURATION_IN + FLIP_DURATION_OUT);
1407
1408    Animator mScrollViewAnim, mFlipSettingsViewAnim, mNotificationButtonAnim,
1409        mSettingsButtonAnim, mClearButtonAnim;
1410
1411    @Override
1412    public void animateExpandNotificationsPanel() {
1413        if (SPEW) Slog.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
1414        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1415            return ;
1416        }
1417
1418        mNotificationPanel.expand();
1419        if (mHasFlipSettings && mScrollView.getVisibility() != View.VISIBLE) {
1420            flipToNotifications();
1421        }
1422
1423        if (false) postStartTracing();
1424    }
1425
1426    public void flipToNotifications() {
1427        if (mFlipSettingsViewAnim != null) mFlipSettingsViewAnim.cancel();
1428        if (mScrollViewAnim != null) mScrollViewAnim.cancel();
1429        if (mSettingsButtonAnim != null) mSettingsButtonAnim.cancel();
1430        if (mNotificationButtonAnim != null) mNotificationButtonAnim.cancel();
1431        if (mClearButtonAnim != null) mClearButtonAnim.cancel();
1432
1433        mScrollView.setVisibility(View.VISIBLE);
1434        mScrollViewAnim = start(
1435            startDelay(FLIP_DURATION_OUT,
1436                interpolator(mDecelerateInterpolator,
1437                    ObjectAnimator.ofFloat(mScrollView, View.SCALE_X, 0f, 1f)
1438                        .setDuration(FLIP_DURATION_IN)
1439                    )));
1440        mFlipSettingsViewAnim = start(
1441            setVisibilityWhenDone(
1442                interpolator(mAccelerateInterpolator,
1443                        ObjectAnimator.ofFloat(mFlipSettingsView, View.SCALE_X, 1f, 0f)
1444                        )
1445                    .setDuration(FLIP_DURATION_OUT),
1446                mFlipSettingsView, View.INVISIBLE));
1447        mNotificationButtonAnim = start(
1448            setVisibilityWhenDone(
1449                ObjectAnimator.ofFloat(mNotificationButton, View.ALPHA, 0f)
1450                    .setDuration(FLIP_DURATION),
1451                mNotificationButton, View.INVISIBLE));
1452        mSettingsButton.setVisibility(View.VISIBLE);
1453        mSettingsButtonAnim = start(
1454            ObjectAnimator.ofFloat(mSettingsButton, View.ALPHA, 1f)
1455                .setDuration(FLIP_DURATION));
1456        mClearButton.setVisibility(View.VISIBLE);
1457        mClearButton.setAlpha(0f);
1458        setAreThereNotifications(); // this will show/hide the button as necessary
1459        mNotificationPanel.postDelayed(new Runnable() {
1460            public void run() {
1461                updateCarrierLabelVisibility(false);
1462            }
1463        }, FLIP_DURATION - 150);
1464    }
1465
1466    @Override
1467    public void animateExpandSettingsPanel() {
1468        if (SPEW) Slog.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
1469        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1470            return;
1471        }
1472
1473        if (mHasFlipSettings) {
1474            mNotificationPanel.expand();
1475            if (mFlipSettingsView.getVisibility() != View.VISIBLE) {
1476                flipToSettings();
1477            }
1478        } else if (mSettingsPanel != null) {
1479            mSettingsPanel.expand();
1480        }
1481
1482        if (false) postStartTracing();
1483    }
1484
1485    public void switchToSettings() {
1486        mFlipSettingsView.setScaleX(1f);
1487        mFlipSettingsView.setVisibility(View.VISIBLE);
1488        mSettingsButton.setVisibility(View.GONE);
1489        mScrollView.setVisibility(View.GONE);
1490        mNotificationButton.setVisibility(View.VISIBLE);
1491        mNotificationButton.setAlpha(1f);
1492        mClearButton.setVisibility(View.GONE);
1493    }
1494
1495    public void flipToSettings() {
1496        if (mFlipSettingsViewAnim != null) mFlipSettingsViewAnim.cancel();
1497        if (mScrollViewAnim != null) mScrollViewAnim.cancel();
1498        if (mSettingsButtonAnim != null) mSettingsButtonAnim.cancel();
1499        if (mNotificationButtonAnim != null) mNotificationButtonAnim.cancel();
1500        if (mClearButtonAnim != null) mClearButtonAnim.cancel();
1501
1502        mFlipSettingsView.setVisibility(View.VISIBLE);
1503        mFlipSettingsView.setScaleX(0f);
1504        mFlipSettingsViewAnim = start(
1505            startDelay(FLIP_DURATION_OUT,
1506                interpolator(mDecelerateInterpolator,
1507                    ObjectAnimator.ofFloat(mFlipSettingsView, View.SCALE_X, 0f, 1f)
1508                        .setDuration(FLIP_DURATION_IN)
1509                    )));
1510        mScrollViewAnim = start(
1511            setVisibilityWhenDone(
1512                interpolator(mAccelerateInterpolator,
1513                        ObjectAnimator.ofFloat(mScrollView, View.SCALE_X, 1f, 0f)
1514                        )
1515                    .setDuration(FLIP_DURATION_OUT),
1516                mScrollView, View.INVISIBLE));
1517        mSettingsButtonAnim = start(
1518            setVisibilityWhenDone(
1519                ObjectAnimator.ofFloat(mSettingsButton, View.ALPHA, 0f)
1520                    .setDuration(FLIP_DURATION),
1521                    mScrollView, View.INVISIBLE));
1522        mNotificationButton.setVisibility(View.VISIBLE);
1523        mNotificationButtonAnim = start(
1524            ObjectAnimator.ofFloat(mNotificationButton, View.ALPHA, 1f)
1525                .setDuration(FLIP_DURATION));
1526        mClearButtonAnim = start(
1527            setVisibilityWhenDone(
1528                ObjectAnimator.ofFloat(mClearButton, View.ALPHA, 0f)
1529                .setDuration(FLIP_DURATION),
1530                mClearButton, View.INVISIBLE));
1531        mNotificationPanel.postDelayed(new Runnable() {
1532            public void run() {
1533                updateCarrierLabelVisibility(false);
1534            }
1535        }, FLIP_DURATION - 150);
1536    }
1537
1538    public void flipPanels() {
1539        if (mHasFlipSettings) {
1540            if (mFlipSettingsView.getVisibility() != View.VISIBLE) {
1541                flipToSettings();
1542            } else {
1543                flipToNotifications();
1544            }
1545        }
1546    }
1547
1548    public void animateCollapseQuickSettings() {
1549        mStatusBarView.collapseAllPanels(true);
1550    }
1551
1552    void makeExpandedInvisibleSoon() {
1553        mHandler.postDelayed(new Runnable() { public void run() { makeExpandedInvisible(); }}, 50);
1554    }
1555
1556    void makeExpandedInvisible() {
1557        if (SPEW) Slog.d(TAG, "makeExpandedInvisible: mExpandedVisible=" + mExpandedVisible
1558                + " mExpandedVisible=" + mExpandedVisible);
1559
1560        if (!mExpandedVisible) {
1561            return;
1562        }
1563
1564        // Ensure the panel is fully collapsed (just in case; bug 6765842, 7260868)
1565        mStatusBarView.collapseAllPanels(/*animate=*/ false);
1566
1567        if (mHasFlipSettings) {
1568            // reset things to their proper state
1569            mScrollView.setScaleX(1f);
1570            mScrollView.setVisibility(View.VISIBLE);
1571            mSettingsButton.setAlpha(1f);
1572            mSettingsButton.setVisibility(View.VISIBLE);
1573            mNotificationPanel.setVisibility(View.GONE);
1574            mFlipSettingsView.setVisibility(View.GONE);
1575            mNotificationButton.setVisibility(View.GONE);
1576            setAreThereNotifications(); // show the clear button
1577        }
1578
1579        mExpandedVisible = false;
1580        mPile.setLayoutTransitionsEnabled(false);
1581        if (mNavigationBarView != null)
1582            mNavigationBarView.setSlippery(false);
1583        visibilityChanged(false);
1584
1585        // Shrink the window to the size of the status bar only
1586        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1587        lp.height = getStatusBarHeight();
1588        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1589        lp.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1590        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1591
1592        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1593            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1594        }
1595
1596        // Close any "App info" popups that might have snuck on-screen
1597        dismissPopups();
1598
1599        if (mPostCollapseCleanup != null) {
1600            mPostCollapseCleanup.run();
1601            mPostCollapseCleanup = null;
1602        }
1603    }
1604
1605    /**
1606     * Enables or disables layers on the children of the notifications pile.
1607     *
1608     * When layers are enabled, this method attempts to enable layers for the minimal
1609     * number of children. Only children visible when the notification area is fully
1610     * expanded will receive a layer. The technique used in this method might cause
1611     * more children than necessary to get a layer (at most one extra child with the
1612     * current UI.)
1613     *
1614     * @param layerType {@link View#LAYER_TYPE_NONE} or {@link View#LAYER_TYPE_HARDWARE}
1615     */
1616    private void setPileLayers(int layerType) {
1617        final int count = mPile.getChildCount();
1618
1619        switch (layerType) {
1620            case View.LAYER_TYPE_NONE:
1621                for (int i = 0; i < count; i++) {
1622                    mPile.getChildAt(i).setLayerType(layerType, null);
1623                }
1624                break;
1625            case View.LAYER_TYPE_HARDWARE:
1626                final int[] location = new int[2];
1627                mNotificationPanel.getLocationInWindow(location);
1628
1629                final int left = location[0];
1630                final int top = location[1];
1631                final int right = left + mNotificationPanel.getWidth();
1632                final int bottom = top + getExpandedViewMaxHeight();
1633
1634                final Rect childBounds = new Rect();
1635
1636                for (int i = 0; i < count; i++) {
1637                    final View view = mPile.getChildAt(i);
1638                    view.getLocationInWindow(location);
1639
1640                    childBounds.set(location[0], location[1],
1641                            location[0] + view.getWidth(), location[1] + view.getHeight());
1642
1643                    if (childBounds.intersects(left, top, right, bottom)) {
1644                        view.setLayerType(layerType, null);
1645                    }
1646                }
1647
1648                break;
1649        }
1650    }
1651
1652    public boolean isClinging() {
1653        return mCling != null && mCling.getVisibility() == View.VISIBLE;
1654    }
1655
1656    public void hideCling() {
1657        if (isClinging()) {
1658            mCling.animate().alpha(0f).setDuration(250).start();
1659            mCling.setVisibility(View.GONE);
1660            mSuppressStatusBarDrags = false;
1661        }
1662    }
1663
1664    public void showCling() {
1665        // lazily inflate this to accommodate orientation change
1666        final ViewStub stub = (ViewStub) mStatusBarWindow.findViewById(R.id.status_bar_cling_stub);
1667        if (stub == null) {
1668            mClingShown = true;
1669            return; // no clings on this device
1670        }
1671
1672        mSuppressStatusBarDrags = true;
1673
1674        mHandler.postDelayed(new Runnable() {
1675            @Override
1676            public void run() {
1677                mCling = (ViewGroup) stub.inflate();
1678
1679                mCling.setOnTouchListener(new View.OnTouchListener() {
1680                    @Override
1681                    public boolean onTouch(View v, MotionEvent event) {
1682                        return true; // e eats everything
1683                    }});
1684                mCling.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
1685                    @Override
1686                    public void onClick(View v) {
1687                        hideCling();
1688                    }});
1689
1690                mCling.setAlpha(0f);
1691                mCling.setVisibility(View.VISIBLE);
1692                mCling.animate().alpha(1f);
1693
1694                mClingShown = true;
1695                SharedPreferences.Editor editor = Prefs.edit(mContext);
1696                editor.putBoolean(Prefs.SHOWN_QUICK_SETTINGS_HELP, true);
1697                editor.apply();
1698
1699                makeExpandedVisible(true); // enforce visibility in case the shade is still animating closed
1700                animateExpandNotificationsPanel();
1701
1702                mSuppressStatusBarDrags = false;
1703            }
1704        }, 500);
1705
1706        animateExpandNotificationsPanel();
1707    }
1708
1709    public boolean interceptTouchEvent(MotionEvent event) {
1710        if (SPEW) {
1711            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1712                + mDisabled + " mTracking=" + mTracking);
1713        } else if (CHATTY) {
1714            if (event.getAction() != MotionEvent.ACTION_MOVE) {
1715                Slog.d(TAG, String.format(
1716                            "panel: %s at (%f, %f) mDisabled=0x%08x",
1717                            MotionEvent.actionToString(event.getAction()),
1718                            event.getRawX(), event.getRawY(), mDisabled));
1719            }
1720        }
1721
1722        if (DEBUG_GESTURES) {
1723            mGestureRec.add(event);
1724        }
1725
1726        // Cling (first-run help) handling.
1727        // The cling is supposed to show the first time you drag, or even tap, the status bar.
1728        // It should show the notification panel, then fade in after half a second, giving you
1729        // an explanation of what just happened, as well as teach you how to access quick
1730        // settings (another drag). The user can dismiss the cling by clicking OK or by
1731        // dragging quick settings into view.
1732        final int act = event.getActionMasked();
1733        if (mSuppressStatusBarDrags) {
1734            return true;
1735        } else if (act == MotionEvent.ACTION_UP && !mClingShown) {
1736            showCling();
1737        } else {
1738            hideCling();
1739        }
1740
1741        return false;
1742    }
1743
1744    public GestureRecorder getGestureRecorder() {
1745        return mGestureRec;
1746    }
1747
1748    @Override // CommandQueue
1749    public void setNavigationIconHints(int hints) {
1750        if (hints == mNavigationIconHints) return;
1751
1752        mNavigationIconHints = hints;
1753
1754        if (mNavigationBarView != null) {
1755            mNavigationBarView.setNavigationIconHints(hints);
1756        }
1757    }
1758
1759    @Override // CommandQueue
1760    public void setSystemUiVisibility(int vis, int mask) {
1761        final int oldVal = mSystemUiVisibility;
1762        final int newVal = (oldVal&~mask) | (vis&mask);
1763        final int diff = newVal ^ oldVal;
1764
1765        if (diff != 0) {
1766            mSystemUiVisibility = newVal;
1767
1768            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1769                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1770                if (lightsOut) {
1771                    animateCollapsePanels();
1772                    if (mTicking) {
1773                        haltTicker();
1774                    }
1775                }
1776
1777                if (mNavigationBarView != null) {
1778                    mNavigationBarView.setLowProfile(lightsOut);
1779                }
1780
1781                setStatusBarLowProfile(lightsOut);
1782            }
1783
1784            notifyUiVisibilityChanged();
1785        }
1786    }
1787
1788    private void setStatusBarLowProfile(boolean lightsOut) {
1789        if (mLightsOutAnimation == null) {
1790            final View notifications = mStatusBarView.findViewById(R.id.notification_icon_area);
1791            final View systemIcons = mStatusBarView.findViewById(R.id.statusIcons);
1792            final View signal = mStatusBarView.findViewById(R.id.signal_cluster);
1793            final View battery = mStatusBarView.findViewById(R.id.battery);
1794            final View clock = mStatusBarView.findViewById(R.id.clock);
1795
1796            final AnimatorSet lightsOutAnim = new AnimatorSet();
1797            lightsOutAnim.playTogether(
1798                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 0),
1799                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 0),
1800                    ObjectAnimator.ofFloat(signal, View.ALPHA, 0),
1801                    ObjectAnimator.ofFloat(battery, View.ALPHA, 0.5f),
1802                    ObjectAnimator.ofFloat(clock, View.ALPHA, 0.5f)
1803                );
1804            lightsOutAnim.setDuration(750);
1805
1806            final AnimatorSet lightsOnAnim = new AnimatorSet();
1807            lightsOnAnim.playTogether(
1808                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 1),
1809                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 1),
1810                    ObjectAnimator.ofFloat(signal, View.ALPHA, 1),
1811                    ObjectAnimator.ofFloat(battery, View.ALPHA, 1),
1812                    ObjectAnimator.ofFloat(clock, View.ALPHA, 1)
1813                );
1814            lightsOnAnim.setDuration(250);
1815
1816            mLightsOutAnimation = lightsOutAnim;
1817            mLightsOnAnimation = lightsOnAnim;
1818        }
1819
1820        mLightsOutAnimation.cancel();
1821        mLightsOnAnimation.cancel();
1822
1823        final Animator a = lightsOut ? mLightsOutAnimation : mLightsOnAnimation;
1824        a.start();
1825
1826        setAreThereNotifications();
1827    }
1828
1829    private boolean areLightsOn() {
1830        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
1831    }
1832
1833    public void setLightsOn(boolean on) {
1834        Log.v(TAG, "setLightsOn(" + on + ")");
1835        if (on) {
1836            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1837        } else {
1838            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1839        }
1840    }
1841
1842    private void notifyUiVisibilityChanged() {
1843        try {
1844            mWindowManagerService.statusBarVisibilityChanged(mSystemUiVisibility);
1845        } catch (RemoteException ex) {
1846        }
1847    }
1848
1849    public void topAppWindowChanged(boolean showMenu) {
1850        if (DEBUG) {
1851            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1852        }
1853        if (mNavigationBarView != null) {
1854            mNavigationBarView.setMenuVisibility(showMenu);
1855        }
1856
1857        // See above re: lights-out policy for legacy apps.
1858        if (showMenu) setLightsOn(true);
1859    }
1860
1861    @Override
1862    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1863        boolean altBack = (backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS)
1864            || ((vis & InputMethodService.IME_VISIBLE) != 0);
1865
1866        mCommandQueue.setNavigationIconHints(
1867                altBack ? (mNavigationIconHints | StatusBarManager.NAVIGATION_HINT_BACK_ALT)
1868                        : (mNavigationIconHints & ~StatusBarManager.NAVIGATION_HINT_BACK_ALT));
1869        if (mQS != null) mQS.setImeWindowStatus(vis > 0);
1870    }
1871
1872    @Override
1873    public void setHardKeyboardStatus(boolean available, boolean enabled) {}
1874
1875    @Override
1876    protected void tick(IBinder key, StatusBarNotification n, boolean firstTime) {
1877        // no ticking in lights-out mode
1878        if (!areLightsOn()) return;
1879
1880        // no ticking in Setup
1881        if (!isDeviceProvisioned()) return;
1882
1883        // not for you
1884        if (!notificationIsForCurrentUser(n)) return;
1885
1886        // Show the ticker if one is requested. Also don't do this
1887        // until status bar window is attached to the window manager,
1888        // because...  well, what's the point otherwise?  And trying to
1889        // run a ticker without being attached will crash!
1890        if (n.notification.tickerText != null && mStatusBarWindow.getWindowToken() != null) {
1891            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1892                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1893                mTicker.addEntry(n);
1894            }
1895        }
1896    }
1897
1898    private class MyTicker extends Ticker {
1899        MyTicker(Context context, View sb) {
1900            super(context, sb);
1901        }
1902
1903        @Override
1904        public void tickerStarting() {
1905            mTicking = true;
1906            mStatusBarContents.setVisibility(View.GONE);
1907            mTickerView.setVisibility(View.VISIBLE);
1908            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1909            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1910        }
1911
1912        @Override
1913        public void tickerDone() {
1914            mStatusBarContents.setVisibility(View.VISIBLE);
1915            mTickerView.setVisibility(View.GONE);
1916            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1917            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1918                        mTickingDoneListener));
1919        }
1920
1921        public void tickerHalting() {
1922            mStatusBarContents.setVisibility(View.VISIBLE);
1923            mTickerView.setVisibility(View.GONE);
1924            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1925            // we do not animate the ticker away at this point, just get rid of it (b/6992707)
1926        }
1927    }
1928
1929    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1930        public void onAnimationEnd(Animation animation) {
1931            mTicking = false;
1932        }
1933        public void onAnimationRepeat(Animation animation) {
1934        }
1935        public void onAnimationStart(Animation animation) {
1936        }
1937    };
1938
1939    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1940        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1941        if (listener != null) {
1942            anim.setAnimationListener(listener);
1943        }
1944        return anim;
1945    }
1946
1947    public static String viewInfo(View v) {
1948        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1949                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
1950    }
1951
1952    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1953        synchronized (mQueueLock) {
1954            pw.println("Current Status Bar state:");
1955            pw.println("  mExpandedVisible=" + mExpandedVisible
1956                    + ", mTrackingPosition=" + mTrackingPosition);
1957            pw.println("  mTicking=" + mTicking);
1958            pw.println("  mTracking=" + mTracking);
1959            pw.println("  mNotificationPanel=" +
1960                    ((mNotificationPanel == null)
1961                            ? "null"
1962                            : (mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""))));
1963            pw.println("  mAnimating=" + mAnimating
1964                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1965                    + ", mAnimAccel=" + mAnimAccel);
1966            pw.println("  mAnimLastTimeNanos=" + mAnimLastTimeNanos);
1967            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1968                    + " mViewDelta=" + mViewDelta);
1969            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1970            pw.println("  mPile: " + viewInfo(mPile));
1971            pw.println("  mTickerView: " + viewInfo(mTickerView));
1972            pw.println("  mScrollView: " + viewInfo(mScrollView)
1973                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1974        }
1975
1976        pw.print("  mNavigationBarView=");
1977        if (mNavigationBarView == null) {
1978            pw.println("null");
1979        } else {
1980            mNavigationBarView.dump(fd, pw, args);
1981        }
1982
1983        if (DUMPTRUCK) {
1984            synchronized (mNotificationData) {
1985                int N = mNotificationData.size();
1986                pw.println("  notification icons: " + N);
1987                for (int i=0; i<N; i++) {
1988                    NotificationData.Entry e = mNotificationData.get(i);
1989                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1990                    StatusBarNotification n = e.notification;
1991                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " score=" + n.score);
1992                    pw.println("         notification=" + n.notification);
1993                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1994                }
1995            }
1996
1997            int N = mStatusIcons.getChildCount();
1998            pw.println("  system icons: " + N);
1999            for (int i=0; i<N; i++) {
2000                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
2001                pw.println("    [" + i + "] icon=" + ic);
2002            }
2003
2004            if (false) {
2005                pw.println("see the logcat for a dump of the views we have created.");
2006                // must happen on ui thread
2007                mHandler.post(new Runnable() {
2008                        public void run() {
2009                            mStatusBarView.getLocationOnScreen(mAbsPos);
2010                            Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
2011                                    + ") " + mStatusBarView.getWidth() + "x"
2012                                    + getStatusBarHeight());
2013                            mStatusBarView.debug();
2014                        }
2015                    });
2016            }
2017        }
2018
2019        if (DEBUG_GESTURES) {
2020            pw.print("  status bar gestures: ");
2021            mGestureRec.dump(fd, pw, args);
2022        }
2023
2024        mNetworkController.dump(fd, pw, args);
2025    }
2026
2027    @Override
2028    public void createAndAddWindows() {
2029        addStatusBarWindow();
2030    }
2031
2032    private void addStatusBarWindow() {
2033        // Put up the view
2034        final int height = getStatusBarHeight();
2035
2036        // Now that the status bar window encompasses the sliding panel and its
2037        // translucent backdrop, the entire thing is made TRANSLUCENT and is
2038        // hardware-accelerated.
2039        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
2040                ViewGroup.LayoutParams.MATCH_PARENT,
2041                height,
2042                WindowManager.LayoutParams.TYPE_STATUS_BAR,
2043                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2044                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
2045                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
2046                PixelFormat.TRANSLUCENT);
2047
2048        lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
2049
2050        lp.gravity = getStatusBarGravity();
2051        lp.setTitle("StatusBar");
2052        lp.packageName = mContext.getPackageName();
2053
2054        makeStatusBarView();
2055        mWindowManager.addView(mStatusBarWindow, lp);
2056    }
2057
2058    void setNotificationIconVisibility(boolean visible, int anim) {
2059        int old = mNotificationIcons.getVisibility();
2060        int v = visible ? View.VISIBLE : View.INVISIBLE;
2061        if (old != v) {
2062            mNotificationIcons.setVisibility(v);
2063            mNotificationIcons.startAnimation(loadAnim(anim, null));
2064        }
2065    }
2066
2067    void updateExpandedInvisiblePosition() {
2068        mTrackingPosition = -mDisplayMetrics.heightPixels;
2069    }
2070
2071    static final float saturate(float a) {
2072        return a < 0f ? 0f : (a > 1f ? 1f : a);
2073    }
2074
2075    @Override
2076    protected int getExpandedViewMaxHeight() {
2077        return mDisplayMetrics.heightPixels - mNotificationPanelMarginBottomPx;
2078    }
2079
2080    @Override
2081    public void updateExpandedViewPos(int thingy) {
2082        if (DEBUG) Slog.v(TAG, "updateExpandedViewPos");
2083
2084        // on larger devices, the notification panel is propped open a bit
2085        mNotificationPanel.setMinimumHeight(
2086                (int)(mNotificationPanelMinHeightFrac * mCurrentDisplaySize.y));
2087
2088        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mNotificationPanel.getLayoutParams();
2089        lp.gravity = mNotificationPanelGravity;
2090        lp.leftMargin = mNotificationPanelMarginPx;
2091        mNotificationPanel.setLayoutParams(lp);
2092
2093        if (mSettingsPanel != null) {
2094            lp = (FrameLayout.LayoutParams) mSettingsPanel.getLayoutParams();
2095            lp.gravity = mSettingsPanelGravity;
2096            lp.rightMargin = mNotificationPanelMarginPx;
2097            mSettingsPanel.setLayoutParams(lp);
2098        }
2099
2100        updateCarrierLabelVisibility(false);
2101    }
2102
2103    // called by makeStatusbar and also by PhoneStatusBarView
2104    void updateDisplaySize() {
2105        mDisplay.getMetrics(mDisplayMetrics);
2106        if (DEBUG_GESTURES) {
2107            mGestureRec.tag("display",
2108                    String.format("%dx%d", mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels));
2109        }
2110    }
2111
2112    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
2113        public void onClick(View v) {
2114            synchronized (mNotificationData) {
2115                // animate-swipe all dismissable notifications, then animate the shade closed
2116                int numChildren = mPile.getChildCount();
2117
2118                int scrollTop = mScrollView.getScrollY();
2119                int scrollBottom = scrollTop + mScrollView.getHeight();
2120                final ArrayList<View> snapshot = new ArrayList<View>(numChildren);
2121                for (int i=0; i<numChildren; i++) {
2122                    final View child = mPile.getChildAt(i);
2123                    if (mPile.canChildBeDismissed(child) && child.getBottom() > scrollTop &&
2124                            child.getTop() < scrollBottom) {
2125                        snapshot.add(child);
2126                    }
2127                }
2128                if (snapshot.isEmpty()) {
2129                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
2130                    return;
2131                }
2132                new Thread(new Runnable() {
2133                    @Override
2134                    public void run() {
2135                        // Decrease the delay for every row we animate to give the sense of
2136                        // accelerating the swipes
2137                        final int ROW_DELAY_DECREMENT = 10;
2138                        int currentDelay = 140;
2139                        int totalDelay = 0;
2140
2141                        // Set the shade-animating state to avoid doing other work during
2142                        // all of these animations. In particular, avoid layout and
2143                        // redrawing when collapsing the shade.
2144                        mPile.setViewRemoval(false);
2145
2146                        mPostCollapseCleanup = new Runnable() {
2147                            @Override
2148                            public void run() {
2149                                if (DEBUG) {
2150                                    Slog.v(TAG, "running post-collapse cleanup");
2151                                }
2152                                try {
2153                                    mPile.setViewRemoval(true);
2154                                    mBarService.onClearAllNotifications();
2155                                } catch (Exception ex) { }
2156                            }
2157                        };
2158
2159                        View sampleView = snapshot.get(0);
2160                        int width = sampleView.getWidth();
2161                        final int velocity = width * 8; // 1000/8 = 125 ms duration
2162                        for (final View _v : snapshot) {
2163                            mHandler.postDelayed(new Runnable() {
2164                                @Override
2165                                public void run() {
2166                                    mPile.dismissRowAnimated(_v, velocity);
2167                                }
2168                            }, totalDelay);
2169                            currentDelay = Math.max(50, currentDelay - ROW_DELAY_DECREMENT);
2170                            totalDelay += currentDelay;
2171                        }
2172                        // Delay the collapse animation until after all swipe animations have
2173                        // finished. Provide some buffer because there may be some extra delay
2174                        // before actually starting each swipe animation. Ideally, we'd
2175                        // synchronize the end of those animations with the start of the collaps
2176                        // exactly.
2177                        mHandler.postDelayed(new Runnable() {
2178                            @Override
2179                            public void run() {
2180                                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
2181                            }
2182                        }, totalDelay + 225);
2183                    }
2184                }).start();
2185            }
2186        }
2187    };
2188
2189    public void startActivityDismissingKeyguard(Intent intent, boolean onlyProvisioned) {
2190        if (onlyProvisioned && !isDeviceProvisioned()) return;
2191        try {
2192            // Dismiss the lock screen when Settings starts.
2193            ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
2194        } catch (RemoteException e) {
2195        }
2196        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2197        mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
2198        animateCollapsePanels();
2199    }
2200
2201    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
2202        public void onClick(View v) {
2203            if (mHasSettingsPanel) {
2204                animateExpandSettingsPanel();
2205            } else {
2206                startActivityDismissingKeyguard(
2207                        new Intent(android.provider.Settings.ACTION_SETTINGS), true);
2208            }
2209        }
2210    };
2211
2212    private View.OnClickListener mClockClickListener = new View.OnClickListener() {
2213        public void onClick(View v) {
2214            startActivityDismissingKeyguard(
2215                    new Intent(Intent.ACTION_QUICK_CLOCK), true); // have fun, everyone
2216        }
2217    };
2218
2219    private View.OnClickListener mNotificationButtonListener = new View.OnClickListener() {
2220        public void onClick(View v) {
2221            animateExpandNotificationsPanel();
2222        }
2223    };
2224
2225    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2226        public void onReceive(Context context, Intent intent) {
2227            Slog.v(TAG, "onReceive: " + intent);
2228            String action = intent.getAction();
2229            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2230                int flags = CommandQueue.FLAG_EXCLUDE_NONE;
2231                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2232                    String reason = intent.getStringExtra("reason");
2233                    if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
2234                        flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
2235                    }
2236                }
2237                animateCollapsePanels(flags);
2238            }
2239            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
2240                // no waiting!
2241                makeExpandedInvisible();
2242            }
2243            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
2244                if (DEBUG) {
2245                    Slog.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
2246                }
2247                mDisplay.getSize(mCurrentDisplaySize);
2248
2249                updateResources();
2250                repositionNavigationBar();
2251                updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
2252                updateShowSearchHoldoff();
2253            }
2254            else if (Intent.ACTION_SCREEN_ON.equals(action)) {
2255                // work around problem where mDisplay.getRotation() is not stable while screen is off (bug 7086018)
2256                repositionNavigationBar();
2257            }
2258        }
2259    };
2260
2261    @Override
2262    public void userSwitched(int newUserId) {
2263        if (MULTIUSER_DEBUG) mNotificationPanelDebugText.setText("USER " + newUserId);
2264        animateCollapsePanels();
2265        updateNotificationIcons();
2266        resetUserSetupObserver();
2267    }
2268
2269    private void resetUserSetupObserver() {
2270        mContext.getContentResolver().unregisterContentObserver(mUserSetupObserver);
2271        mUserSetupObserver.onChange(false);
2272        mContext.getContentResolver().registerContentObserver(
2273                Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), true,
2274                mUserSetupObserver,
2275                mCurrentUserId);
2276    }
2277
2278    private void setIntruderAlertVisibility(boolean vis) {
2279        if (!ENABLE_INTRUDERS) return;
2280        if (DEBUG) {
2281            Slog.v(TAG, (vis ? "showing" : "hiding") + " intruder alert window");
2282        }
2283        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
2284    }
2285
2286    public void dismissIntruder() {
2287        if (mCurrentlyIntrudingNotification == null) return;
2288
2289        try {
2290            mBarService.onNotificationClear(
2291                    mCurrentlyIntrudingNotification.pkg,
2292                    mCurrentlyIntrudingNotification.tag,
2293                    mCurrentlyIntrudingNotification.id);
2294        } catch (android.os.RemoteException ex) {
2295            // oh well
2296        }
2297    }
2298
2299    /**
2300     * Reload some of our resources when the configuration changes.
2301     *
2302     * We don't reload everything when the configuration changes -- we probably
2303     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
2304     * meantime, just update the things that we know change.
2305     */
2306    void updateResources() {
2307        final Context context = mContext;
2308        final Resources res = context.getResources();
2309
2310        if (mClearButton instanceof TextView) {
2311            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
2312        }
2313
2314        // Update the QuickSettings container
2315        if (mQS != null) mQS.updateResources();
2316
2317        loadDimens();
2318    }
2319
2320    protected void loadDimens() {
2321        final Resources res = mContext.getResources();
2322
2323        mNaturalBarHeight = res.getDimensionPixelSize(
2324                com.android.internal.R.dimen.status_bar_height);
2325
2326        int newIconSize = res.getDimensionPixelSize(
2327            com.android.internal.R.dimen.status_bar_icon_size);
2328        int newIconHPadding = res.getDimensionPixelSize(
2329            R.dimen.status_bar_icon_padding);
2330
2331        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
2332//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
2333            mIconHPadding = newIconHPadding;
2334            mIconSize = newIconSize;
2335            //reloadAllNotificationIcons(); // reload the tray
2336        }
2337
2338        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
2339
2340        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
2341        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
2342        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
2343        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
2344
2345        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
2346        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
2347
2348        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
2349        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
2350
2351        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
2352
2353        mFlingGestureMaxOutputVelocityPx = res.getDimension(R.dimen.fling_gesture_max_output_velocity);
2354
2355        mNotificationPanelMarginBottomPx
2356            = (int) res.getDimension(R.dimen.notification_panel_margin_bottom);
2357        mNotificationPanelMarginPx
2358            = (int) res.getDimension(R.dimen.notification_panel_margin_left);
2359        mNotificationPanelGravity = res.getInteger(R.integer.notification_panel_layout_gravity);
2360        if (mNotificationPanelGravity <= 0) {
2361            mNotificationPanelGravity = Gravity.LEFT | Gravity.TOP;
2362        }
2363        mSettingsPanelGravity = res.getInteger(R.integer.settings_panel_layout_gravity);
2364        if (mSettingsPanelGravity <= 0) {
2365            mSettingsPanelGravity = Gravity.RIGHT | Gravity.TOP;
2366        }
2367
2368        mCarrierLabelHeight = res.getDimensionPixelSize(R.dimen.carrier_label_height);
2369        mNotificationHeaderHeight = res.getDimensionPixelSize(R.dimen.notification_panel_header_height);
2370
2371        mNotificationPanelMinHeightFrac = res.getFraction(R.dimen.notification_panel_min_height_frac, 1, 1);
2372        if (mNotificationPanelMinHeightFrac < 0f || mNotificationPanelMinHeightFrac > 1f) {
2373            mNotificationPanelMinHeightFrac = 0f;
2374        }
2375
2376        if (false) Slog.v(TAG, "updateResources");
2377    }
2378
2379    //
2380    // tracing
2381    //
2382
2383    void postStartTracing() {
2384        mHandler.postDelayed(mStartTracing, 3000);
2385    }
2386
2387    void vibrate() {
2388        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
2389                Context.VIBRATOR_SERVICE);
2390        vib.vibrate(250);
2391    }
2392
2393    Runnable mStartTracing = new Runnable() {
2394        public void run() {
2395            vibrate();
2396            SystemClock.sleep(250);
2397            Slog.d(TAG, "startTracing");
2398            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
2399            mHandler.postDelayed(mStopTracing, 10000);
2400        }
2401    };
2402
2403    Runnable mStopTracing = new Runnable() {
2404        public void run() {
2405            android.os.Debug.stopMethodTracing();
2406            Slog.d(TAG, "stopTracing");
2407            vibrate();
2408        }
2409    };
2410
2411    @Override
2412    protected void haltTicker() {
2413        mTicker.halt();
2414    }
2415
2416    @Override
2417    protected boolean shouldDisableNavbarGestures() {
2418        return mExpandedVisible || (mDisabled & StatusBarManager.DISABLE_HOME) != 0;
2419    }
2420
2421    private static class FastColorDrawable extends Drawable {
2422        private final int mColor;
2423
2424        public FastColorDrawable(int color) {
2425            mColor = 0xff000000 | color;
2426        }
2427
2428        @Override
2429        public void draw(Canvas canvas) {
2430            canvas.drawColor(mColor, PorterDuff.Mode.SRC);
2431        }
2432
2433        @Override
2434        public void setAlpha(int alpha) {
2435        }
2436
2437        @Override
2438        public void setColorFilter(ColorFilter cf) {
2439        }
2440
2441        @Override
2442        public int getOpacity() {
2443            return PixelFormat.OPAQUE;
2444        }
2445
2446        @Override
2447        public void setBounds(int left, int top, int right, int bottom) {
2448        }
2449
2450        @Override
2451        public void setBounds(Rect bounds) {
2452        }
2453    }
2454}
2455