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