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