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