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