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