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