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