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