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