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